Utility Functions/Classes

Custom Datatypes

This module defines subclasses of UserDict and UserList to be able to prevent unintended modifications

masci_tools.util.lockable_containers.LockContainer(lock_object)[source]

Contextmanager for temporarily locking a lockable object. Object is unfrozen when exiting with block

Parameters:

lock_object (LockableList[Any] | LockableDict[Any, Any]) – lockable container (not yet frozen)

Return type:

Iterator[None]

class masci_tools.util.lockable_containers.LockableDict(*args, recursive=True, **kwargs)[source]

Subclass of UserDict, which can prevent modifications to itself. Raises RuntimeError if modification is attempted.

Use LockableDict.freeze() to enforce. LockableDict.get_unlocked() returns a copy of the locked object with builtin lists and dicts

Parameters:

recursive (bool) – bool if True (default) all subitems (lists or dicts) are converted into their lockable counterparts

All other args or kwargs will be passed on to initialize the UserDict

IMPORTANT NOTE:

This is not a direct subclass of dict. So isinstance(a, dict) will be False if a is an LockableDict

freeze()[source]

Freezes the object. This prevents further modifications

Return type:

None

get_unlocked()[source]

Get copy of object with builtin lists and dicts

Return type:

dict[TypeVar(S), TypeVar(T_co, covariant=True)]

property locked: bool

Returns whether the object is locked

class masci_tools.util.lockable_containers.LockableList(*args, recursive=True, **kwargs)[source]

Subclass of UserList, which can prevent modifications to itself. Raises RuntimeError if modification is attempted.

Use LockableList.freeze() to enforce. LockableList.get_unlocked() returns a copy of the locked object with builtin lists and dicts

Parameters:

recursive (bool) – bool if True (default) all subitems (lists or dicts) are converted into their lockable counterparts

All other args or kwargs will be passed on to initialize the UserList

IMPORTANT NOTE:

This is not a direct subclass of list. So isinstance(a, list) will be False if a is an LockableList

append(item)[source]

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

Return type:

None

clear()[source]

Clear the list

Return type:

None

extend(other)[source]

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

Return type:

None

freeze()[source]

Freezes the object. This prevents further modifications

Return type:

None

get_unlocked()[source]

Get copy of object with builtin lists and dicts

Return type:

list[TypeVar(T)]

insert(i, item)[source]

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

Return type:

None

property locked: bool

Returns whether the object is locked

pop(i=-1)[source]

return the value at index i (default last) and remove it from list

Return type:

TypeVar(T)

remove(item)[source]

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

Return type:

None

reverse()[source]

S.reverse() – reverse IN PLACE

Return type:

None

masci_tools.util.lockable_containers.S

Type variable for the key type of the dictionary

alias of TypeVar(‘S’)

masci_tools.util.lockable_containers.T

Type variable for the value type of the list

alias of TypeVar(‘T’)

masci_tools.util.lockable_containers.T_co

Type variable for the value type of the dictionary

alias of TypeVar(‘T_co’, covariant=True)

This module defines a small helper class to make case insensitive dictionary lookups available naturally

class masci_tools.util.case_insensitive_dict.CaseInsensitiveDict(*args, upper=False, recursive=True, **kwargs)[source]

Dict with case insensitive lookup. Used in Schema dicts to make finding paths for tags and attributes easier. Does not preserve the case of the inserted key. Does not support case insensitive lookups in nested dicts Subclass of masci_tools.util.lockable_containers.LockableDict. So can be frozen via the`freeze()` method

Parameters:

upper (bool) – bool if True the method upper() will be used instead of lower() to normalize keys

All other args or kwargs will be passed on to initialize the UserDict

IMPORTANT NOTE:

This is not a direct subcalss of dict. So isinstance(a, dict) will be False if a is an CaseInsensitiveDict

class masci_tools.util.case_insensitive_dict.CaseInsensitiveFrozenSet(iterable=None, upper=False)[source]

Frozenset (i.e. immutable set) with case insensitive membership tests. Used in Schema dicts in tag_info entries to make flexible classification easy Preserves the case of the entered keys (original_case() returns the case of the first encounter)

Parameters:

iterable (Optional[Iterable[TypeVar(T_co, covariant=True)]]) – iterable only containing str

Note:

There might be subtle differences to expected behaviour with the methods __radd__, __ror__, and so on

difference(*others)[source]

Return the difference of two or more sets as a new set.

(i.e. all elements that are in this set but not the others.)

Return type:

CaseInsensitiveFrozenSet[TypeVar(T_co, covariant=True)]

intersection(*others)[source]

Return the intersection of two sets as a new set.

(i.e. all elements that are in both sets.)

Return type:

CaseInsensitiveFrozenSet[TypeVar(T_co, covariant=True)]

isdisjoint(other)[source]

Return True if two sets have a null intersection.

Return type:

bool

issubset(other)[source]

Report whether another set contains this set.

Return type:

bool

issuperset(other)[source]

Report whether this set contains another set.

Return type:

bool

symmetric_difference(other)[source]

Return the symmetric difference of two sets as a new set.

(i.e. all elements that are in exactly one of the sets.)

Return type:

CaseInsensitiveFrozenSet[TypeVar(T_co, covariant=True)]

union(*others)[source]

Return the union of sets as a new set.

(i.e. all elements that are in either set.)

Return type:

CaseInsensitiveFrozenSet[Union[TypeVar(T_co, covariant=True), TypeVar(_S)]]

masci_tools.util.case_insensitive_dict.S

Generic Type

alias of TypeVar(‘S’)

masci_tools.util.case_insensitive_dict.T_co

Generic Type

alias of TypeVar(‘T_co’, covariant=True)

This module defines some aliases used in typing

masci_tools.util.typing.FileLike

Type used for functions accepting file-like objects, i.e. handles or file paths

alias of Union[str, bytes, Path, PathLike, IO[Any]]

masci_tools.util.typing.TXPathLike

Type for xpath expressions

alias of TypeVar(‘TXPathLike’, bound=Union[str, bytes, XPath, XPathBuilder])

masci_tools.util.typing.XMLFileLike

Type used for functions accepting xml-file-like objects, i.e. handles or file paths or already parsed xml objects

alias of Union[_ElementTree, _Element, str, bytes, Path, PathLike, IO[Any]]

masci_tools.util.typing.XMLLike

Type used for functions accepting xml objects from lxml

alias of Union[_Element, _ElementTree]

masci_tools.util.typing.XPathLike

Type for xpath expressions

alias of Union[str, bytes, XPath, XPathBuilder]

Common XML utility

Common functions for parsing input/output files or XMLschemas from FLEUR

masci_tools.util.xml.common_functions.T

Generic Type

alias of TypeVar(‘T’)

masci_tools.util.xml.common_functions.abs_to_rel_xpath(xpath, new_root)[source]

Convert a given xpath to be relative from a tag appearing in the original xpath.

Parameters:
  • xpath (str) – str of the xpath to convert

  • new_root (str) – str of the tag from which the new xpath should be relative

Return type:

str

Returns:

str of the relative xpath

masci_tools.util.xml.common_functions.add_tag(xpath, tag)[source]

Add tag to xpath

Note

etree.XPath objects could lose context in here, i.e. non-default options passed at init

Parameters:
Return type:

TypeVar(TXPathLike, bound= Union[str, bytes, XPath, XPathBuilder])

Returns:

xpath with the form {old_xpath}/tag

masci_tools.util.xml.common_functions.check_complex_xpath(node, base_xpath, complex_xpath)[source]

Check that the given complex xpath produces a subset of the results for the simple xpath

Parameters:
Raises:

ValueError – If the complex_xpath does not produce a subset of the results of the base_xpath

Return type:

None

masci_tools.util.xml.common_functions.clear_xml(tree)[source]

Removes comments and executes xinclude tags of an xml tree.

Parameters:

tree (_ElementTree) – an xml-tree which will be processed

Return type:

tuple[_ElementTree, set[str]]

Returns:

cleared_tree, an xmltree without comments and with replaced xinclude tags

masci_tools.util.xml.common_functions.contains_tag(xpath, tag)[source]

Return whether a given xpath contains a given tag This assumes that predicates of xpaths can’t be nested since otherwise the regex for removing them could fail

This function will only return True if one of the tags exactly matches the tag argument not if one tag contains the given name in it’s name

Parameters:
Return type:

bool

Returns:

whether a tag is contained in the xpath

masci_tools.util.xml.common_functions.eval_xpath(node, xpath, logger=None, list_return=False, namespaces=None, **variables)[source]

Tries to evaluate an xpath expression. If it fails it logs it. If a absolute path is given (starting with ‘/’) and the tag of the node does not match the root. It will try to find the tag in the path and convert it into a relative path

Parameters:
  • node – root node of an etree

  • xpath – xpath expression (relative, or absolute)

  • logger – logger object for logging warnings, errors, if not provided all errors will be raised

  • list_return – if True, the returned quantity is always a list even if only one element is in it

  • namespaces – dict, passed to namespaces argument in xpath call

Returns:

text, attribute or a node list

masci_tools.util.xml.common_functions.get_inpgen_comments(xmltree)[source]

Get the XML comment element appended after the root of the inp.xml file

These contain at the moment the inpgen command line and the content of the inpgen file

Parameters:

xmltree (_ElementTree) – representation of the inp.xml

Return type:

list[_Element]

Returns:

list of XML comments, which appear after the fleurInput tag

masci_tools.util.xml.common_functions.get_xml_attribute(node, attributename, logger=None)[source]

Get an attribute value from a node.

Parameters:
  • node (_Element) – a node from etree

  • attributename (str) – a string with the attribute name.

  • logger (Optional[Logger]) – logger object for logging warnings, errors, if not provided all errors will be raised

Return type:

Optional[str]

Returns:

either attributevalue, or None

masci_tools.util.xml.common_functions.is_valid_tag(tag)[source]

Return whether the given string is a valid XML tag name

Parameters:

tag (str) – tag to check

Return type:

bool

masci_tools.util.xml.common_functions.normalize_xmllike(xmllike)[source]

Returns the root of the xmltree

Return type:

_Element

masci_tools.util.xml.common_functions.process_xpath_argument(simple_xpath, complex_xpath, filters)[source]

Process the simple and complex Xpath expressions and given filters Used for unifying the logic for all xml setters/evaluators using these arguments

Parameters:
Return type:

Union[str, bytes, XPath, XPathBuilder]

Returns:

Complex XPath expression

masci_tools.util.xml.common_functions.readd_inpgen_comments(xmltree, comments)[source]

Add the given comments after the fleurInput tag of the inp.xml

These contain at the moment the inpgen command line and the content of the inpgen file

Parameters:
Return type:

_ElementTree

masci_tools.util.xml.common_functions.reverse_xinclude(xmltree, schema_dict, included_tags, **kwargs)[source]

DEPRECATED ALIAS: Moved to masci_tools.util.schema_dict_util

Split the xmltree back up according to the given included tags. The original xmltree will be returned with the corresponding xinclude tags and the included trees are returned in a dict mapping the inserted filename to the extracted tree

Tags for which no known filename is known are returned under unknown-1.xml, … The following tags have known filenames:

  • relaxation: relax.xml

  • kPointLists: kpts.xml

  • symmetryOperations: sym.xml

  • atomSpecies: species.xml

  • atomGroups: atoms.xml

Additional mappings can be given in the keyword arguments

Parameters:
  • xmltree – an xml-tree which will be processed

  • schema_dict – Schema dictionary containing all the necessary information

  • included_tags – Iterable of str, containing the names of the tags to be excluded

Returns:

xmltree with the inseerted xinclude tags and a dict mapping the filenames to the excluded trees

Raises:

ValueError – if the tag can not be found in the given xmltree

masci_tools.util.xml.common_functions.serialize_xml_objects(args, kwargs)[source]

Convert every XML element/tree in the given args/kwargs to string using lxml.etree.tostring()

Parameters:
Return type:

tuple[tuple[Any, ...], dict[str, Any]]

masci_tools.util.xml.common_functions.split_off_attrib(xpath)[source]

Splits off attribute of the given xpath (part after @)

Note

etree.XPath objects could lose context in here, i.e. non-default options passed at init

Parameters:

xpath (TypeVar(TXPathLike, bound= Union[str, bytes, XPath, XPathBuilder])) – xpath to split up

Return type:

tuple[TypeVar(TXPathLike, bound= Union[str, bytes, XPath, XPathBuilder]), str]

masci_tools.util.xml.common_functions.split_off_tag(xpath)[source]

Splits off the last part of the given xpath

Note

etree.XPath objects could lose context in here, i.e. non-default options passed at init

Parameters:

xpath (TypeVar(TXPathLike, bound= Union[str, bytes, XPath, XPathBuilder])) – xpath to split up

Return type:

tuple[TypeVar(TXPathLike, bound= Union[str, bytes, XPath, XPathBuilder]), str]

masci_tools.util.xml.common_functions.validate_xml(xmltree, schema, error_header='File does not validate')[source]

Checks a given xmltree against a schema and produces a nice error message with all the validation errors collected

Parameters:
  • xmltree (_ElementTree) – xmltree of the file to validate

  • schema (XMLSchema) – etree.XMLSchema to validate against

  • error_header (str) – str to lead a evtl error message with

Raises:

etree.DocumentInvalid if the schema does not validate

Return type:

None

Common functions for converting types to and from XML files

masci_tools.util.xml.converters.convert_fleur_electronconfig(econfig_element)[source]

Convert electronConfig tag to eConfig string

Return type:

str

masci_tools.util.xml.converters.convert_fleur_lo(loelements, allow_special_los=True)[source]

Converts lo xml elements from the inp.xml file into a lo string for the inpgen

Return type:

str

masci_tools.util.xml.converters.convert_from_fortran_bool(stringbool)[source]

Converts a string in this case (‘T’, ‘F’, or ‘t’, ‘f’) to True or False

Parameters:

stringbool (str | bool) – a string (‘t’, ‘f’, ‘F’, ‘T’)

Return type:

bool

Returns:

boolean (either True or False)

masci_tools.util.xml.converters.convert_from_fortran_complex(number_str)[source]

Converts a string of the form (float,float) to a complex number

Parameters:

number_str (str) – string to convert

Return type:

complex

Returns:

complex number

masci_tools.util.xml.converters.convert_from_xml(xmlstring, schema_dict, name, text=False, constants=None, logger=None, list_return=False)[source]

Tries to converts a given string to the types specified in the schema_dict. First succeeded conversion will be returned

If no logger is given and a attribute cannot be converted an error is raised

Parameters:
  • stringattribute – str, Attribute to convert.

  • schema_dict (SchemaDict) – Schema dictionary containing all the information

  • name (str) – name of the attribute or element

  • text (bool) – bool, decides whether to take the definitions for text or attributes

  • constants (Optional[dict[str, float]]) – dict, of constants defined in fleur input

  • logger (Optional[Logger]) – logger object for logging warnings if given the errors are logged and the list is returned with the unconverted values otherwise a error is raised, when the first conversion fails

  • list_return (bool) – if True, the returned quantity is always a list even if only one element is in it

