aiida.common documentation¶
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
-
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).
Note
The order of the internal variable _sorted_datastates is used.
Parameters: - 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.
Returns: a sorted list of the given data states.
Raises: ValueError – if any of the given states is not a valid state.
Constants¶
This module defines the (physical) constants that are used throughout the code. Note that
Exceptions¶
-
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.
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).
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.
-
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: 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')
: Nonea.get('def_field','whatever')
: ‘whatever’- Note that
a.defaultkeys()
does NOT contain ‘def_field’
if we do
a.def_field = None
, then the behavior becomesa.get('def_field')
: Nonea.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.
-
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')
Folders¶
-
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.
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).
-
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
(src_filelike, dest_name)[source]¶ Create a file from a file-like object.
Note: 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.
Parameters: - 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.
- src_filelike – the file-like object (e.g., if you have
a string called s, you can pass
-
create_symlink
(src, name)[source]¶ 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.
-
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.
-
mode_dir
¶ Return the mode with which the folders should be created
-
mode_file
¶ 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_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]¶ 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.
-
section
¶ The section to which this folder belongs.
-
subfolder
¶ The subfolder within the section/uuid folder.
-
uuid
¶ The uuid to which this folder belongs.
-
-
class
aiida.common.folders.
SandboxFolder
[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.
Todo
Implement check of whether the folder has been removed.
Orbitals¶
-
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
Parameters: - position – the absolute position (three floats) units in angstrom
- x_orientation – x,y,z unit vector defining polar angle theta in spherical coordinates unitless
- z_orientation – x,y,z unit vector defining azimuthal angle phi in spherical coordinates unitless
- orientation_spin – x,y,z unit vector defining the spin orientation unitless
- diffusivity – Float controls the radial term in orbital equation units are reciprocal Angstrom.
- module_name – internal parameter, stores orbital type
-
aiida.common.orbital.
OrbitalFactory
(module)[source]¶ 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.
RealHydrogen¶
-
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 http://www.wannier.org/doc/user_guide.pdf A brief description of what is meant by each of these labels:
Parameters: - radial_nodes – the number of radial nodes (or inflections) if no radial nodes are supplied, defaults to 0
- angular_momentum – Angular quantum number, using real orbitals
- magnetic_number – Magnetic quantum number, using real orbitals
- spin – spin, up (1) down (-1) or unspecified (0)
The conventions regarding L and M correpsond to those used in wannier90 for all L greater than 0 the orbital is not hyrbridized see table 3.1 and for L less than 0 the orbital is hybridized see table 3.2. M then indexes all the possible orbitals from 0 to 2L for L > 0 and from 0 to (-L) for L < 0.
-
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, 'aiida.orm.calculation.job', suffix='Calculation') # <- finds cp also if new style BaseFactory('job.quantumespresso.cp', Calculation, 'aiida.orm.calculation') <- will find cp only if old style
-
aiida.common.pluginloader.
all_plugins
(category)[source]¶ find old and new plugins
If both are available for a given name, the old style plugin takes precedence.
-
aiida.common.pluginloader.
entry_point_tpstr_from
(plugin_class)[source]¶ 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
-
aiida.common.pluginloader.
existing_plugins
(base_class, plugins_module_name, max_depth=5, suffix=None)[source]¶ Return a list of plugin names, old and new style
Refer to aiida.common.old_pluginloader.existing_plugins for more info on behaviour for old style plugins.
If no old style plugins are found and the plugins_module_name is mappable to a group of entry points, aiida.common.pluginloader.plugin_list is returned
-
aiida.common.pluginloader.
get_class_to_entry_point_map
(short_group_name=False)[source]¶ 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.
Parameters: - category – the plugin category to load the plugin from, e.g. ‘transport’.
- 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
Utilities¶
-
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)
-
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)[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(): @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!
-
aiida.common.utils.
conv_to_fortran
(val)[source]¶ Parameters: val – the value to be read and converted to a Fortran-friendly string.
-
aiida.common.utils.
conv_to_fortran_withlists
(val)[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.
-
aiida.common.utils.
create_display_name
(field)[source]¶ Given a string, creates the suitable “default” display name: replace underscores with spaces, and capitalize each word.
Returns: the converted string
-
aiida.common.utils.
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.utils.
flatten_list
(value)[source]¶ 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
-
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_configured_user_email
()[source]¶ Return the email (that is used as the username) configured during the first verdi install.
-
aiida.common.utils.
get_extremas_from_positions
(positions)[source]¶ 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
-
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
(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_object_string
(obj)[source]¶ 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
-
aiida.common.utils.
get_repository_folder
(subfolder=None)[source]¶ 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.
- Args:
- provided_string: the string to compare allowed_strings: a list of valid strings
- Returns:
- 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.
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.
gunzip_string
(string)[source]¶ Gunzip string contents.
Parameters: string – a gzipped string Returns: a string
-
aiida.common.utils.
gzip_string
(string)[source]¶ Gzip string contents.
Parameters: string – a string Returns: a gzipped string
-
aiida.common.utils.
issingular
(singularForm)[source]¶ 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
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.
md5_file
(filename, block_size_factor=128)[source]¶ Open a file and return its md5sum (hexdigested).
Parameters: - 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
, wheremd5.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.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.
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).
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
, wheresha1.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.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.