Return type:

tuple[Union[int, float, bool, str, complex, list[Union[int, float, bool, str, complex]], list[Union[int, float, bool, str, complex, list[Union[int, float, bool, str, complex]]]]], bool]

Returns:

The converted value of the first successful conversion

masci_tools.util.xml.converters.convert_from_xml_explicit(xmlstring, definitions, constants=None, logger=None, list_return=False)[source]

Tries to converts a given string to the types given in definitions. First succeeded conversion will be returned

If no logger is given and a attribute cannot be converted an error is raised

Parameters:
  • stringattribute – str, Attribute to convert.

  • definitions (list[AttributeType]) – list of AttributeType definitions

  • constants (Optional[dict[str, float]]) – dict, of constants defined in fleur input

  • logger (Optional[Logger]) – logger object for logging warnings if given the errors are logged and the list is returned with the unconverted values otherwise a error is raised, when the first conversion fails

  • list_return (bool) – if True, the returned quantity is always a list even if only one element is in it

Return type:

tuple[Union[int, float, bool, str, complex, list[Union[int, float, bool, str, complex]], list[Union[int, float, bool, str, complex, list[Union[int, float, bool, str, complex]]]]], bool]

Returns:

The converted value of the first successful conversion

masci_tools.util.xml.converters.convert_from_xml_single_values(xmlstring, possible_types, constants=None, logger=None)[source]

Tries to converts a given string attribute to the types given in possible_types. First succeeded conversion will be returned

If no logger is given and a attribute cannot be converted an error is raised

Parameters:
  • stringattribute – str, Attribute to convert.

  • possible_types (tuple[Literal['int', 'switch', 'string', 'float', 'float_expression', 'complex'], ...]) – list of str What types it will try to convert to

  • constants (Optional[dict[str, float]]) – dict, of constants defined in fleur input

  • logger (Optional[Logger]) – logger object for logging warnings if given the errors are logged and the list is returned with the unconverted values otherwise a error is raised, when the first conversion fails

  • list_return – if True, the returned quantity is always a list even if only one element is in it

Return type:

tuple[list[Union[int, float, bool, str, complex]], bool]

Returns:

The converted value of the first successful conversion

masci_tools.util.xml.converters.convert_str_version_number(version_str)[source]

Convert the version number as a integer for easy comparisons

Parameters:

version_str (str) – str of the version number, e.g. ‘0.33’

Return type:

tuple[int, int]

Returns:

tuple of ints representing the version str

masci_tools.util.xml.converters.convert_to_fortran_bool(boolean)[source]

Converts a Boolean as string to the format defined in the input

Parameters:

boolean (bool | str) – either a boolean or a string (‘True’, ‘False’, ‘F’, ‘T’)

Return type:

Literal['T', 'F']

Returns:

a string (either ‘t’ or ‘f’)

masci_tools.util.xml.converters.convert_to_xml(value, schema_dict, name, text=False, logger=None, list_return=False)[source]

Tries to converts a given string to the types specified in the schema_dict. First succeeded conversion will be returned

If no logger is given and a attribute cannot be converted an error is raised

Parameters:
  • stringattribute – str, Attribute to convert.

  • schema_dict (SchemaDict) – Schema dictionary containing all the information

  • name (str) – name of the attribute or element

  • text (bool) – bool, decides whether to take the definitions for text or attributes

  • constants – dict, of constants defined in fleur input

  • logger (Optional[Logger]) – logger object for logging warnings if given the errors are logged and the list is returned with the unconverted values otherwise a error is raised, when the first conversion fails

  • list_return (bool) – if True, the returned quantity is always a list even if only one element is in it

Return type:

tuple[str | list[str], bool]

Returns:

The converted value of the first successful conversion

masci_tools.util.xml.converters.convert_to_xml_explicit(value, definitions, logger=None, float_format='.10', list_return=False)[source]

Tries to convert a given list of values to str for a xml file based on the definitions (length and type). First succeeded conversion will be returned

Parameters:
  • textvalue – value to convert

  • definitions (list[AttributeType]) – list of AttributeType definitions

  • logger (Optional[Logger]) – logger object for logging warnings if given the errors are logged and the list is returned with the unconverted values otherwise a error is raised, when the first conversion fails

  • list_return (bool) – if True, the returned quantity is always a list even if only one element is in it

Return type:

tuple[str | list[str], bool]

Returns:

The converted value of the first successful conversion

masci_tools.util.xml.converters.convert_to_xml_single_values(value, possible_types, logger=None, float_format='.10')[source]

Tries to converts a given attributevalue to a string for a xml file according to the types given in possible_types. First succeeded conversion will be returned

Parameters:
  • value (Union[Any, Iterable[Any]]) – value to convert.

  • possible_types (tuple[Literal['int', 'switch', 'string', 'float', 'float_expression', 'complex'], ...]) – list of str What types it will try to convert from

  • logger (Optional[Logger]) – logger object for logging warnings if given the errors are logged and the list is returned with the unconverted values otherwise a error is raised, when the first conversion fails

  • list_return – if True, the returned quantity is always a list even if only one element is in it

Return type:

tuple[list[str], bool]

Returns:

The converted str of the value of the first successful conversion

This module contains Classes for building complex XPath expressions based on general attribute conditions from simple XPath expressions

masci_tools.util.xml.xpathbuilder.FilterType

Type for filters argument for XPathBuilder

alias of Dict[str, Any]

class masci_tools.util.xml.xpathbuilder.XPathBuilder(simple_path, filters=None, compile_path=False, strict=False, **kwargs)[source]

Class for building a complex xpath (restricted to adding filters) from a simple xpath expression

Note

passing in an etree.XPath object will not respect the options passed into it. Only the kwargs in __init__ are used to compile the path if compile_path=True

Note

Filters/Constraints (or predicates like they are called for XPaths) can either be added by providing the filters argument in the constructor or by calling the add_filter() method.

The filters argument is a dictionary with the tag names, where to apply the condition, as keys and the condition as values while the add_filter() method takes these as it’s two arguments. The tag name has to be a part of the original simple xpath expression. The conditition is a dictionary with one key specifying the kind of condition and the value for the condition. The condition can also be the name of an attribute or path, in which case the value can be another condition dictionary. The following conditions operators i.e. keys in the dictionary are supported:

  • =/==: equal to

  • !=: not equal to

  • <: less than

  • >: greater than

  • <=: less than or equal to

  • >=: greater than or equal to

  • contains: attribute/tag contains the given value (case sensitive)

  • not-contains: attribute/tag does not contains the given value

  • starts-with: attribute/tag starts with the given value (case sensitive)

  • ends-with: attribute/tag ends with the given value (case sensitive)

  • index: Select tags based on their index in the parent tag (either explicit index or another condition)

  • has: Select tags based on the presence of the given attribute/tag

  • has-not: Select tags based on the absence of the given attribute/tag

  • number-nodes: Compute the number of nodes in the previous path and select based on further criteria

  • and: Provide multiple conditions in a list joined by and

  • or: Provide multiple conditions in a list joined by or

  • in: Select tags if the value of the path is in a given list of values

  • not-in: Select tags if the value of the path is not in a given list of values

  • <string>: All other strings are interpreted as paths to attributes/tags specifying conditions on their value

  • <tuple of paths>: Multiple strings are interpreted as multiple node sets, which are joined with |

Example:

from masci_tools.util.xml.xpathbuilder import XPathBuilder

# XPath selecting all lo tags for SCLO type LOs and Iron species
xpath = XPathBuilder('/fleurInput/atomSpecies/species/lo',
                     filters = {'species': {
                                    'name': {'contains': 'Fe'},
                                },
                                'lo': {
                                    'type': 'SCLO'
                                }
                            })
Parameters:
  • simple_path (str | bytes | XPath) – basic simple XPath expression to start from

  • filters (Optional[dict[str, Dict[str, Any]]]) – dictionary with filters

  • compile_path (bool) – bool if True the path property will be compiled as etree.XPath

  • strict (bool) – bool if True the __str__ conversion will raise an error

Other Kwargs will be passed on to the etree.XPath compilation if compile_path=True

add_filter(tag, conditions)[source]

Add a filter to the filters dictionary

Parameters:
  • tag (str) – str name of the tag name to add a filter to

  • conditions (Union[Dict[str, Any], Any]) – dictionary specifying the filter

Return type:

None

append_tag(tag)[source]

Append another tag to the end of the simple xpath expression

Parameters:

tag (str) – str name of the tag to append

Return type:

None

get_predicate(tag, condition, compound=False, path='.', process_path=False)[source]

Construct the predicate for the given tag and condition

Parameters:
  • tag (str) – str name of the tag

  • condition (Any) – condition specified, either dict or single value

  • compound (bool) – bool if True the enclosing condition is a compound condition, forbidding any other compound condition

  • path (str | tuple[str, ...]) – path, to which to apply the condition

  • process_path (bool) – bool if True the path will taken apart into its components and the components will be checked with XPath variables

Return type:

str

property path: str | lxml.etree.XPath

Property for constructing the complex Xpath

process_condition(tag, operator, content, path, process_path=False)[source]

Process the condition for the given tag and condition

Parameters:
  • tag (str) – str name of the tag

  • operator (str) – operator for condition

  • content (Any) – content of condition

  • path (str | tuple[str, ...]) – path, to which to apply the condition

  • process_path (bool) – bool if True the path will taken apart into its components and the components will be checked with XPath variables

Return type:

str

strip_off_tag()[source]

Strip off the last tag of the simple xpath expression

Return type:

str

XML Setter functions

Functions for modifying the xml input file of Fleur utilizing the schema dict and as little knowledge of the concrete xpaths as possible

masci_tools.util.xml.xml_setters_names.add_number_to_attrib(xmltree, schema_dict, name, number_to_add, complex_xpath=None, filters=None, mode='absolute', occurrences=None, **kwargs)[source]

Adds a given number to the attribute value in a xmltree specified by the name of the attribute and optional further specification If there are no nodes under the specified xpath an error is raised

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • name (str) – the attribute name to change

  • number_to_add (Any) – number to add/multiply with the old attribute value

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

  • mode (Literal['abs', 'absolute', 'rel', 'relative']) – str (either rel/relative or abs/absolute). rel/relative multiplies the old value with number_to_add abs/absolute adds the old value and number_to_add

  • occurrences (Union[int, Iterable[int], None]) – int or list of int. Which occurrence of the node to set. By default all are set.

Kwargs:
param tag_name:

str, name of the tag where the attribute should be parsed

param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

param exclude:

list of str, here specific types of attributes can be excluded valid values are: settable, settable_contains, other

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with shifted attribute

masci_tools.util.xml.xml_setters_names.add_number_to_first_attrib(xmltree, schema_dict, name, number_to_add, complex_xpath=None, filters=None, mode='absolute', **kwargs)[source]

Adds a given number to the first occurrence of an attribute value in a xmltree specified by the name of the attribute and optional further specification If there are no nodes under the specified xpath an error is raised

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • name (str) – the attribute name to change

  • number_to_add (Any) – number to add/multiply with the old attribute value

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • mode (Literal['abs', 'absolute', 'rel', 'relative']) – str (either rel/relative or abs/absolute). rel/relative multiplies the old value with number_to_add abs/absolute adds the old value and number_to_add

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

Kwargs:
param tag_name:

str, name of the tag where the attribute should be parsed

param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

param exclude:

list of str, here specific types of attributes can be excluded valid values are: settable, settable_contains, other

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with shifted attribute

masci_tools.util.xml.xml_setters_names.clone_species(xmltree, schema_dict, species_name, new_name, changes=None)[source]

Method to create a new species from an existing one with evtl. modifications

For reference of the changes dictionary look at set_species()

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml etree of the inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • species_name (str) – string, name of the specie you want to clone Has to correspond to one single species (no ‘all’/’all-<search_string>’)

  • new_name (str) – new name of the cloned species

  • changes (Optional[dict[str, Any]]) – a optional python dict specifying what you want to change.

Returns xmltree:

xml etree of the new inp.xml

Return type:

Union[_Element, _ElementTree]

masci_tools.util.xml.xml_setters_names.create_tag(xmltree, schema_dict, tag, complex_xpath=None, filters=None, create_parents=False, occurrences=None, **kwargs)[source]

This method creates a tag with a uniquely identified xpath under the nodes of its parent. If there are no nodes evaluated the subtags can be created with create_parents=True

The tag is always inserted in the correct place if a order is enforced by the schema

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • tag (QName | str | _Element) – str of the tag to create or etree Element or string representing the XML element with the same name to insert

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

  • create_parents (bool) – bool optional (default False), if True and the given xpath has no results the the parent tags are created recursively

  • occurrences (Union[int, Iterable[int], None]) – int or list of int. Which occurrence of the parent nodes to create a tag. By default all nodes are used.

Kwargs:
param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with created tags

masci_tools.util.xml.xml_setters_names.delete_att(xmltree, schema_dict, name, complex_xpath=None, filters=None, occurrences=None, **kwargs)[source]

This method deletes a attribute with a uniquely identified xpath.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • name (str) – str of the attribute to delete

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

  • occurrences (Union[int, Iterable[int], None]) – int or list of int. Which occurrence of the parent nodes to delete a attribute. By default all nodes are used.

Kwargs:
param tag_name:

str, name of the tag where the attribute should be parsed

param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

param exclude:

list of str, here specific types of attributes can be excluded valid values are: settable, settable_contains, other

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with deleted attributes

masci_tools.util.xml.xml_setters_names.delete_tag(xmltree, schema_dict, tag_name, complex_xpath=None, filters=None, occurrences=None, **kwargs)[source]

This method deletes a tag with a uniquely identified xpath.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • tag – str of the tag to delete

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

  • occurrences (Union[int, Iterable[int], None]) – int or list of int. Which occurrence of the parent nodes to delete a tag. By default all nodes are used.

Kwargs:
param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with deleted tags

masci_tools.util.xml.xml_setters_names.replace_tag(xmltree, schema_dict, tag_name, element, complex_xpath=None, filters=None, occurrences=None, **kwargs)[source]

This method deletes a tag with a uniquely identified xpath.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • tag – str of the tag to replace

  • element (str | _Element) – etree Element or string representing the XML element to replace the tag

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

  • occurrences (Union[int, Iterable[int], None]) – int or list of int. Which occurrence of the parent nodes to replace a tag. By default all nodes are used.

Kwargs:
param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with replaced tags

masci_tools.util.xml.xml_setters_names.set_atomgroup(xmltree, schema_dict, changes, position=None, species=None, filters=None)[source]

Method to set parameters of an atom group of the fleur inp.xml file.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml etree of the inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • changes (dict[str, Any]) – a python dict specifying what you want to change.

  • position (Union[int, Literal['all'], None]) – position of an atom group to be changed. If equals to ‘all’, all species will be changed

  • species (Optional[str]) – atom groups, corresponding to the given species will be changed

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

Return type:

Union[_Element, _ElementTree]

Returns:

xml etree of the new inp.xml

changes is a python dictionary containing dictionaries that specify attributes to be set inside the certain specie. For example, if one wants to set a beta noco parameter it can be done via:

'changes': {'nocoParams': {'beta': val}}
masci_tools.util.xml.xml_setters_names.set_atomgroup_label(xmltree, schema_dict, atom_label, changes)[source]

This method calls set_atomgroup() method for a certain atom species that corresponds to an atom with a given label.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml etree of the inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • atom_label (str) – string, a label of the atom which specie will be changed. ‘all’ to change all the species

  • changes (dict[str, Any]) – a python dict specifying what you want to change.

Return type:

Union[_Element, _ElementTree]

Returns:

xml etree of the new inp.xml

changes is a python dictionary containing dictionaries that specify attributes to be set inside the certain specie. For example, if one wants to set a beta noco parameter it can be done via:

'changes': {'nocoParams': {'beta': val}}
masci_tools.util.xml.xml_setters_names.set_attrib_value(xmltree, schema_dict, name, value, complex_xpath=None, filters=None, occurrences=None, create=False, **kwargs)[source]

Sets an attribute in a xmltree to a given value, specified by its name and further specifications. If there are no nodes under the specified xpath a tag can be created with create=True. The attribute values are converted automatically according to the types of the attribute with convert_to_xml() if they are not str already.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • name (str) – the attribute name to set

  • value (Any) – value or list of values to set

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

  • occurrences (Union[int, Iterable[int], None]) – int or list of int. Which occurrence of the node to set. By default all are set.

  • create (bool) – bool optional (default False), if True the tag is created if is missing

Kwargs:
param tag_name:

str, name of the tag where the attribute should be parsed

param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

param exclude:

list of str, here specific types of attributes can be excluded valid values are: settable, settable_contains, other

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with set attribute

masci_tools.util.xml.xml_setters_names.set_complex_tag(xmltree, schema_dict, tag_name, changes, complex_xpath=None, filters=None, create=False, **kwargs)[source]

Function to correctly set tags/attributes for a given tag. Goes through the attributedict and decides based on the schema_dict, how the corresponding key has to be handled. The tag is specified via its name and evtl. further specification

Supports:

  • attributes

  • tags with text only

  • simple tags, i.e. only attributes (can be optional single/multiple)

  • complex tags, will recursively create/modify them

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • tag_name (str) – name of the tag to set

  • changes (dict[str, Any]) – Keys in the dictionary correspond to names of tags and the values are the modifications to do on this tag (attributename, subdict with changes to the subtag, …)

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

  • create (bool) – bool optional (default False), if True and the path, where the complex tag is set does not exist it is created

Kwargs:
param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with changes to the complex tag

masci_tools.util.xml.xml_setters_names.set_first_attrib_value(xmltree, schema_dict, name, value, complex_xpath=None, filters=None, create=False, **kwargs)[source]

Sets the first occurrence of an attribute in a xmltree to a given value, specified by its name and further specifications. If there are no nodes under the specified xpath a tag can be created with create=True. The attribute values are converted automatically according to the types of the attribute with convert_to_xml() if they are not str already.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • name (str) – the attribute name to set

  • value (Any) – value or list of values to set

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

  • create (bool) – bool optional (default False), if True the tag is created if is missing

Kwargs:
param tag_name:

str, name of the tag where the attribute should be parsed

param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

param exclude:

list of str, here specific types of attributes can be excluded valid values are: settable, settable_contains, other

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with set attribute

masci_tools.util.xml.xml_setters_names.set_first_text(xmltree, schema_dict, tag_name, text, complex_xpath=None, filters=None, create=False, **kwargs)[source]

Sets the text the first occurrence of a tag in a xmltree to a given value, specified by the name of the tag and further specifications. By default the text will be set on all nodes returned for the specified xpath. If there are no nodes under the specified xpath a tag can be created with create=True. The text values are converted automatically according to the types with convert_to_xml() if they are not str already.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • tag_name (str) – str name of the tag, where the text should be set

  • text (Any) – value or list of values to set

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

  • create (bool) – bool optional (default False), if True the tag is created if is missing

Kwargs:
param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with set text

masci_tools.util.xml.xml_setters_names.set_inpchanges(xmltree, schema_dict, changes, path_spec=None)[source]

This method sets all the attribute and texts provided in the change_dict.

The first occurrence of the attribute/tag is set

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml tree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • changes (dict[str, Any]) – dictionary {attrib_name : value} with all the wanted changes.

  • path_spec (Optional[dict[str, Any]]) – dict, with ggf. necessary further specifications for the path of the attribute

An example of changes:

changes = {
    'itmax' : 1,
    'l_noco': True,
    'ctail': False,
    'l_ss': True
}
Return type:

Union[_Element, _ElementTree]

Returns:

an xmltree of the inp.xml file with changes.

masci_tools.util.xml.xml_setters_names.set_kpath(xmltree, schema_dict, kpath, count, gamma=False)[source]

Sets a k-path directly into inp.xml as a alternative kpoint set with purpose ‘bands’

Warning

This method is only supported for input versions before the Max5 release

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml tree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • kpath (dict[str, Iterable[float]]) – a dictionary with kpoint name as key and k point coordinate as value

  • count (int) – number of k-points

  • gamma (bool) – bool that controls if the gamma-point should be included in the k-point mesh

Return type:

Union[_Element, _ElementTree]

Returns:

an xmltree of the inp.xml file with changes.

masci_tools.util.xml.xml_setters_names.set_kpath_max4(xmltree, schema_dict, kpath, count, gamma=False)[source]

Sets a k-path directly into inp.xml as a alternative kpoint set with purpose ‘bands’

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml tree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • kpath (dict[str, Iterable[float]]) – a dictionary with kpoint name as key and k point coordinate as value

  • count (int) – number of k-points

  • gamma (bool) – bool that controls if the gamma-point should be included in the k-point mesh

Return type:

Union[_Element, _ElementTree]

Returns:

an xmltree of the inp.xml file with changes.

masci_tools.util.xml.xml_setters_names.set_kpointlist(xmltree, schema_dict, kpoints, weights, name=None, kpoint_type='path', special_labels=None, switch=False, overwrite=False, additional_attributes=None)[source]

Explicitly create a kPointList from the given kpoints and weights. This routine will add the specified kPointList with the given name.

Warning

For input versions Max4 and older all keyword arguments are not valid (name, kpoint_type, special_labels, switch and overwrite)

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml tree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • kpoints (Iterable[Iterable[float]]) – list or array containing the relative coordinates of the kpoints

  • weights (Iterable[float]) – list or array containing the weights of the kpoints

  • name (Optional[str]) – str for the name of the list, if not given a default name is generated

  • kpoint_type (Literal['path', 'mesh', 'tria', 'tria-bulk', 'spex-mesh']) – str specifying the type of the kPointList (‘path’, ‘mesh’, ‘spex’, ‘tria’, …)

  • special_labels (Optional[dict[int, str]]) – dict mapping indices to labels. The labels will be inserted for the kpoints corresponding to the given index

  • switch (bool) – bool, if True the kPointlist will be used by Fleur when starting the next calculation

  • overwrite (bool) – bool, if True and a kPointlist with the given name already exists it will be overwritten

Return type:

Union[_Element, _ElementTree]

Returns:

an xmltree of the inp.xml file with changes.

masci_tools.util.xml.xml_setters_names.set_kpointlist_max4(xmltree, schema_dict, kpoints, weights, name=None, kpoint_type='path', special_labels=None, switch=False, overwrite=False, additional_attributes=None)[source]

Explicitly create a kPointList from the given kpoints and weights. This routine is specific to input versions Max4 and before and will replace any existing kPointCount, kPointMesh, … with the specified kPointList

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml tree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • kpoints (Iterable[Iterable[float]]) – list or array containing the relative coordinates of the kpoints

  • weights (Iterable[float]) – list or array containing the weights of the kpoints

Return type:

Union[_Element, _ElementTree]

Returns:

an xmltree of the inp.xml file with changes.

masci_tools.util.xml.xml_setters_names.set_kpointmesh(xmltree, schema_dict, mesh, name=None, use_symmetries=True, switch=False, overwrite=False, shift=None, time_reversal=True, map_to_first_bz=True)[source]

Create a kpoint mesh using spglib

for details see get_stabilized_reciprocal_mesh()

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml tree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • mesh (Collection[int]) – list-like woth three elements, giving the size of the kpoint set in each direction

  • use_symmetry – bool if True the available symmetry operations in the inp.xml will be used to reduce the kpoint set otherwise only the identity matrix is used

  • name (Optional[str]) – Name of the created kpoint list. If not given a name is generated

  • switch (bool) – bool if True the kpoint list is direclty set as the used set

  • overwrite (bool) – if True and a kpoint list of the given name already exists it will be overwritten

  • shift (Optional[Iterable[float]]) – shift the center of the kpint set

  • time_reversal (bool) – bool if True time reversal symmetry will be used to reduce the kpoint set

  • map_to_first_bz (bool) – bool if True the kpoints are mapped into the [0,1] interval

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with a created kpoint path

masci_tools.util.xml.xml_setters_names.set_kpointpath(xmltree, schema_dict, path=None, nkpts=None, density=None, name=None, switch=False, overwrite=False, special_points=None)[source]

Create a kpoint list for a bandstructure calculation (using ASE kpath generation)

The path can be defined explictly (see bandpath()) or derived from the unit cell

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml tree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • path (Union[str, list[str], None]) – str, list of str or None defines the path to interpolate (for syntax bandpath())

  • nkpts (Optional[int]) – int number of kpoints in the path

  • density (Optional[float]) – float number of kpoints per Angstroem

  • name (Optional[str]) – Name of the created kpoint list. If not given a name is generated

  • switch (bool) – bool if True the kpoint list is direclty set as the used set

  • overwrite (bool) – if True and a kpoint list of the given name already exists it will be overwritten

  • special_points (Optional[dict[str, Iterable[float]]]) – dict mapping names to coordinates for special points to use

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with a created kpoint path

masci_tools.util.xml.xml_setters_names.set_nkpts(xmltree, schema_dict, count, gamma=False)[source]

Sets a k-point mesh directly into inp.xml

Warning

This method is only supported for input versions before the Max5 release

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml tree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • count (int) – number of k-points

  • gamma (bool) – bool that controls if the gamma-point should be included in the k-point mesh

Return type:

Union[_Element, _ElementTree]

Returns:

an xmltree of the inp.xml file with changes.

masci_tools.util.xml.xml_setters_names.set_nkpts_max4(xmltree, schema_dict, count, gamma=False)[source]

Sets a k-point mesh directly into inp.xml specific for inputs of version Max4

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml tree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • count (int) – number of k-points

  • gamma (bool) – bool that controls if the gamma-point should be included in the k-point mesh

Return type:

Union[_Element, _ElementTree]

Returns:

an xmltree of the inp.xml file with changes.

masci_tools.util.xml.xml_setters_names.set_simple_tag(xmltree, schema_dict, tag_name, changes, complex_xpath=None, filters=None, create_parents=False, **kwargs)[source]

Sets one or multiple simple tag(s) in an xmltree. A simple tag can only hold attributes and has no subtags. The tag is specified by its name and further specification If the tag can occur multiple times all existing tags are DELETED and new ones are written. If the tag only occurs once it will automatically be created if its missing.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • tag_name (str) – str name of the tag to modify/set

  • changes (list[dict[str, Any]] | dict[str, Any]) – list of dicts or dict with the changes. Elements in list describe multiple tags. Keys in the dictionary correspond to {‘attributename’: attributevalue}

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

  • create_parents (bool) – bool optional (default False), if True and the path, where the simple tags are set does not exist it is created

Kwargs:
param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with set simple tags

masci_tools.util.xml.xml_setters_names.set_species(xmltree, schema_dict, species_name, changes, filters=None, create=False)[source]

Method to set parameters of a species tag of the fleur inp.xml file.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml etree of the inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • species_name (str) – string, name of the specie you want to change Can be name of the species, ‘all’ or ‘all-<string>’ (sets species with the string in the species name)

  • changes (dict[str, Any]) – a python dict specifying what you want to change.

  • create (bool) – bool, if species does not exist create it and all subtags?

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

Raises:

ValueError – if species name is non existent in inp.xml and should not be created. also if other given tags are garbage. (errors from eval_xpath() methods)

Return xmltree:

xml etree of the new inp.xml

Return type:

Union[_Element, _ElementTree]

changes is a python dictionary containing dictionaries that specify attributes to be set inside the certain specie. For example, if one wants to set a MT radius it can be done via:

changes = {'mtSphere' : {'radius' : 2.2}}

Another example:

'changes': {'special': {'socscale': 0.0}}

that switches SOC terms on a sertain specie. mtSphere, atomicCutoffs, energyParameters, lo, electronConfig, nocoParams, ldaU and special keys are supported. To find possible keys of the inner dictionary please refer to the FLEUR documentation flapw.de

masci_tools.util.xml.xml_setters_names.set_species_label(xmltree, schema_dict, atom_label, changes, create=False)[source]

This method calls set_species() method for a certain atom species that corresponds to an atom with a given label

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml etree of the inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • atom_label (str) – string, a label of the atom which specie will be changed. ‘all’ to change all the species

  • changes (dict[str, Any]) – a python dict specifying what you want to change.

  • create (bool) – bool, if species does not exist create it and all subtags?

Return type:

Union[_Element, _ElementTree]

Returns:

xml etree of the new inp.xml

masci_tools.util.xml.xml_setters_names.set_text(xmltree, schema_dict, tag_name, text, complex_xpath=None, filters=None, occurrences=None, create=False, **kwargs)[source]

Sets the text on tags in a xmltree to a given value, specified by the name of the tag and further specifications. By default the text will be set on all nodes returned for the specified xpath. If there are no nodes under the specified xpath a tag can be created with create=True. The text values are converted automatically according to the types with convert_to_xml() if they are not str already.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • tag_name (str) – str name of the tag, where the text should be set

  • text (Any) – value or list of values to set

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

  • occurrences (Union[int, Iterable[int], None]) – int or list of int. Which occurrence of the node to set. By default all are set.

  • create (bool) – bool optional (default False), if True the tag is created if is missing

Kwargs:
param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with set text

masci_tools.util.xml.xml_setters_names.set_xcfunctional(xmltree, schema_dict, xc_functional, xc_functional_options=None, libxc=False)[source]

Set the Exchange Correlation potential tag

Setting a inbuilt XC functional .. code-block:: python

set_xcfunctional(xmltree, schema_dict, ‘vwn’)

Setting a LibXC XC functional .. code-block:: python

set_xcfunctional(xmltree, schema_dict, {‘exchange’: ‘lda_x’, ‘correlation’:”lda_c_xalpha”}, libxc=True)

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – XML tree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • xc_functional (str | dict[str, int | str]) – str or dict. If str it is the name of a inbuilt XC functional. If it is a dict it specifies either the name or id for LibXC functionals for the keys ‘exchange’, ‘correlation’, ‘etot_exchange’ and ‘etot_correlation’

  • xc_functional_options (Optional[dict[str, Any]]) – dict with further general changes to the xcFunctional tag

  • libxc (bool) – bool if True the functional is a LibXC functional

Return type:

Union[_Element, _ElementTree]

Returns:

an xmltree with modified xcFunctional tag

masci_tools.util.xml.xml_setters_names.shift_value(xmltree, schema_dict, changes, mode='absolute', path_spec=None)[source]

Shifts numerical values of attributes directly in the inp.xml file.

The first occurrence of the attribute is shifted

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml tree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • changes (dict[str, Any]) – a python dictionary with the keys to shift and the shift values.

  • mode (Literal['abs', 'absolute', 'rel', 'relative']) – str (either rel/relative or abs/absolute). rel/relative multiplies the old value with the given value abs/absolute adds the old value and the given value

  • path_spec (Optional[dict[str, Any]]) – dict, with ggf. necessary further specifications for the path of the attribute

Return type:

Union[_Element, _ElementTree]

Returns:

a xml tree with shifted values

An example of changes:

changes = {'itmax' : 1, 'dVac': -0.123}
masci_tools.util.xml.xml_setters_names.shift_value_species_label(xmltree, schema_dict, atom_label, attribute_name, number_to_add, mode='absolute', **kwargs)[source]

Shifts the value of an attribute on a species by label if atom_label contains ‘all’ then applies to all species

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml etree of the inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • atom_label (str) – string, a label of the atom which specie will be changed. ‘all’ if set up all species

  • attribute_name (str) – name of the attribute to change

  • number_to_add (Any) – value to add or to multiply by

  • mode (Literal['abs', 'absolute', 'rel', 'relative']) – str (either rel/relative or abs/absolute). rel/relative multiplies the old value with number_to_add abs/absolute adds the old value and number_to_add

Kwargs if the attribute_name does not correspond to a unique path:
param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

Return type:

Union[_Element, _ElementTree]

Returns:

xml etree of the new inp.xml

masci_tools.util.xml.xml_setters_names.switch_kpointset(xmltree, schema_dict, list_name)[source]

Switch the used k-point set

Warning

This method is only supported for input versions after the Max5 release

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml tree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • list_name (str) – name of the kPoint set to use

Return type:

Union[_Element, _ElementTree]

Returns:

an xmltree of the inp.xml file with changes.

masci_tools.util.xml.xml_setters_names.switch_kpointset_max4(xmltree, schema_dict, list_name)[source]

Sets a k-point mesh directly into inp.xml specific for inputs of version Max4

Warning

This method is only supported for input versions after the Max5 release

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml tree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • list_name (str) – name of the kPoint set to use

Return type:

Union[_Element, _ElementTree]

Returns:

an xmltree of the inp.xml file with changes.

masci_tools.util.xml.xml_setters_names.switch_species(xmltree, schema_dict, new_species_name, position=None, species=None, filters=None, clone=False, changes=None)[source]

Method to switch the species of an atom group of the fleur inp.xml file.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml etree of the inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • new_species_name (str) – name of the species to switch to

  • position (Union[int, Literal['all'], None]) – position of an atom group to be changed. If equals to ‘all’, all species will be changed

  • species (Optional[str]) – atom groups, corresponding to the given species will be changed

  • clone (bool) – if True and the new species name does not exist and it corresponds to changing from one species the species will be cloned with clone_species()

  • changes (Optional[dict[str, Any]]) – changes to do if the species is cloned

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

Return type:

Union[_Element, _ElementTree]

Returns:

xml etree of the new inp.xml

masci_tools.util.xml.xml_setters_names.switch_species_label(xmltree, schema_dict, atom_label, new_species_name, clone=False, changes=None)[source]

Method to switch the species of an atom group of the fleur inp.xml file based on a label of a contained atom

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – xml etree of the inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • atom_label (str) – string, a label of the atom which group will be changed. ‘all’ to change all the groups

  • new_species_name (str) – name of the species to switch to

  • clone (bool) – if True and the new species name does not exist and it corresponds to changing from one species the species will be cloned with clone_species()

  • changes (Optional[dict[str, Any]]) – changes to do if the species is cloned

Return type:

Union[_Element, _ElementTree]

Returns:

xml etree of the new inp.xml

This module contains useful methods for initializing or modifying a n_mmp_mat file for LDA+U

class masci_tools.util.xml.xml_setters_nmmpmat.LDAUElement(species: str, orbital: int, group_index: int)[source]

Contains the important information needed to locate the associated density matrix blocks

group_index: int

Alias for field number 2

orbital: int

Alias for field number 1

species: str

Alias for field number 0

masci_tools.util.xml.xml_setters_nmmpmat.align_nmmpmat_to_sqa(xmltree, nmmplines, schema_dict, species_name='all', orbital='all', phi_before=0.0, theta_before=0.0, filters=None)[source]

Align the density matrix with the given SQA of the associated species

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • nmmplines (list[str]) – list of lines in the n_mmp_mat file

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • species_name (str) – string, name of the species you want to change

  • orbital (int | str) – integer or string (‘all’), orbital quantum number of the LDA+U procedure to be modified

  • phi_before (float | list[float]) – float or list of floats, angle (radian), values for phi for the previous alignment of the density matrix

  • theta_before (float | list[float]) – float or list of floats, angle (radian), values for theta for the previous alignment of the density matrix

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

Raises:
  • ValueError – If something in the input is wrong

  • KeyError – If no LDA+U procedure is found on a species

Return type:

list[str]

Returns:

list with modified nmmplines

masci_tools.util.xml.xml_setters_nmmpmat.rotate_nmmpmat(xmltree, nmmplines, schema_dict, species_name, orbital, phi, theta, inverse=False, filters=None)[source]

Rotate the density matrix with the given angles phi and theta

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • nmmplines (list[str]) – list of lines in the n_mmp_mat file

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • species_name (str) – string, name of the species you want to change

  • orbital (int | str) – integer or string (‘all’), orbital quantum number of the LDA+U procedure to be modified

  • phi (float) – float, angle (radian), by which to rotate the density matrix

  • theta (float) – float, angle (radian), by which to rotate the density matrix

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

Raises:
  • ValueError – If something in the input is wrong

  • KeyError – If no LDA+U procedure is found on a species

Return type:

list[str]

Returns:

list with modified nmmplines

masci_tools.util.xml.xml_setters_nmmpmat.set_nmmpmat(xmltree, nmmplines, schema_dict, species_name, orbital, spin, state_occupations=None, orbital_occupations=None, denmat=None, phi=None, theta=None, inverse=False, align_to_sqa=False, filters=None)[source]

Routine sets the block in the n_mmp_mat file specified by species_name, orbital and spin to the desired density matrix

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • nmmplines (Optional[list[str]]) – list of lines in the n_mmp_mat file

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • species_name (str) – string, name of the species you want to change

  • orbital (int) – integer, orbital quantum number of the LDA+U procedure to be modified

  • spin (int) – integer, specifies which spin block should be modified

  • state_occupations (Optional[list[float]]) – list, sets the diagonal elements of the density matrix and everything else to zero

  • denmat (Optional[ndarray]) – matrix, specify the density matrix explicitly

  • phi (Optional[float]) – float, optional angle (radian), by which to rotate the density matrix before writing it

  • theta (Optional[float]) – float, optional angle (radian), by which to rotate the density matrix before writing it

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

Raises:
  • ValueError – If something in the input is wrong

  • KeyError – If no LDA+U procedure is found on a species

Return type:

list[str]

Returns:

list with modified nmmplines

masci_tools.util.xml.xml_setters_nmmpmat.validate_nmmpmat(xmltree, nmmplines, schema_dict)[source]

Checks that the given nmmp_lines is valid with the given xmltree

Checks that the number of blocks is as expected from the inp.xml and each block does not contain non-zero elements outside their size given by the orbital quantum number in the inp.xml. Additionally the occupations, i.e. diagonal elements are checked that they are in between 0 and the maximum possible occupation

Parameters:
Raises:

ValueError – if any of the above checks are violated.

Return type:

None

Functions for modifying the xml input file of Fleur with explicit xpath arguments These can still use the schema dict for finding information about the xpath

masci_tools.util.xml.xml_setters_xpaths.eval_xpath_create(xmltree, schema_dict, xpath, base_xpath, create_parents=False, occurrences=None, number_nodes=1)[source]

Evaluates and xpath and creates tag if the result is empty

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • xpath (Union[str, bytes, XPath, XPathBuilder]) – a path where to place a new tag

  • base_xpath (str) – path where to place a new tag without complex syntax ([] conditions and so on)

  • create_parents (bool) – bool optional (default False), if True also the parents of the tag are created if they are missing

  • occurrences (Union[int, Iterable[int], None]) – int or list of int. Which occurrence of the parent nodes to create a tag if the tag is missing. By default all nodes are used.

  • list_return – if True, the returned quantity is always a list even if only one element is in it

  • number_nodes (int) – how many identical nodes to create

Return type:

list[_Element]

Returns:

list of nodes from the result of the xpath expression

masci_tools.util.xml.xml_setters_xpaths.xml_add_number_to_attrib(xmltree, schema_dict, xpath, base_xpath, name, number_to_add, mode='absolute', occurrences=None)[source]

Adds a given number to the attribute value in a xmltree. By default the attribute will be shifted on all nodes returned for the specified xpath. If there are no nodes under the specified xpath an error is raised

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • xpath (Union[str, bytes, XPath, XPathBuilder]) – a path where to set the attributes

  • base_xpath (str) – path where to place a new tag without complex syntax ([] conditions and so on)

  • name (str) – the attribute name to change

  • number_to_add (Any) – number to add/multiply with the old attribute value

  • mode (Literal['abs', 'absolute', 'rel', 'relative']) – str (either rel/relative or abs/absolute). rel/relative multiplies the old value with number_to_add abs/absolute adds the old value and number_to_add

  • occurrences (Union[int, Iterable[int], None]) – int or list of int. Which occurrence of the node to set. By default all are set.

Raises:
  • ValueError – If the attribute is unknown or cannot be float or int

  • ValueError – If the evaluation of the old values failed

  • ValueError – If a float result is written to a integer attribute

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with shifted attribute

masci_tools.util.xml.xml_setters_xpaths.xml_add_number_to_first_attrib(xmltree, schema_dict, xpath, base_xpath, name, number_to_add, mode='absolute')[source]

Adds a given number to the first occurrence of a attribute value in a xmltree. If there are no nodes under the specified xpath an error is raised

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • xpath (Union[str, bytes, XPath, XPathBuilder]) – a path where to set the attributes

  • base_xpath (str) – path where to place a new tag without complex syntax ([] conditions and so on)

  • name (str) – the attribute name to change

  • number_to_add (Any) – number to add/multiply with the old attribute value

  • mode (Literal['abs', 'absolute', 'rel', 'relative']) – str (either rel/relative or abs/absolute). rel/relative multiplies the old value with number_to_add abs/absolute adds the old value and number_to_add

Raises:
  • ValueError – If the attribute is unknown or cannot be float or int

  • ValueError – If the evaluation of the old values failed

  • ValueError – If a float result is written to a integer attribute

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with shifted attribute

masci_tools.util.xml.xml_setters_xpaths.xml_create_tag_schema_dict(xmltree, schema_dict, xpath, base_xpath, element, create_parents=False, number_nodes=1, occurrences=None)[source]

This method evaluates an xpath expression and creates a tag in a xmltree under the returned nodes. If there are no nodes evaluated the subtags can be created with create_parents=True

The tag is always inserted in the correct place if a order is enforced by the schema

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • xpath (Union[str, bytes, XPath, XPathBuilder]) – a path where to place a new tag

  • base_xpath (str) – path where to place a new tag without complex syntax ([] conditions and so on)

  • element (QName | str | _Element) – a tag name or etree Element or string representing the XML element to be created

  • create_parents (bool) – bool optional (default False), if True and the given xpath has no results the the parent tags are created recursively

  • occurrences (Union[int, Iterable[int], None]) – int or list of int. Which occurrence of the parent nodes to create a tag. By default all nodes are used.

  • number_nodes (int) – how many identical nodes to create

Raises:

ValueError – If the nodes are missing and create_parents=False

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with created tags

masci_tools.util.xml.xml_setters_xpaths.xml_set_attrib_value(xmltree, schema_dict, xpath, base_xpath, name, value, occurrences=None, create=False)[source]

Sets an attribute in a xmltree to a given value. By default the attribute will be set on all nodes returned for the specified xpath. If there are no nodes under the specified xpath a tag can be created with create=True. The attribute values are converted automatically according to the types of the attribute with convert_to_xml() if they are not str already.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • xpath (Union[str, bytes, XPath, XPathBuilder]) – a path where to set the attributes

  • base_xpath (str) – path where to place a new tag without complex syntax ([] conditions and so on)

  • name (str) – the attribute name to set

  • value (Any) – value or list of values to set

  • occurrences (Union[int, Iterable[int], None]) – int or list of int. Which occurrence of the node to set. By default all are set.

  • create (bool) – bool optional (default False), if True the tag is created if is missing

Raises:
  • ValueError – If the conversion to string failed

  • ValueError – If the tag is missing and create=False

  • ValueError – If the name is not allowed on the base_xpath

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with set attribute

masci_tools.util.xml.xml_setters_xpaths.xml_set_complex_tag(xmltree, schema_dict, xpath, base_xpath, changes, create=False)[source]

Recursive function to correctly set tags/attributes for a given tag and it’s subtags. Goes through the changes dictionary and decides based on the schema_dict, how the corresponding key has to be handled.

Supports:

  • attributes

  • tags with text only

  • simple tags, i.e. only attributes (can be optional single/multiple)

  • complex tags, will recursively create/modify them

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • xpath (Union[str, bytes, XPath, XPathBuilder]) – a path where to set the attributes

  • base_xpath (str) – path where to place a new tag without complex syntax ([] conditions and so on)

  • tag_name – name of the tag to set

  • changes (dict[str, Any]) – Keys in the dictionary correspond to names of tags and the values are the modifications to do on this tag (attributename, subdict with changes to the subtag, …)

  • create (bool) – bool optional (default False), if True and the path, where the complex tag is set does not exist it is created

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with changes to the complex tag

masci_tools.util.xml.xml_setters_xpaths.xml_set_first_attrib_value(xmltree, schema_dict, xpath, base_xpath, name, value, create=False)[source]

Sets the first occurrence attribute in a xmltree to a given value. If there are no nodes under the specified xpath a tag can be created with create=True. The attribute values are converted automatically according to the types of the attribute with convert_to_xml() if they are not str already.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • xpath (Union[str, bytes, XPath, XPathBuilder]) – a path where to set the attribute

  • base_xpath (str) – path where to place a new tag without complex syntax ([] conditions and so on)

  • name (str) – the attribute name to set

  • value (Any) – value or list of values to set

  • create (bool) – bool optional (default False), if True the tag is created if is missing

Raises:
  • ValueError – If the conversion to string failed

  • ValueError – If the tag is missing and create=False

  • ValueError – If the attributename is not allowed on the base_xpath

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with set attribute

masci_tools.util.xml.xml_setters_xpaths.xml_set_first_text(xmltree, schema_dict, xpath, base_xpath, text, create=False)[source]

Sets the text on the first occurrence of a tag in a xmltree to a given value. If there are no nodes under the specified xpath a tag can be created with create=True. The text values are converted automatically according to the types with convert_to_xml() if they are not str already.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • xpath (Union[str, bytes, XPath, XPathBuilder]) – a path where to set the text

  • base_xpath (str) – path where to place a new tag without complex syntax ([] conditions and so on)

  • text (Any) – value or list of values to set

  • create (bool) – bool optional (default False), if True the tag is created if is missing

Raises:
  • ValueError – If the conversion to string failed

  • ValueError – If the tag is missing and create=False

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with set text

masci_tools.util.xml.xml_setters_xpaths.xml_set_simple_tag(xmltree, schema_dict, xpath, base_xpath, tag_name, changes, create_parents=False)[source]

Sets one or multiple simple tag(s) in an xmltree. A simple tag can only hold attributes and has no subtags. If the tag can occur multiple times all existing tags are DELETED and new ones are written. If the tag only occurs once it will automatically be created if its missing.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • xpath (Union[str, bytes, XPath, XPathBuilder]) – a path where to set the attributes

  • base_xpath (str) – path where to place a new tag without complex syntax ([] conditions and so on)

  • tag_name (str) – name of the tag to set

  • changes (list[dict[str, Any]] | dict[str, Any]) – list of dicts or dict with the changes. Elements in list describe multiple tags. Keys in the dictionary correspond to {‘name’: value}

  • create_parents (bool) – bool optional (default False), if True and the path, where the simple tags are set does not exist it is created

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with set simple tags

masci_tools.util.xml.xml_setters_xpaths.xml_set_text(xmltree, schema_dict, xpath, base_xpath, text, occurrences=None, create=False)[source]

Sets the text on tags in a xmltree to a given value. By default the text will be set on all nodes returned for the specified xpath. If there are no nodes under the specified xpath a tag can be created with create=True. The text values are converted automatically according to the types with convert_to_xml() if they are not str already.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • schema_dict (SchemaDict) – InputSchemaDict containing all information about the structure of the input

  • xpath (Union[str, bytes, XPath, XPathBuilder]) – a path where to set the text

  • base_xpath (str) – path where to place a new tag without complex syntax ([] conditions and so on)

  • text (Any) – value or list of values to set

  • occurrences (Union[int, Iterable[int], None]) – int or list of int. Which occurrence of the node to set. By default all are set.

  • create (bool) – bool optional (default False), if True the tag is created if is missing

Raises:
  • ValueError – If the conversion to string failed

  • ValueError – If the tag is missing and create=False

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with set text

Basic functions for modifying the xml input file of Fleur. These functions DO NOT have the ability to create missing tags on the fly. This functionality is added on top in xml_setters_xpaths since we need the schema dictionary to do these operations robustly

masci_tools.util.xml.xml_setters_basic.xml_create_tag(xmltree, xpath, element, place_index=None, tag_order=None, occurrences=None, correct_order=True, several=True)[source]

This method evaluates an xpath expression and creates a tag in a xmltree under the returned nodes. If there are no nodes under the specified xpath an error is raised.

The tag is appended by default, but can be inserted at a certain index (place_index) or can be inserted according to a given order of tags

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • xpath (Union[str, bytes, XPath, XPathBuilder]) – a path where to place a new tag

  • element (QName | str | _Element) – a tag name, etree Element or string representing the XML element to be created

  • place_index (Optional[int]) – defines the place where to put a created tag

  • tag_order (Optional[list[str]]) – defines a tag order

  • occurrences (Union[int, Iterable[int], None]) – int or list of int. Which occurrence of the parent nodes to create a tag. By default all nodes are used.

  • correct_order (bool) – bool, if True (default) and a tag_order is given, that does not correspond to the given order in the xmltree (only order wrong no unknown tags) it will be corrected and a warning is given This is necessary for some edge cases of the xml schemas of fleur

  • several (bool) – bool, if True multiple tags od the given name are allowed

Raises:

ValueError – If the insertion failed in any way (tag_order does not match, failed to insert, …)

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with created tags

masci_tools.util.xml.xml_setters_basic.xml_delete_att(xmltree, xpath, name, occurrences=None)[source]

Deletes an attribute in the XML tree

Parameters:
Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with deleted attribute

masci_tools.util.xml.xml_setters_basic.xml_delete_tag(xmltree, xpath, occurrences=None)[source]

Deletes a tag in the XML tree.

Parameters:
Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with deleted tag

masci_tools.util.xml.xml_setters_basic.xml_replace_tag(xmltree, xpath, element, occurrences=None)[source]

Replace XML tags by a given tag on the given XML tree

Parameters:
Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with replaced tag

masci_tools.util.xml.xml_setters_basic.xml_set_attrib_value_no_create(xmltree, xpath, name, value, occurrences=None)[source]

Sets an attribute in a xmltree to a given value. By default the attribute will be set on all nodes returned for the specified xpath.

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – an xmltree that represents inp.xml

  • xpath (Union[str, bytes, XPath, XPathBuilder]) – a path where to set the attributes

  • name (str) – the attribute name to set

  • value (Any) – value or list of values to set (if not str they will be converted with str(value))

  • occurrences (Union[int, Iterable[int], None]) – int or list of int. Which occurrence of the node to set. By default all are set.

Raises:

ValueError – If the lengths of attribv or occurrences do not match number of nodes

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with set attribute

masci_tools.util.xml.xml_setters_basic.xml_set_text_no_create(xmltree, xpath, text, occurrences=None)[source]

Sets the text of a tag in a xmltree to a given value. By default the text will be set on all nodes returned for the specified xpath.

Parameters:
Raises:

ValueError – If the lengths of text or occurrences do not match number of nodes

Return type:

Union[_Element, _ElementTree]

Returns:

xmltree with set text

XML Getter functions

This module provides functions to extract distinct parts of the fleur xml files for easy versioning and reuse

masci_tools.util.xml.xml_getters.get_cell(xmltree, schema_dict, logger=None, convert_to_angstroem=True)[source]

Get the Bravais matrix from the given fleur xml file. In addition a list determining in, which directions there are periodic boundary conditions in the system.

Warning

Only the explicit definition of the Bravais matrix is supported. Old inputs containing the latnam definitions are not supported

Parameters:
Return type:

tuple[ndarray, tuple[bool, bool, bool]]

Returns:

numpy array of the bravais matrix and list of boolean values for periodic boundary conditions

masci_tools.util.xml.xml_getters.get_fleur_modes(xmltree, schema_dict, logger=None)[source]

Determine the calculation modes of fleur for the given xml file. Calculation modes are things that change the produced files or output in the out.xml files

Parameters:
Return type:

dict[str, Any]

Returns:

dictionary with all the extracted calculation modes

The following modes are inspected:

  • jspin: How many spins are considered in the calculation

  • noco: Is the calculation non-collinear?

  • soc: Is spin-orbit coupling included?

  • relax: Is the calculation a structure relaxation?

  • spex: Special mode for GW/Spex calculations

  • force_theorem: Is a Force theorem calculation performed?

  • film: Is the structure a film system

  • ldau: Is LDA+U included?

  • dos: Is it a density of states calculation?

  • band: Is it a bandstructure calculation?

  • bz_integration: How is the integration over the Brillouin-Zone performed?

masci_tools.util.xml.xml_getters.get_kpoints_data(*args, **kwargs)[source]

RENAMED TO get_kpointsdata

Return type:

tuple[list[list[float]] | dict[str, list[list[float]]], list[float] | dict[str, list[float]], ndarray, tuple[bool, bool, bool]]

masci_tools.util.xml.xml_getters.get_kpointsdata(xmltree, schema_dict, name=None, index=None, only_used=False, logger=None, convert_to_angstroem=True)[source]

Get the kpoint sets defined in the given fleur xml file.

Warning

For file versions before Max5 arguments name, index and only_used have no effect

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – etree representing the fleur xml file

  • schema_dict (InputSchemaDict | OutputSchemaDict) – schema dictionary corresponding to the file version of the xmltree

  • name (Optional[str]) – str, optional, if given only the kpoint set with the given name is returned

  • index (Optional[int]) – int, optional, if given only the kpoint set with the given index is returned

  • only_used (bool) – bool if True only the kpoint list used in the calculation is returned

  • logger (Optional[Logger]) – logger object for logging warnings, errors

  • convert_to_angstroem (bool) – bool if True the bravais matrix is converted to angstroem

Return type:

tuple[list[list[float]] | dict[str, list[list[float]]], list[float] | dict[str, list[float]], ndarray, tuple[bool, bool, bool]]

Returns:

tuple containing the kpoint information

The tuple contains the following entries:

  1. kpoints:

    dict or list (list if there is only one kpoint set), containing the coordinates of the kpoints

  2. weights:

    dict or list (list if there is only one kpoint set), containing the weights of the kpoints

  3. cell:

    numpy array, bravais matrix of the given system

  4. pbc:

    list of booleans, determines in which directions periodic boundary conditions are applicable

masci_tools.util.xml.xml_getters.get_kpointsdata_max4(xmltree, schema_dict, name=None, index=None, only_used=False, logger=None, convert_to_angstroem=True)[source]

Get the kpoint sets defined in the given fleur xml file.

Note

This function is specific to file version before and including the Max4 release of fleur

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – etree representing the fleur xml file

  • schema_dict (InputSchemaDict | OutputSchemaDict) – schema dictionary corresponding to the file version of the xmltree

  • logger (Optional[Logger]) – logger object for logging warnings, errors

  • convert_to_angstroem (bool) – bool if True the bravais matrix is converted to angstroem

  • only_used (bool) – (Has no effect for Max4) bool if True only the kpoint list used in the calculation is returned

  • name (Optional[str]) – (Has no effect for Max4)

  • index (Optional[int]) – (Has no effect for Max4)

Return type:

tuple[list[list[float]], list[float], ndarray, tuple[bool, bool, bool]]

Returns:

tuple containing the kpoint information

The tuple contains the following entries:

  1. kpoints:

    list containing the coordinates of the kpoints

  2. weights:

    list containing the weights of the kpoints

  3. cell:

    numpy array, bravais matrix of the given system

  4. pbc:

    list of booleans, determines in which directions periodic boundary conditions are applicable

masci_tools.util.xml.xml_getters.get_nkpts(xmltree, schema_dict, logger=None)[source]

Get the number of kpoints that will be used in the calculation specified in the given fleur XMl file.

Warning

For file versions before Max5 only kPointList or kPointCount tags will work. However, for kPointCount there is no real guarantee that for every occasion it will correspond to the number of kpoints. So a warning is written out

Parameters:
Return type:

int

Returns:

int with the number of kpoints

masci_tools.util.xml.xml_getters.get_nkpts_max4(xmltree, schema_dict, logger=None)[source]

Get the number of kpoints that will be used in the calculation specified in the given fleur XMl file. Version specific for Max4 versions or older

Warning

For file versions before Max5 only kPointList or kPointCount tags will work. However, for kPointCount there is no real guarantee that for every occasion it will correspond to the number of kpoints. So a warning is written out

Parameters:
Return type:

int

Returns:

int with the number of kpoints

masci_tools.util.xml.xml_getters.get_parameter_data(*args, **kwargs)[source]

RENAMED TO get_parameterdata

Return type:

dict[str, Any]

masci_tools.util.xml.xml_getters.get_parameterdata(xmltree, schema_dict, inpgen_ready=True, write_ids=True, extract_econfig=False, allow_special_los=True, logger=None)[source]

This routine returns an python dictionary produced from the inp.xml file, which contains all the parameters needed to setup a new inp.xml from a inpgen input file to produce the same input (for parameters that the inpgen can control)

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – etree representing the fleur xml file

  • schema_dict (InputSchemaDict | OutputSchemaDict) – schema dictionary corresponding to the file version of the xmltree

  • inpgen_ready (bool) – Bool, return a dict which can be inputted into inpgen while setting atoms

  • write_ids (bool) – Bool, if True the atom ids are added to the atom namelists

  • logger (Optional[Logger]) – logger object for logging warnings, errors

Return type:

dict[str, Any]

Returns:

dict, which will lead to the same inp.xml (in case if other defaults, which can not be controlled by input for inpgen, were changed)

masci_tools.util.xml.xml_getters.get_relaxation_information(xmltree, schema_dict, logger=None)[source]

Get the relaxation information from the given fleur XML file. This includes the current displacements, energy and posforce evolution

Parameters:
Return type:

dict[str, Any]

Returns:

dict with the relaxation information

Raises:

ValueError – If no relaxation section is included in the xml tree

masci_tools.util.xml.xml_getters.get_relaxation_information_pre029(xmltree, schema_dict, logger=None)[source]

Get the relaxation information from the given fleur XML file. This includes the current displacements, energy and posforce evolution

Parameters:
Return type:

dict[str, Any]

Returns:

dict with the relaxation information

Raises:

ValueError – If no relaxation section is included in the xml tree

masci_tools.util.xml.xml_getters.get_special_kpoints(xmltree, schema_dict, name=None, index=None, only_used=False, logger=None)[source]

Extract the labeled special kpoints from the given kpointlist

Warning

Only implemented for versions starting with Max5

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – etree representing the fleur xml file

  • schema_dict (InputSchemaDict | OutputSchemaDict) – schema dictionary corresponding to the file version of the xmltree

  • name (Optional[str]) – str, optional, if given only the kpoint set with the given name is returned

  • index (Optional[int]) – int, optional, if given only the kpoint set with the given index is returned

  • only_used (bool) – bool if True only the kpoint list used in the calculation is returned

  • logger (Optional[Logger]) – logger object for logging warnings, errors

Return type:

list[tuple[int, str]] | dict[str, list[tuple[int, str]]]

Returns:

list of tuples (index, label) for multiple kpoint sets a dict with the names containing the list of tuples is returned

masci_tools.util.xml.xml_getters.get_special_kpoints_max4(xmltree, schema_dict, name=None, index=None, only_used=False, logger=None)[source]

Extract the labeled special kpoints from the given kpointlist

Warning

Only implemented for versions starting with Max5

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – etree representing the fleur xml file

  • schema_dict (InputSchemaDict | OutputSchemaDict) – schema dictionary corresponding to the file version of the xmltree

  • name (Optional[str]) – str, optional, if given only the kpoint set with the given name is returned

  • index (Optional[int]) – int, optional, if given only the kpoint set with the given index is returned

  • only_used (bool) – bool if True only the kpoint list used in the calculation is returned

  • logger (Optional[Logger]) – logger object for logging warnings, errors

Return type:

list[tuple[int, str]] | dict[str, list[tuple[int, str]]]

Returns:

list of tuples (index, label) for multiple kpoint sets a dict with the names containing the list of tuples is returned

masci_tools.util.xml.xml_getters.get_structure_data(*args, **kwargs)[source]

RENAMED TO get_structuredata

Return type:

tuple[list[AtomSiteProperties], ndarray, tuple[bool, bool, bool]]

masci_tools.util.xml.xml_getters.get_structuredata(xmltree, schema_dict, include_relaxations=True, convert_to_angstroem=True, normalize_kind_name=True, extract_magnetic_moments=True, logger=None, **kwargs)[source]

Get the structure defined in the given fleur xml file.

Warning

Only the explicit definition of the Bravais matrix is supported. Old inputs containing the latnam definitions are not supported

Warning

In versions 0.5.0 or later the output of the atom sites was restructured to be more interoperable with other IO functions (e.g. write_inpgen_file()) The new format returns a list of AtomSiteProperties instead of the list of tuples (position, symbol)

For better compatibility this output is not default in 0.5.0 but instead is enabled by site_namedtuple=True and a DeprecationWarning is given when this argument is False.

Note

In versions 0.5.0 or later the returned atom positions correspond to the relaxed structure if a relaxation section is present in the xmltree

Parameters:
  • xmltree (Union[_Element, _ElementTree]) – etree representing the fleur xml file

  • schema_dict (InputSchemaDict | OutputSchemaDict) – schema dictionary corresponding to the file version of the xmltree

  • include_relaxations (bool) – bool if True and a relaxation section is included the resulting positions correspond to the relaxed structure

  • logger (Optional[Logger]) – logger object for logging warnings, errors

  • convert_to_angstroem (bool) – bool if True the bravais matrix is converted to angstroem

  • extract_magnetic_moments (bool) – bool, if True (default) the magnetic moments are also extracted and put onto the atom_data output

Return type:

tuple[list[AtomSiteProperties], ndarray, tuple[bool, bool, bool]]

Returns:

tuple containing the structure information

The tuple contains the following entries:

  1. atom_data:

    list of (named)tuples containing the absolute positions and symbols of the atoms

  2. cell:

    numpy array, bravais matrix of the given system

  3. pbc:

    list of booleans, determines in which directions periodic boundary conditions are applicable

Changed in version 0.7.0: The default for site_namedtuple is set to True

Changed in version 0.10.0: The argument site_namedtuple was deprecated. The old output is no longer supported. If the argument site_namedtuple is passed a deprecation warning is shown

masci_tools.util.xml.xml_getters.get_symmetry_information(xmltree, schema_dict, logger=None)[source]

Get the symmetry information from the given fleur XML file. This includes the rotation matrices and shifts defined in the symmetryOperations tag.

Note

Only the explicit definition of the used symmetry operations in the xml file is supported.

Parameters:
Return type:

tuple[list[ndarray], list[ndarray]]

Returns:

tuple of the rotations and their respective shifts

Raises:

ValueError – If no symmetryOperations section is included in the xml tree

Basic IO helper functions

Here commonly used functions that do not need aiida-stuff (i.e. can be tested without a database) are collected.

class masci_tools.io.common_functions.AtomSiteProperties(position: list[float], symbol: str, kind: str, magnetic_moment: Literal['up', 'down'] | float | list[float] | None = None)[source]

namedtuple used for input output of atom sites

kind: str

Alias for field number 2

magnetic_moment: Union[Literal['up', 'down'], float, list[float], None]

Alias for field number 3

position: list[float]

Alias for field number 0

symbol: str

Alias for field number 1

masci_tools.io.common_functions._TVectorType

Generic type variable for atom position types

alias of TypeVar(‘_TVectorType’, bound=Union[Tuple[float, float, float], List[float], ndarray])

masci_tools.io.common_functions.abs_to_rel(vector, cell)[source]

Converts a position vector in absolute coordinates to relative coordinates.

Parameters:
Return type:

TypeVar(_TVectorType, bound= Union[Tuple[float, float, float], List[float], ndarray])

Returns:

list of length 3 of scaled vector, or False if vector was not length 3

masci_tools.io.common_functions.abs_to_rel_f(vector, cell, pbc)[source]

Converts a position vector in absolute coordinates to relative coordinates for a film system.

Parameters:
Return type:

TypeVar(_TVectorType, bound= Union[Tuple[float, float, float], List[float], ndarray])

Returns:

list of length 3 of scaled vector, or False if vector was not length 3

masci_tools.io.common_functions.angles_to_vec(magnitude, theta, phi)[source]

convert (magnitude, theta, phi) to (x,y,z)

theta/phi need to be in radians!

Input can be single number, list of numpy.ndarray data Returns x,y,z vector

Return type:

ndarray

masci_tools.io.common_functions.camel_to_snake(name)[source]

Converts camelCase to snake_case variable names Used in the Fleur parser to convert attribute names from the xml files

Return type:

str

masci_tools.io.common_functions.convert_to_fortran(val, quote_strings=True)[source]
Parameters:

val (Any) – the value to be read and converted to a Fortran-friendly string.

Return type:

str

masci_tools.io.common_functions.convert_to_fortran_string(string)[source]

converts some parameter strings to the format for the inpgen :type string: str :param string: some string :rtype: str :returns: string in right format (extra “” if not already present)

masci_tools.io.common_functions.convert_to_pystd(value)[source]

Recursively convert numpy datatypes to standard python, needed by aiida-core.

Return type:

Any

Usage:

converted = convert_to_pystd(to_convert)

where to_convert can be a dict, array, list, or single valued variable

masci_tools.io.common_functions.fac(n)[source]

Returns the factorial of n

Return type:

int

masci_tools.io.common_functions.filter_out_empty_dict_entries(dict_to_filter)[source]

Filter out entries in a given dict that correspond to empty values. At the moment this is empty lists, dicts and None

Parameters:

dict_to_filter (dict) – dict to filter

Return type:

dict

Returns:

dict without empty entries

masci_tools.io.common_functions.find_symmetry_relation(from_pos, to_pos, rotations, shifts, cell, relative_pos=False, film=False)[source]

Find symmetry relation between the given vectors. This functions assumes that a symmetry relation exists otherwise an error is raised

Parameters:
Return type:

tuple[ndarray, ndarray]

Returns:

tuple of rotation and shift mapping from_pos to to_pos

Raises:

ValueError – If no symmetry relation is found

masci_tools.io.common_functions.get_corestates_from_potential(potfile='potential')[source]

Read core states from potential file

Return type:

tuple[list, list, list]

masci_tools.io.common_functions.get_ef_from_potfile(potfile)[source]

extract fermi energy from potfile

Return type:

float

masci_tools.io.common_functions.get_highest_core_state(nstates, energies, lmoments)[source]

Find highest lying core state from list of core states, needed to find and check energy contour

Return type:

tuple[int, float, str]

masci_tools.io.common_functions.get_outfile_txt(outfile)[source]

Get the content of a file In case the outfile is a file handle, we just roll it back and read everything in again. For an ordinary file path we open the file in a context manager and then read it.

masci_tools.io.common_functions.get_pauli_matrix(direction, alpha=0.0, beta=0.0)[source]

Get the pauli matrix with additional rotation applied

Parameters:
  • direction (Literal['x', 'y', 'z']) – str (x,y or z) for which pauli matrix to return

  • alpha (float) – angle in radians

  • beta (float) – angle in radians

Return type:

ndarray

masci_tools.io.common_functions.get_spin_rotation(alpha, beta)[source]

Get matrix to rotate the spin frame by the given angles alpha/beta

Parameters:
  • alpha (float) – angle in radians

  • beta (float) – angle in radians

Return type:

ndarray

masci_tools.io.common_functions.get_wigner_matrix(l, alpha, beta, gamma=0.0, inverse=False)[source]

Produces the wigner rotation matrix for the density matrix

Parameters:
  • l (int) – int, orbital quantum number

  • alpha (float) – float, angle (radian) corresponds to euler angle alpha

  • beta (float) – float, angle (radian) corresponds to euler angle beta

  • gamma (float) – float, angle (radian) corresponds to euler angle gamma

Return type:

ndarray

masci_tools.io.common_functions.interpolate_dos(dosfile, return_original=False)[source]

interpolation function copied from complexdos3 fortran code

Principle of DOS here: Two-point contour integration for DOS in the middle of the two points. The input DOS and energy must be complex. Parameter deltae should be of the order of magnitude of eim:

      <-2*deltae->   _
           /\        |     DOS=(n(1)+n(2))/2 + (n(1)-n(2))*eim/deltae
          /  \       |
        (1)  (2)   2*i*eim=2*i*pi*Kb*Tk
        /      \     |
       /        \    |
------------------------ (Real E axis)
Parameters:

input – either absolute path of ‘complex.dos’ file or file handle to it

Returns:

E_Fermi, numpy array of interpolated dos

Note:

output units are in Ry!

masci_tools.io.common_functions.is_sequence(arg)[source]

Checks if arg is a sequence

Return type:

bool

masci_tools.io.common_functions.open_general(filename_or_handle, iomode=None)[source]

Open a file directly from a path or use a file handle if that is given. Also take care of closed files by reopenning them. This is intended to be used like this:

with open_general(outfile) as f:
    txt = f.readlines()
Return type:

IO[Any]

masci_tools.io.common_functions.rel_to_abs(vector, cell)[source]

Converts a position vector in internal coordinates to absolute coordinates in Angstrom.

Parameters:
Return type:

TypeVar(_TVectorType, bound= Union[Tuple[float, float, float], List[float], ndarray])

Returns:

list of length 3 of scaled vector, or False if vector was not length 3

masci_tools.io.common_functions.rel_to_abs_f(vector, cell)[source]

Converts a position vector in internal coordinates to absolute coordinates in Angstrom for a film structure (2D).

Return type:

TypeVar(_TVectorType, bound= Union[Tuple[float, float, float], List[float], ndarray])

masci_tools.io.common_functions.skipHeader(seq, n)[source]

Iterate over a sequence skipping the first n elements

Return type:

Generator[Any, None, None]

Args:

seq (iterable): Iterable sequence n (int): Number of Elements to skip in the beginning of the sequence

Yields:

item: Elements in seq after the first n elements

masci_tools.io.common_functions.vec_to_angles(vec)[source]

converts vector (x,y,z) to (magnitude, theta, phi)

Return type:

tuple[ndarray, ndarray, ndarray] | tuple[float, float, float]

Small utility functions for inspecting hdf files and converting the complete file structure into a python dictionary

masci_tools.io.hdf5_util.h5dump(file, group='/')[source]

Shows the overall filestructure of an hdf file Goes through all groups and subgroups and prints the attributes or the shape and datatype of the datasets

Parameters:

filepath – path to the hdf file

Return type:

None

masci_tools.io.hdf5_util.hdfList(name, obj)[source]

Print the name of the current object (indented to create a nice tree structure)

Also prints attribute values and dataset shapes and datatypes

Return type:

None

masci_tools.io.hdf5_util.read_groups(hdfdata, flatten=False)[source]

Recursive function to read a hdf datastructure and extract the datasets and attributes

Parameters:
  • hdfdata (Group) – current hdf group to process

  • flatten (bool) – bool, if True the dictionary will be flattened (does not check for lost information)

Return type:

tuple[dict[str, Any], dict[str, Any]]

Returns:

two dictionaries, one with the datasets the other with the attributes in the file

masci_tools.io.hdf5_util.read_hdf_simple(file, flatten=False)[source]

Reads in an hdf file and returns its context in a nested dictionary

Parameters:
  • filepath – path or filehandle to the hdf file

  • flatten (bool) – bool, if True the dictionary will be flattened (does not check for lost information)

Return type:

tuple[dict[str, Any], dict[str, Any]]

Returns:

two dictionaries, one with the datasets the other with the attributes in the file

Non unique group attribute or dataset names will be overwritten in the return dict

Logging Utility

This module defines useful utility for logging related functionality

class masci_tools.util.logging_util.DictHandler(log_dict, ignore_unknown_levels=False, **kwargs)[source]

Custom Handler for the logging module inserting logging messages into a given dictionary.

Messages are grouped into list under the names of the error categories. Keyword arguments can be used to modify the keys for the different levels

emit(record)[source]

Emit a record.

Return type:

None

class masci_tools.util.logging_util.OutParserLogAdapter(logger, extra=None)[source]

This adapter expects the passed in dict-like object to have a ‘iteration’ key, whose value is prepended as [Iteration i] to the message

process(msg, kwargs)[source]

Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword args or both. Return the message and kwargs modified (or not) to suit your needs.

Normally, you’ll only need to override this one method in a LoggerAdapter subclass for your specific needs.

Return type:

tuple[str, dict[str, Any]]

Fleur parser utility

This module contains helper functions for extracting information easily from the schema_dicts defined for the Fleur input/output

Also provides convenient functions to use just a attribute name for extracting the attribute from the right place in the given etree

masci_tools.util.schema_dict_util.attrib_exists(node, schema_dict, name, logger=None, iteration_path=False, filters=None, **kwargs)[source]

Evaluates whether the attribute exists in the xmltree based on the given name and additional further specifications with the available type information

Parameters:
  • node (Union[_Element, _ElementTree, XPathElementEvaluator]) – etree Element, on which to execute the xpath evaluations

  • schema_dict (SchemaDict) – dict, containing all the path information and more

  • name (str) – str, name of the attribute

  • logger (Optional[Logger]) – logger object for logging warnings, errors, if not provided all errors will be raised

  • iteration_path (bool) – bool if True and the SchemaDict is of an output schema an absolute path into the iteration element is constructed

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

Kwargs:
param tag_name:

str, name of the tag where the attribute should be parsed

param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

param exclude:

list of str, here specific types of attributes can be excluded valid values are: settable, settable_contains, other

Return type:

bool

Returns:

bool, True if any tag with the attribute exists

masci_tools.util.schema_dict_util.ensure_relaxation_xinclude(xmltree, schema_dict)[source]

Ensure that the xinclude tag for the relax.xml is added if no relaxation is present in the inp.xml

Parameters:
  • xmltree (_ElementTree) – an xml-tree which will be processed

  • schema_dict (InputSchemaDict) – Schema dictionary containing all the necessary information

Return type:

None

Returns:

xmltree, which either contains the relaxation section or a xinclude tag

masci_tools.util.schema_dict_util.eval_simple_xpath(node, schema_dict, name, logger=None, iteration_path=False, filters=None, list_return=False, **kwargs)[source]

Evaluates a simple xpath expression of the tag in the xmltree based on the given name and additional further specifications with the available type information

Parameters:
  • node (Union[_Element, _ElementTree, XPathElementEvaluator]) – etree Element, on which to execute the xpath evaluations

  • schema_dict (SchemaDict) – dict, containing all the path information and more

  • name (str) – str, name of the tag

  • logger (Optional[Logger]) – logger object for logging warnings, errors, if not provided all errors will be raised

  • iteration_path (bool) – bool if True and the SchemaDict is of an output schema an absolute path into the iteration element is constructed

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

  • list_return (bool) – bool, if True a list is always returned

Kwargs:
param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

Return type:

_Element | list[_Element]

Returns:

etree Elements obtained via the simple xpath expression

masci_tools.util.schema_dict_util.evaluate_attribute(node, schema_dict, name, constants=None, logger=None, complex_xpath=None, filters=None, iteration_path=False, **kwargs)[source]

Evaluates the value of the attribute based on the given name and additional further specifications with the available type information

Parameters:
  • node (Union[_Element, _ElementTree, XPathElementEvaluator]) – etree Element, on which to execute the xpath evaluations

  • schema_dict (SchemaDict) – dict, containing all the path information and more

  • name (str) – str, name of the attribute

  • constants (Optional[dict[str, float]]) – dict, contains the defined constants

  • logger (Optional[Logger]) – logger object for logging warnings, errors, if not provided all errors will be raised

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • iteration_path (bool) – bool if True and the SchemaDict is of an output schema an absolute path into the iteration element is constructed

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

Kwargs:
param tag_name:

str, name of the tag where the attribute should be parsed

param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

param exclude:

list of str, here specific types of attributes can be excluded valid values are: settable, settable_contains, other

param list_return:

if True, the returned quantity is always a list even if only one element is in it

param optional:

bool, if True and no logger given none or an empty list is returned

Return type:

Any

Returns:

list or single value, converted in convert_xml_attribute

masci_tools.util.schema_dict_util.evaluate_parent_tag(node, schema_dict, name, constants=None, logger=None, complex_xpath=None, iteration_path=False, filters=None, **kwargs)[source]

Evaluates all attributes of the parent tag based on the given name and additional further specifications with the available type information

Parameters:
  • node (Union[_Element, _ElementTree, XPathElementEvaluator]) – etree Element, on which to execute the xpath evaluations

  • schema_dict (SchemaDict) – dict, containing all the path information and more

  • name (str) – str, name of the tag

  • constants (Optional[dict[str, float]]) – dict, contains the defined constants

  • logger (Optional[Logger]) – logger object for logging warnings, errors, if not provided all errors will be raised

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • iteration_path (bool) – bool if True and the SchemaDict is of an output schema an absolute path into the iteration element is constructed

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

Kwargs:
param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

param only_required:

bool (optional, default False), if True only required attributes are parsed

param ignore:

list of str (optional), attributes not to parse

param list_return:

if True, the returned quantity is always a list even if only one element is in it

param strict_missing_error:

if True, and no logger is given an error is raised if any attribute is not found

Return type:

Any

Returns:

dict, with attribute values converted via convert_xml_attribute

masci_tools.util.schema_dict_util.evaluate_single_value_tag(node, schema_dict, name, constants=None, logger=None, complex_xpath=None, **kwargs)[source]

Evaluates the value and unit attribute of the tag based on the given name and additional further specifications with the available type information

Parameters:
Kwargs:
param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

param only_required:

bool (optional, default False), if True only required attributes are parsed

param ignore:

list of str (optional), attributes not to parse

param list_return:

if True, the returned quantity is always a list even if only one element is in it

param strict_missing_error:

if True, and no logger is given an error is raised if any attribute is not found

param iteration_path:

bool if True and the SchemaDict is of an output schema an absolute path into the iteration element is constructed

param filters:

Dict specifying constraints to apply on the xpath. See XPathBuilder for details

Return type:

Any

Returns:

value and unit, both converted in convert_xml_attribute

masci_tools.util.schema_dict_util.evaluate_tag(node, schema_dict, name, constants=None, logger=None, subtags=False, text=True, complex_xpath=None, iteration_path=False, filters=None, **kwargs)[source]

Evaluates all attributes of the tag based on the given name and additional further specifications with the available type information

Parameters:
  • node (Union[_Element, _ElementTree, XPathElementEvaluator]) – etree Element, on which to execute the xpath evaluations

  • schema_dict (SchemaDict) – dict, containing all the path information and more

  • name (str) – str, name of the tag

  • constants (Optional[dict[str, float]]) – dict, contains the defined constants

  • logger (Optional[Logger]) – logger object for logging warnings, errors, if not provided all errors will be raised

  • subtags (bool) – optional bool, if True the subtags of the given tag are evaluated

  • text (bool) – optional bool, if True the text of the tag is also parsed

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • iteration_path (bool) – bool if True and the SchemaDict is of an output schema an absolute path into the iteration element is constructed

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

Kwargs:
param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

param only_required:

bool (optional, default False), if True only required attributes are parsed

param ignore:

list of str (optional), attributes not to parse

param list_return:

if True, the returned quantity is always a list even if only one element is in it

param strict_missing_error:

if True, and no logger is given an error is raised if any attribute is not found

Return type:

Any

Returns:

dict, with attribute values converted via convert_xml_attribute

masci_tools.util.schema_dict_util.evaluate_text(node, schema_dict, name, constants=None, logger=None, complex_xpath=None, iteration_path=False, filters=None, **kwargs)[source]

Evaluates the text of the tag based on the given name and additional further specifications with the available type information

Parameters:
  • node (Union[_Element, _ElementTree, XPathElementEvaluator]) – etree Element, on which to execute the xpath evaluations

  • schema_dict (SchemaDict) – dict, containing all the path information and more

  • name (str) – str, name of the tag

  • constants (Optional[dict[str, float]]) – dict, contains the defined constants

  • logger (Optional[Logger]) – logger object for logging warnings, errors, if not provided all errors will be raised

  • complex_xpath (Union[str, bytes, XPath, XPathBuilder, None]) – an optional xpath to use instead of the simple xpath for the evaluation

  • iteration_path (bool) – bool if True and the SchemaDict is of an output schema an absolute path into the iteration element is constructed

  • filters (Optional[Dict[str, Any]]) – Dict specifying constraints to apply on the xpath. See XPathBuilder for details

Kwargs:
param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

param list_return:

if True, the returned quantity is always a list even if only one element is in it

param optional:

bool, if True and no logger given none or an empty list is returned

Return type:

Any

Returns:

list or single value, converted in convert_xml_text

masci_tools.util.schema_dict_util.get_number_of_nodes(node, schema_dict, name, logger=None, **kwargs)[source]

Evaluates the number of occurrences of the tag in the xmltree based on the given name and additional further specifications with the available type information

Parameters:
Kwargs:
param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

param iteration_path:

bool if True and the SchemaDict is of an output schema an absolute path into the iteration element is constructed

param filters:

Dict specifying constraints to apply on the xpath. See XPathBuilder for details

Return type:

int

Returns:

number of nodes for the given tag

masci_tools.util.schema_dict_util.read_constants(root, schema_dict, logger=None)[source]

Reads in the constants defined in the inp.xml and returns them combined with the predefined constants from fleur as a dictionary

Parameters:
Return type:

dict[str, float]

Returns:

a python dictionary with all defined constants

masci_tools.util.schema_dict_util.reverse_xinclude(xmltree, schema_dict, included_tags, **kwargs)[source]

Split the xmltree back up according to the given included tags. The original xmltree will be returned with the corresponding xinclude tags and the included trees are returned in a dict mapping the inserted filename to the extracted tree

Tags for which no known filename is known are returned under unknown-1.xml, … The following tags have known filenames:

  • relaxation: relax.xml

  • kPointLists: kpts.xml

  • symmetryOperations: sym.xml

  • atomSpecies: species.xml

  • atomGroups: atoms.xml

Additional mappings can be given in the keyword arguments

Parameters:
  • xmltree (_ElementTree) – an xml-tree which will be processed

  • schema_dict (InputSchemaDict) – Schema dictionary containing all the necessary information

  • included_tags (Iterable[str]) – Iterable of str, containing the names of the tags to be excluded

Return type:

tuple[_ElementTree, dict[PathLike | str, _ElementTree]]

Returns:

xmltree with the inseerted xinclude tags and a dict mapping the filenames to the excluded trees

Raises:

ValueError – if the tag can not be found in the given xmltree

masci_tools.util.schema_dict_util.tag_exists(node, schema_dict, name, logger=None, **kwargs)[source]

Evaluates whether the tag exists in the xmltree based on the given name and additional further specifications with the available type information

Parameters:
Kwargs:
param contains:

str, this string has to be in the final path

param not_contains:

str, this string has to NOT be in the final path

param iteration_path:

bool if True and the SchemaDict is of an output schema an absolute path into the iteration element is constructed

param filters:

Dict specifying constraints to apply on the xpath. See XPathBuilder for details

Return type:

bool

Returns:

bool, True if any nodes with the path exist

This module contains the functions necessary to parse mathematical expressions with predefined constants given in the inp.xml file of Fleur

exception masci_tools.util.fleur_calculate_expression.MissingConstant[source]

Exception raised when a constant appearing in a expression is not defined

masci_tools.util.fleur_calculate_expression.calculate_expression(expression, constants=None)[source]

Recursively evaluates the given expression string with the given defined constants

Parameters:
  • expression (str | float | int) – str containing the expression to be parsed

  • constants (Optional[dict[str, float]]) – dict with all defined constants (predefined in the Fleur code or defined in the inp.xml)

Return type:

float | int

Returns:

float value of the given expression string

masci_tools.util.fleur_calculate_expression.calculate_expression_partial(expression, constants=None, prevCommand=None)[source]

Recursively evaluates the given expression string with the given defined constants and returns the unevaluated part of the expression

Parameters:
  • expression (str | float | int) – str containing the expression to be parsed

  • constants (Optional[dict[str, float]]) – dict with all defined constants (predefined in the Fleur code or defined in the inp.xml)

  • prevCommand (Optional[str]) – str, which gives the command before the beginning of the current block if it is given the calculation is stopped, when a command is encountered, which should be exectuted after prevCommand (order of operations)

Return type:

tuple[float | int, str]

Returns:

float value of the given expression string

masci_tools.util.fleur_calculate_expression.evaluate_bracket(expression, constants)[source]

Evaluates the bracket opened at the start of the expression

Parameters:
  • expression (str) – expression to be parsed

  • constants (dict[str, float]) – dict with defined constants

Return type:

tuple[float | int, str]

Returns:

value of the expression inside the brackets and remaining string of the expression after the corresponding closed bracket

masci_tools.util.fleur_calculate_expression.get_first_number(expression)[source]

Reads the number in the beginning of the expression string. This number can begin with a sign +-, a number or the decimal point

Parameters:

expression (str) – str of the expression

Return type:

tuple[float, str]

Returns:

float value of the number in the beginning and the string of the remaining expression

masci_tools.util.fleur_calculate_expression.get_first_string(expression)[source]

Reads the letter string in the beginning of the expression string.

Parameters:

expression (str) – str of the expression

Return type:

tuple[str, str]

Returns:

letter string in the beginning and the string of the remaining expression

This module contains custom conversion functions for the outxml_parser, which cannot be handled by the standard parsing framework

masci_tools.io.parsers.fleur.outxml_conversions.calculate_total_magnetic_moment(out_dict, logger)[source]

Calculate the the total magnetic moment per cell

Parameters:

out_dict (dict[str, Any]) – dict with the already parsed information

Return type:

dict[str, Any]

masci_tools.io.parsers.fleur.outxml_conversions.calculate_walltime(out_dict, logger)[source]

Calculate the walltime from start and end time

Parameters:
  • out_dict (dict[str, Any]) – dict with the already parsed information

  • logger (Logger) – logger object for logging warnings, errors, if not provided all errors will be raised

Return type:

dict[str, Any]

masci_tools.io.parsers.fleur.outxml_conversions.convert_forces(out_dict, logger)[source]

Convert the parsed forces from a iteration

Parameters:

out_dict (dict[str, Any]) – dict with the already parsed information

Return type:

dict[str, Any]

masci_tools.io.parsers.fleur.outxml_conversions.convert_htr_to_ev(out_dict, name, converted_name=None, pop=False, add_unit=True, logger=None)[source]

Convert value from htr to eV

Return type:

dict[str, Any]

masci_tools.io.parsers.fleur.outxml_conversions.convert_ldahia_definitions(out_dict, logger)[source]

Convert the parsed information from LDA+U into a more readable dict

ldau_info has keys for each species with LDA+U ({species_name}/{atom_number}) and this in turn contains a dict with the LDA+U definition for the given orbital (spdf)

Parameters:

out_dict (dict[str, Any]) – dict with the already parsed information

Return type:

dict[str, Any]

masci_tools.io.parsers.fleur.outxml_conversions.convert_ldau_definitions(out_dict, logger)[source]

Convert the parsed information from LDA+U into a more readable dict

ldau_info has keys for each species with LDA+U ({species_name}/{atom_number}) and this in turn contains a dict with the LDA+U definition for the given orbital (spdf)

Parameters:

out_dict (dict[str, Any]) – dict with the already parsed information

Return type:

dict[str, Any]

masci_tools.io.parsers.fleur.outxml_conversions.convert_relax_info(out_dict, logger)[source]

Convert the general relaxation information

Parameters:

out_dict (dict[str, Any]) – dict with the already parsed information

Return type:

dict[str, Any]

Functions for expanding/splitting or converting electron configuration strings

masci_tools.util.econfig.convert_fleur_config_to_econfig(fleurconf_str, keep_spin=False)[source]

‘[Kr] (4d3/2) (4d5/2) (4f5/2) (4f7/2)’ -> ‘[Kr] 4d10 4f14’, or ‘[Kr] 4d3/2 4d5/2 4f5/2 4f7/2’

# for now only use for coreconfig, it will fill all orbitals, since it has no information on the filling.

Parameters:
  • fleurconf_str (str) – string of the electron config like it is read from the inp.xml

  • keep_spin (bool) – bool if True the spin indices will be kept in the converted string

Return type:

str

Returns:

string of the electron config to be used in the inpgen

masci_tools.util.econfig.get_coreconfig(element, full=False)[source]

returns the econfiguration as a string of an element.

Parameters:
  • element (str | int) – element string

  • full (bool) – a bool if True the econfig without [He]… is returned

Return type:

Optional[str]

Returns:

coreconfig string

masci_tools.util.econfig.get_econfig(element, full=False)[source]

returns the econfiguration as a string of an element.

Parameters:
  • element (str | int) – element string

  • full (bool) – a bool if True the econfig without [He]… is returned

Return type:

Optional[str]

Returns:

a econfig string

masci_tools.util.econfig.rek_econ(econfigstr)[source]

recursive routine to return a full econfig ‘[Xe] 4f14 | 5d10 6s2 6p4’ -> ‘1s 2s … 4f14 | 5d10 6s2 6p4’

Parameters:

econfigstr (str) – electron config string to expand

Return type:

Optional[str]

Returns:

expanded econfig string

Basic Fleur Schema parser functions

Load all fleur schema related functions

class masci_tools.io.parsers.fleur_schema.AttributeType(base_type: str, length: int | Literal['unbounded'] | None)[source]

Type for describing the types of attributes/text

exception masci_tools.io.parsers.fleur_schema.IncompatibleSchemaVersions[source]

Exception raised when it is known that a given output version and input version cannot be compiled into a complete fleur output xml schema

class masci_tools.io.parsers.fleur_schema.InputSchemaDict(*args, xmlschema=None, **kwargs)[source]

This class contains information parsed from the FleurInputSchema.xsd

The keys contain the following information:

inp_version:

Version string of the input schema represented in this object

tag_paths:

simple xpath expressions to all valid tag names Multiple paths or ambiguous tag names are parsed as a list

_basic_types:

Parsed definitions of all simple Types with their respective base type (int, float, …) and evtl. length restrictions (Only used in the schema construction itself)

attrib_types:

All possible base types for all valid attributes. If multiple are possible a list, with ‘string’ always last (if possible)

simple_elements:

All elements with simple types and their type definition with the additional attributes

unique_attribs:

All attributes and their paths, which occur only once and have a unique path

unique_path_attribs:

All attributes and their paths, which have a unique path but occur in multiple places

other_attribs:

All attributes and their paths, which are not in ‘unique_attribs’ or ‘unique_path_attribs’

omitt_contained_tags:

All tags, which only contain a list of one other tag

tag_info:

For each tag (path), the valid attributes and tags (optional, several, order, simple, text)

classmethod fromPath(path)[source]

load the FleurInputSchema dict for the specified FleurInputSchema file

Parameters:

path (PathLike) – path to the input schema file

Return type:

InputSchemaDict

Returns:

InputSchemaDict object with the information for the provided file

classmethod fromVersion(version, logger=None, no_cache=False)[source]

load the FleurInputSchema dict for the specified version

Parameters:
  • version (str) – str with the desired version, e.g. ‘0.33’

  • logger (Optional[Logger]) – logger object for warnings, errors and information, …

Return type:

InputSchemaDict

Returns:

InputSchemaDict object with the information for the provided version

property inp_version: tuple[int, int]

Returns the input version as an integer for comparisons (> or <)

exception masci_tools.io.parsers.fleur_schema.NoPathFound[source]

Exception raised when no path is found for a given tag/attribute

exception masci_tools.io.parsers.fleur_schema.NoUniquePathFound[source]

Exception raised when no unique path is found for a given tag/attribute

class masci_tools.io.parsers.fleur_schema.OutputSchemaDict(*args, xmlschema=None, **kwargs)[source]

This object contains information parsed from the FleurOutputSchema.xsd

The keys contain the following information:

out_version:

Version string of the output schema represented in this class

input_tag:

Name of the element containing the fleur input

iteration_tags:

Names of the elements that can contain all iteration tags

tag_paths:

simple xpath expressions to all valid tag names not in an iteration Multiple paths or ambiguous tag names are parsed as a list

iteration_tag_paths:

simple relative xpath expressions to all valid tag names inside an iteration. Multiple paths or ambiguous tag names are parsed as a list

_basic_types:

Parsed definitions of all simple Types with their respective base type (int, float, …) and evtl. length restrictions (Only used in the schema construction itself)

_input_basic_types:

Part of the parsed definitions of all simple Types with their respective base type (int, float, …) and evtl. length restrictions from the input schema (Only used in the schema construction itself)

attrib_types:

All possible base types for all valid attributes. If multiple are possible a list, with ‘string’ always last (if possible)

simple_elements:

All elements with simple types and their type definition with the additional attributes

unique_attribs:

All attributes and their paths, which occur only once and have a unique path outside of an iteration

unique_path_attribs:

All attributes and their paths, which have a unique path but occur in multiple places outside of an iteration

other_attribs:

All attributes and their paths, which are not in ‘unique_attribs’ or ‘unique_path_attribs’ outside of an iteration

iteration_unique_attribs:

All attributes and their relative paths, which occur only once and have a unique path inside of an iteration

iteration_unique_path_attribs:

All attributes and their relative paths, which have a unique path but occur in multiple places inside of an iteration

iteration_other_attribs:

All attributes and their relative paths, which are not in ‘unique_attribs’ or ‘unique_path_attribs’ inside of an iteration

omitt_contained_tags:

All tags, which only contain a list of one other tag

tag_info:

For each tag outside of an iteration (path), the valid attributes and tags (optional, several, order, simple, text)

iteration_tag_info:

For each tag inside of an iteration (relative path), the valid attributes and tags (optional, several, order, simple, text)

classmethod fromPath(path, inp_path=None, inpschema_dict=None)[source]

load the FleurOutputSchema dict for the specified paths

Parameters:
  • path (PathLike) – path to the FleurOutputSchema file

  • inp_path (Optional[PathLike]) – path to the FleurInputSchema file (defaults to same folder as path)

Return type:

OutputSchemaDict

Returns:

OutputSchemaDict object with the information for the provided files

classmethod fromVersion(version, inp_version=None, logger=None, no_cache=False)[source]

load the FleurOutputSchema dict for the specified version

Parameters:
  • version (str) – str with the desired version, e.g. ‘0.33’

  • inp_version (Optional[str]) – str with the desired input version, e.g. ‘0.33’ (defaults to version)

  • logger (Optional[Logger]) – logger object for warnings, errors and information, …

Return type:

OutputSchemaDict

Returns:

OutputSchemaDict object with the information for the provided versions

property inp_version: tuple[int, int]

Returns the input version as an integer for comparisons (> or <)

iteration_attrib_xpath(name, contains=None, not_contains=None, exclude=None, tag_name=None, iteration_tag='iteration')[source]

Tries to find a unique path from the schema_dict based on the given name of the attribute and additional further specifications in the iteration section of the out.xml and returns the absolute path to it

Parameters:
  • name (str) – str, name of the attribute

  • contains (Union[str, Iterable[str], None]) – str or list of str, this string has to be in the final path

  • not_contains (Union[str, Iterable[str], None]) – str or list of str, this string has to NOT be in the final path

  • exclude (Optional[Iterable[str]]) – list of str, here specific types of attributes can be excluded valid values are: settable, settable_contains, other

  • tag_name (Optional[str]) – str, if given this name will be used to find a path to a tag with the same name in iteration_tag_xpath()

  • iteration_tag (str) – name of the tag containing the iteration information

Return type:

str

Returns:

str, xpath to the tag with the given attribute

Raises:
iteration_tag_xpath(name, contains=None, not_contains=None, iteration_tag='iteration')[source]

Tries to find a unique path from the schema_dict based on the given name of the tag and additional further specifications in the iteration section of the out.xml and returns the absolute path to it

Parameters:
  • name (str) – str, name of the tag

  • contains (Union[str, Iterable[str], None]) – str or list of str, this string has to be in the final path

  • not_contains (Union[str, Iterable[str], None]) – str or list of str, this string has to NOT be in the final path

  • iteration_tag (str) – name of the tag containing the iteration information

Return type:

str

Returns:

str, xpath for the given tag

Raises:
property out_version: tuple[int, int]

Returns the output version as an integer for comparisons (> or <)

relative_iteration_attrib_xpath(name, root_tag, contains=None, not_contains=None, exclude=None, tag_name=None, iteration_tag='iteration')[source]

Tries to find a unique relative path from the schema_dict based on the given name of the attribute name of the root, from which the path should be relative and additional further specifications

Parameters:
  • schema_dict – dict, containing all the path information and more

  • name (str) – str, name of the attribute

  • root_tag (str) – str, name of the tag from which the path should be relative

  • contains (Union[str, Iterable[str], None]) – str or list of str, this string has to be in the final path

  • not_contains (Union[str, Iterable[str], None]) – str or list of str, this string has to NOT be in the final path

  • exclude (Optional[Iterable[str]]) – list of str, here specific types of attributes can be excluded valid values are: settable, settable_contains, other

  • tag_name (Optional[str]) – str, if given this name will be used to find a path to a tag with the same name in relative_iteration_tag_xpath()

  • iteration_tag (str) – name of the tag containing the iteration information

Return type:

str

Returns:

str, xpath for the given tag

Raises:
relative_iteration_tag_xpath(name, root_tag, contains=None, not_contains=None, iteration_tag='iteration')[source]

Tries to find a unique path from the schema_dict based on the given name of the tag and additional further specifications in the iteration section of the out.xml and returns the absolute path to it

Parameters:
  • name (str) – str, name of the tag

  • contains (Union[str, Iterable[str], None]) – str or list of str, this string has to be in the final path

  • not_contains (Union[str, Iterable[str], None]) – str or list of str, this string has to NOT be in the final path

  • iteration_tag (str) – name of the tag containing the iteration information

Return type:

str

Returns:

str, xpath for the given tag

Raises:
class masci_tools.io.parsers.fleur_schema.SchemaDict(*args, xmlschema=None, **kwargs)[source]

Base class for schema dictionaries. Is locked on initialization with freeze(). Holds a reference to the xmlSchema for validating files.

Also provides interfaces for utility functions

Parameters:

xmlschema (Optional[XMLSchema]) – etree.XMLSchema object for validating files

All other arguments are passed on to LockableDict

attrib_xpath(name, contains=None, not_contains=None, exclude=None, tag_name=None)[source]

Tries to find a unique path from the schema_dict based on the given name of the attribute and additional further specifications

Parameters:
  • name (str) – str, name of the attribute

  • contains (Union[str, Iterable[str], None]) – str or list of str, this string has to be in the final path

  • not_contains (Union[str, Iterable[str], None]) – str or list of str, this string has to NOT be in the final path

  • exclude (Optional[Iterable[str]]) – list of str, here specific types of attributes can be excluded valid values are: settable, settable_contains, other

  • tag_name (Optional[str]) – str, if given this name will be used to find a path to a tag with the same name in tag_xpath()

Return type:

str

Returns:

str, xpath to the tag with the given attribute

Raises:
classmethod clear_cache()[source]

Remove all stored entries in the schema dictionary cache

Return type:

None

relative_attrib_xpath(name, root_tag, contains=None, not_contains=None, exclude=None, tag_name=None)[source]

Tries to find a unique relative path from the schema_dict based on the given name of the attribute name of the root, from which the path should be relative and additional further specifications

Parameters:
  • schema_dict – dict, containing all the path information and more

  • name (str) – str, name of the attribute

  • root_tag (str) – str, name of the tag from which the path should be relative

  • contains (Union[str, Iterable[str], None]) – str or list of str, this string has to be in the final path

  • not_contains (Union[str, Iterable[str], None]) – str or list of str, this string has to NOT be in the final path

  • exclude (Optional[Iterable[str]]) – list of str, here specific types of attributes can be excluded valid values are: settable, settable_contains, other

  • tag_name (Optional[str]) – str, if given this name will be used to find a path to a tag with the same name in relative_tag_xpath()

Return type:

str

Returns:

str, xpath for the given tag

Raises:
relative_tag_xpath(name, root_tag, contains=None, not_contains=None)[source]

Tries to find a unique relative path from the schema_dict based on the given name of the tag name of the root, from which the path should be relative and additional further specifications

Parameters:
  • name (str) – str, name of the tag

  • root_tag (str) – str, name of the tag from which the path should be relative

  • contains (Union[str, Iterable[str], None]) – str or list of str, this string has to be in the final path

  • not_contains (Union[str, Iterable[str], None]) – str or list of str, this string has to NOT be in the final path

Return type:

str

Returns:

str, xpath for the given tag

Raises:

ValueError – If no unique path could be found

tag_info(name, contains=None, not_contains=None, parent=False)[source]

Tries to find a unique path from the schema_dict based on the given name of the tag and additional further specifications and returns the tag_info entry for this tag

Parameters:
  • schema_dict – dict, containing all the path information and more

  • name (str) – str, name of the tag

  • contains (Union[str, Iterable[str], None]) – str or list of str, this string has to be in the final path

  • not_contains (Union[str, Iterable[str], None]) – str or list of str, this string has to NOT be in the final path

  • parent (bool) – bool, if True the tag_info for the parent of the tag is returned

Return type:

TagInfo

Returns:

dict, tag_info for the found xpath

tag_xpath(name, contains=None, not_contains=None)[source]

Tries to find a unique path from the schema_dict based on the given name of the tag and additional further specifications

Parameters:
  • name (str) – str, name of the tag

  • contains (Union[str, Iterable[str], None]) – str or list of str, this string has to be in the final path

  • not_contains (Union[str, Iterable[str], None]) – str or list of str, this string has to NOT be in the final path

Return type:

str

Returns:

str, xpath for the given tag

Raises:
validate(xmltree, logger=None, header='')[source]

Validate the given XML tree against the schema

Parameters:
Return type:

None

masci_tools.io.parsers.fleur_schema.list_available_versions(output_schema)[source]

List the available versions for the schema

Parameters:

output_schema (bool) – bool, if True search for FleurOutputSchema.xsd otherwise FleurInputSchema.xsd

Return type:

list[str]

Returns:

list version string of the available versions

masci_tools.io.parsers.fleur_schema.schema_dict_version_dispatch(output_schema=False)[source]

Decorator for creating variations of functions based on the inp/out version of the schema_dict. All functions here need to have the signature:

def f(node, schema_dict, *args, **kwargs):
    pass

So schema_dict is the second positional argument

Inspired by singledispatch in the functools module

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], SchemaDictDispatch[TypeVar(F, bound= Callable[..., Any])]]

functions to extract information about the fleur schema input or output

class masci_tools.io.parsers.fleur_schema.fleur_schema_parser_functions.AttributeType(base_type: str, length: int | Literal['unbounded'] | None)[source]

Type for describing the types of attributes/text

class masci_tools.io.parsers.fleur_schema.fleur_schema_parser_functions.TagInfo[source]

Dict representing the entries for the tag information.

masci_tools.io.parsers.fleur_schema.fleur_schema_parser_functions.convert_str_version_number(version_str)[source]

Convert the version number as a integer for easy comparisons

Parameters:

version_str (str) – str of the version number, e.g. ‘0.33’

Return type:

tuple[int, int]

Returns:

tuple of ints representing the version str

masci_tools.io.parsers.fleur_schema.fleur_schema_parser_functions.eval_single_string_attribute(xmlschema_evaluator, xpath, **variables)[source]

Wrapper around the xpath calls in this module. Makes sure the return value is a single string (not cached)

Parameters:
  • xmlschema_evaluator – etree.XPathEvaluator for the schema

  • xpath – str, xpath expression to evaluate

masci_tools.io.parsers.fleur_schema.fleur_schema_parser_functions.extract_attribute_types(xmlschema_evaluator, **kwargs)[source]

Determine the required type of all attributes

Parameters:

xmlschema_evaluator (XPathDocumentEvaluator) – etree.XPathEvaluator for the schema

Return type:

CaseInsensitiveDict[str, list[AttributeType]]

Returns:

possible types of the attributes in a dictionary, if multiple types are possible a list is inserted for the tag

masci_tools.io.parsers.fleur_schema.fleur_schema_parser_functions.extract_text_types(xmlschema_evaluator, **kwargs)[source]

Determine the required type of all elements with text

Parameters:

xmlschema_evaluator (XPathDocumentEvaluator) – etree.XPathEvaluator for the schema

Return type:

CaseInsensitiveDict[str, list[AttributeType]]

Returns:

possible types of the attributes in a dictionary, if multiple types are possible a list is inserted for the tag

masci_tools.io.parsers.fleur_schema.fleur_schema_parser_functions.get_basic_types(xmlschema_ev