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:
- 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
- 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
- extend(other)[source]¶
S.extend(iterable) – extend sequence by appending elements from the iterable
- Return type:
- pop(i=-1)[source]¶
return the value at index i (default last) and remove it from list
- Return type:
TypeVar
(T
)
- 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)]
- 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)]
- 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
- 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
]
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.
- 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
- 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:
node (
Union
[_Element
,_ElementTree
,XPathElementEvaluator
]) – root node of an etree or an etreebase_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – str of the xpath without complex syntaxcomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – str of the xpath to check
- Raises:
ValueError – If the complex_xpath does not produce a subset of the results of the base_xpath
- Return type:
- 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
- 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:
- 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.
- masci_tools.util.xml.common_functions.is_valid_tag(tag)[source]¶
Return whether the given string is a valid XML tag name
- masci_tools.util.xml.common_functions.normalize_xmllike(xmllike)[source]¶
Returns the root of the xmltree
- Return type:
- 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:
simple_xpath (
str
|bytes
|XPath
) – THe simple XPath (no predicates) expression to base the paths oncomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
,None
]) – Optional XPath given with no restrictionsfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for details
- 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:
xmltree (
_ElementTree
) – representation of the inp.xml
- Return type:
- 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()
- 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
- 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
- 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 validateschema (
XMLSchema
) – etree.XMLSchema to validate againsterror_header (
str
) – str to lead a evtl error message with
- Raises:
etree.DocumentInvalid if the schema does not validate
- Return type:
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:
- 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:
- 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
- masci_tools.util.xml.converters.convert_from_fortran_complex(number_str)[source]¶
Converts a string of the form (float,float) to a 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 informationname (
str
) – name of the attribute or elementtext (
bool
) – bool, decides whether to take the definitions for text or attributesconstants (
Optional
[dict
[str
,float
]]) – dict, of constants defined in fleur inputlogger (
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 failslist_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 ofAttributeType
definitionsconstants (
Optional
[dict
[str
,float
]]) – dict, of constants defined in fleur inputlogger (
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 failslist_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 toconstants (
Optional
[dict
[str
,float
]]) – dict, of constants defined in fleur inputlogger (
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 failslist_return – if True, the returned quantity is always a list even if only one element is in it
- Return type:
- 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
- masci_tools.util.xml.converters.convert_to_fortran_bool(boolean)[source]¶
Converts a Boolean as string to the format defined in the input
- 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 informationname (
str
) – name of the attribute or elementtext (
bool
) – bool, decides whether to take the definitions for text or attributesconstants – 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 failslist_return (
bool
) – if True, the returned quantity is always a list even if only one element is in it
- Return type:
- 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 ofAttributeType
definitionslogger (
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 failslist_return (
bool
) – if True, the returned quantity is always a list even if only one element is in it
- Return type:
- 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:
possible_types (
tuple
[Literal
['int'
,'switch'
,'string'
,'float'
,'float_expression'
,'complex'
],...
]) – list of str What types it will try to convert fromlogger (
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 failslist_return – if True, the returned quantity is always a list even if only one element is in it
- Return type:
- 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
- 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 theadd_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 theadd_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 tocontains
: attribute/tag contains the given value (case sensitive)not-contains
: attribute/tag does not contains the given valuestarts-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/taghas-not
: Select tags based on the absence of the given attribute/tagnumber-nodes
: Compute the number of nodes in the previous path and select based on further criteriaand
: Provide multiple conditions in a list joined byand
or
: Provide multiple conditions in a list joined byor
in
: Select tags if the value of the path is in a given list of valuesnot-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 fromfilters (
Optional
[dict
[str
,Dict
[str
,Any
]]]) – dictionary with filterscompile_path (
bool
) – bool if True the path property will be compiled as etree.XPathstrict (
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
- 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 tagcondition (
Any
) – condition specified, either dict or single valuecompound (
bool
) – bool if True the enclosing condition is a compound condition, forbidding any other compound conditionpath (
str
|tuple
[str
,...
]) – path, to which to apply the conditionprocess_path (
bool
) – bool if True the path will taken apart into its components and the components will be checked with XPath variables
- Return type:
- 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 tagoperator (
str
) – operator for conditioncontent (
Any
) – content of conditionpath (
str
|tuple
[str
,...
]) – path, to which to apply the conditionprocess_path (
bool
) – bool if True the path will taken apart into its components and the components will be checked with XPath variables
- Return type:
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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputname (
str
) – the attribute name to changenumber_to_add (
Any
) – number to add/multiply with the old attribute valuecomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
,None
]) – an optional xpath to use instead of the simple xpath for the evaluationfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for detailsmode (
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_addoccurrences (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputname (
str
) – the attribute name to changenumber_to_add (
Any
) – number to add/multiply with the old attribute valuecomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
,None
]) – an optional xpath to use instead of the simple xpath for the evaluationmode (
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_addfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputspecies_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 specieschanges (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputtag (
QName
|str
|_Element
) – str of the tag to create or etree Element or string representing the XML element with the same name to insertcomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
,None
]) – an optional xpath to use instead of the simple xpath for the evaluationfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for detailscreate_parents (
bool
) – bool optional (default False), if True and the given xpath has no results the the parent tags are created recursivelyoccurrences (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputname (
str
) – str of the attribute to deletecomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
,None
]) – an optional xpath to use instead of the simple xpath for the evaluationfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for detailsoccurrences (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputtag – 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 evaluationfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for detailsoccurrences (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputtag – str of the tag to replace
element (
str
|_Element
) – etree Element or string representing the XML element to replace the tagcomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
,None
]) – an optional xpath to use instead of the simple xpath for the evaluationfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for detailsoccurrences (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputchanges (
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 changedspecies (
Optional
[str
]) – atom groups, corresponding to the given species will be changedfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for details
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputatom_label (
str
) – string, a label of the atom which specie will be changed. ‘all’ to change all the specieschanges (
dict
[str
,Any
]) – a python dict specifying what you want to change.
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputname (
str
) – the attribute name to setvalue (
Any
) – value or list of values to setcomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
,None
]) – an optional xpath to use instead of the simple xpath for the evaluationfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for detailsoccurrences (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputtag_name (
str
) – name of the tag to setchanges (
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 evaluationfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for detailscreate (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputname (
str
) – the attribute name to setvalue (
Any
) – value or list of values to setcomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
,None
]) – an optional xpath to use instead of the simple xpath for the evaluationfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for detailscreate (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputtag_name (
str
) – str name of the tag, where the text should be settext (
Any
) – value or list of values to setcomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
,None
]) – an optional xpath to use instead of the simple xpath for the evaluationfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for detailscreate (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputchanges (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputkpath (
dict
[str
,Iterable
[float
]]) – a dictionary with kpoint name as key and k point coordinate as valuecount (
int
) – number of k-pointsgamma (
bool
) – bool that controls if the gamma-point should be included in the k-point mesh
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputkpath (
dict
[str
,Iterable
[float
]]) – a dictionary with kpoint name as key and k point coordinate as valuecount (
int
) – number of k-pointsgamma (
bool
) – bool that controls if the gamma-point should be included in the k-point mesh
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputkpoints (
Iterable
[Iterable
[float
]]) – list or array containing the relative coordinates of the kpointsweights (
Iterable
[float
]) – list or array containing the weights of the kpointsname (
Optional
[str
]) – str for the name of the list, if not given a default name is generatedkpoint_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 indexswitch (
bool
) – bool, if True the kPointlist will be used by Fleur when starting the next calculationoverwrite (
bool
) – bool, if True and a kPointlist with the given name already exists it will be overwritten
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputkpoints (
Iterable
[Iterable
[float
]]) – list or array containing the relative coordinates of the kpointsweights (
Iterable
[float
]) – list or array containing the weights of the kpoints
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputmesh (
Collection
[int
]) – list-like woth three elements, giving the size of the kpoint set in each directionuse_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 generatedswitch (
bool
) – bool if True the kpoint list is direclty set as the used setoverwrite (
bool
) – if True and a kpoint list of the given name already exists it will be overwrittenshift (
Optional
[Iterable
[float
]]) – shift the center of the kpint settime_reversal (
bool
) – bool if True time reversal symmetry will be used to reduce the kpoint setmap_to_first_bz (
bool
) – bool if True the kpoints are mapped into the [0,1] interval
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputpath (
Union
[str
,list
[str
],None
]) – str, list of str or None defines the path to interpolate (for syntaxbandpath()
)density (
Optional
[float
]) – float number of kpoints per Angstroemname (
Optional
[str
]) – Name of the created kpoint list. If not given a name is generatedswitch (
bool
) – bool if True the kpoint list is direclty set as the used setoverwrite (
bool
) – if True and a kpoint list of the given name already exists it will be overwrittenspecial_points (
Optional
[dict
[str
,Iterable
[float
]]]) – dict mapping names to coordinates for special points to use
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputcount (
int
) – number of k-pointsgamma (
bool
) – bool that controls if the gamma-point should be included in the k-point mesh
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputcount (
int
) – number of k-pointsgamma (
bool
) – bool that controls if the gamma-point should be included in the k-point mesh
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputtag_name (
str
) – str name of the tag to modify/setchanges (
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 evaluationfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for detailscreate_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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputspecies_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. SeeXPathBuilder
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:
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
andspecial
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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputatom_label (
str
) – string, a label of the atom which specie will be changed. ‘all’ to change all the specieschanges (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputtag_name (
str
) – str name of the tag, where the text should be settext (
Any
) – value or list of values to setcomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
,None
]) – an optional xpath to use instead of the simple xpath for the evaluationfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for detailsoccurrences (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputxc_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 taglibxc (
bool
) – bool if True the functional is a LibXC functional
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputchanges (
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 valuepath_spec (
Optional
[dict
[str
,Any
]]) – dict, with ggf. necessary further specifications for the path of the attribute
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputatom_label (
str
) – string, a label of the atom which specie will be changed. ‘all’ if set up all speciesattribute_name (
str
) – name of the attribute to changenumber_to_add (
Any
) – value to add or to multiply bymode (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputlist_name (
str
) – name of the kPoint set to use
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputlist_name (
str
) – name of the kPoint set to use
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputnew_species_name (
str
) – name of the species to switch toposition (
Union
[int
,Literal
['all'
],None
]) – position of an atom group to be changed. If equals to ‘all’, all species will be changedspecies (
Optional
[str
]) – atom groups, corresponding to the given species will be changedclone (
bool
) – if True and the new species name does not exist and it corresponds to changing from one species the species will be cloned withclone_species()
changes (
Optional
[dict
[str
,Any
]]) – changes to do if the species is clonedfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for details
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputatom_label (
str
) – string, a label of the atom which group will be changed. ‘all’ to change all the groupsnew_species_name (
str
) – name of the species to switch toclone (
bool
) – if True and the new species name does not exist and it corresponds to changing from one species the species will be cloned withclone_species()
changes (
Optional
[dict
[str
,Any
]]) – changes to do if the species is cloned
- Return type:
- 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
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputspecies_name (
str
) – string, name of the species you want to changeorbital (
int
|str
) – integer or string (‘all’), orbital quantum number of the LDA+U procedure to be modifiedphi_before (
float
|list
[float
]) – float or list of floats, angle (radian), values for phi for the previous alignment of the density matrixtheta_before (
float
|list
[float
]) – float or list of floats, angle (radian), values for theta for the previous alignment of the density matrixfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for details
- Raises:
ValueError – If something in the input is wrong
KeyError – If no LDA+U procedure is found on a species
- Return type:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputspecies_name (
str
) – string, name of the species you want to changeorbital (
int
|str
) – integer or string (‘all’), orbital quantum number of the LDA+U procedure to be modifiedphi (
float
) – float, angle (radian), by which to rotate the density matrixtheta (
float
) – float, angle (radian), by which to rotate the density matrixfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for details
- Raises:
ValueError – If something in the input is wrong
KeyError – If no LDA+U procedure is found on a species
- Return type:
- 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.xmlnmmplines (
Optional
[list
[str
]]) – list of lines in the n_mmp_mat fileschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputspecies_name (
str
) – string, name of the species you want to changeorbital (
int
) – integer, orbital quantum number of the LDA+U procedure to be modifiedspin (
int
) – integer, specifies which spin block should be modifiedstate_occupations (
Optional
[list
[float
]]) – list, sets the diagonal elements of the density matrix and everything else to zerodenmat (
Optional
[ndarray
]) – matrix, specify the density matrix explicitlyphi (
Optional
[float
]) – float, optional angle (radian), by which to rotate the density matrix before writing ittheta (
Optional
[float
]) – float, optional angle (radian), by which to rotate the density matrix before writing itfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for details
- Raises:
ValueError – If something in the input is wrong
KeyError – If no LDA+U procedure is found on a species
- Return type:
- 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:
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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path where to place a new tagbase_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 missingoccurrences (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path where to set the attributesbase_xpath (
str
) – path where to place a new tag without complex syntax ([] conditions and so on)name (
str
) – the attribute name to changenumber_to_add (
Any
) – number to add/multiply with the old attribute valuemode (
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_addoccurrences (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path where to set the attributesbase_xpath (
str
) – path where to place a new tag without complex syntax ([] conditions and so on)name (
str
) – the attribute name to changenumber_to_add (
Any
) – number to add/multiply with the old attribute valuemode (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path where to place a new tagbase_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 createdcreate_parents (
bool
) – bool optional (default False), if True and the given xpath has no results the the parent tags are created recursivelyoccurrences (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path where to set the attributesbase_xpath (
str
) – path where to place a new tag without complex syntax ([] conditions and so on)name (
str
) – the attribute name to setvalue (
Any
) – value or list of values to setoccurrences (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path where to set the attributesbase_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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path where to set the attributebase_xpath (
str
) – path where to place a new tag without complex syntax ([] conditions and so on)name (
str
) – the attribute name to setvalue (
Any
) – value or list of values to setcreate (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path where to set the textbase_xpath (
str
) – path where to place a new tag without complex syntax ([] conditions and so on)text (
Any
) – value or list of values to setcreate (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path where to set the attributesbase_xpath (
str
) – path where to place a new tag without complex syntax ([] conditions and so on)tag_name (
str
) – name of the tag to setchanges (
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:
- 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.xmlschema_dict (
SchemaDict
) – InputSchemaDict containing all information about the structure of the inputxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path where to set the textbase_xpath (
str
) – path where to place a new tag without complex syntax ([] conditions and so on)text (
Any
) – value or list of values to setoccurrences (
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:
- 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.xmlxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path where to place a new tagelement (
QName
|str
|_Element
) – a tag name, etree Element or string representing the XML element to be createdplace_index (
Optional
[int
]) – defines the place where to put a created tagoccurrences (
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 fleurseveral (
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:
- 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:
xmltree (
Union
[_Element
,_ElementTree
]) – an xmltree that represents inp.xmlxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path to the attribute to be deletedname (
str
) – the name of an attribute to deleteoccurrences (
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.
- Return type:
- 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:
xmltree (
Union
[_Element
,_ElementTree
]) – an xmltree that represents inp.xmlxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path to the tag to be deletedoccurrences (
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.
- Return type:
- 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:
xmltree (
Union
[_Element
,_ElementTree
]) – an xmltree that represents inp.xmlxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path to the tag to be replacedelement (
str
|_Element
) – an Element or string representing the Element to replace the found tags withoccurrences (
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.
- Return type:
- 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.xmlxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path where to set the attributesname (
str
) – the attribute name to setvalue (
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:
- 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:
xmltree (
Union
[_Element
,_ElementTree
]) – an xmltree that represents inp.xmlxpath (
Union
[str
,bytes
,XPath
,XPathBuilder
]) – a path where to set the texttext (
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 text or occurrences do not match number of nodes
- Return type:
- 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:
xmltree (
Union
[_Element
,_ElementTree
]) – etree representing the fleur xml fileschema_dict (
InputSchemaDict
|OutputSchemaDict
) – schema dictionary corresponding to the file version of the xmltreelogger (
Optional
[Logger
]) – logger object for logging warnings, errorsconvert_to_angstroem (
bool
) – bool if True the bravais matrix is converted to angstroem
- Return type:
- 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:
xmltree (
Union
[_Element
,_ElementTree
]) – etree representing the fleur xml fileschema_dict (
InputSchemaDict
|OutputSchemaDict
) – schema dictionary corresponding to the file version of the xmltreelogger (
Optional
[Logger
]) – logger object for logging warnings, errors
- Return type:
- 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
- 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 fileschema_dict (
InputSchemaDict
|OutputSchemaDict
) – schema dictionary corresponding to the file version of the xmltreename (
Optional
[str
]) – str, optional, if given only the kpoint set with the given name is returnedindex (
Optional
[int
]) – int, optional, if given only the kpoint set with the given index is returnedonly_used (
bool
) – bool if True only the kpoint list used in the calculation is returnedlogger (
Optional
[Logger
]) – logger object for logging warnings, errorsconvert_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:
- kpoints:
dict or list (list if there is only one kpoint set), containing the coordinates of the kpoints
- weights:
dict or list (list if there is only one kpoint set), containing the weights of the kpoints
- cell:
numpy array, bravais matrix of the given system
- 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 fileschema_dict (
InputSchemaDict
|OutputSchemaDict
) – schema dictionary corresponding to the file version of the xmltreelogger (
Optional
[Logger
]) – logger object for logging warnings, errorsconvert_to_angstroem (
bool
) – bool if True the bravais matrix is converted to angstroemonly_used (
bool
) – (Has no effect for Max4) bool if True only the kpoint list used in the calculation is returned
- 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:
- kpoints:
list containing the coordinates of the kpoints
- weights:
list containing the weights of the kpoints
- cell:
numpy array, bravais matrix of the given system
- 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:
xmltree (
Union
[_Element
,_ElementTree
]) – etree representing the fleur xml fileschema_dict (
InputSchemaDict
|OutputSchemaDict
) – schema dictionary corresponding to the file version of the xmltreelogger (
Optional
[Logger
]) – logger object for logging warnings, errors
- Return type:
- 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:
xmltree (
Union
[_Element
,_ElementTree
]) – etree representing the fleur xml fileschema_dict (
InputSchemaDict
|OutputSchemaDict
) – schema dictionary corresponding to the file version of the xmltreelogger (
Optional
[Logger
]) – logger object for logging warnings, errors
- Return type:
- Returns:
int with the number of kpoints
- masci_tools.util.xml.xml_getters.get_parameter_data(*args, **kwargs)[source]¶
RENAMED TO get_parameterdata
- 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 fileschema_dict (
InputSchemaDict
|OutputSchemaDict
) – schema dictionary corresponding to the file version of the xmltreeinpgen_ready (
bool
) – Bool, return a dict which can be inputted into inpgen while setting atomswrite_ids (
bool
) – Bool, if True the atom ids are added to the atom namelistslogger (
Optional
[Logger
]) – logger object for logging warnings, errors
- Return type:
- 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:
xmltree (
Union
[_Element
,_ElementTree
]) – etree representing the fleur xml fileschema_dict (
InputSchemaDict
|OutputSchemaDict
) – schema dictionary corresponding to the file version of the xmltreelogger (
Optional
[Logger
]) – logger object for logging warnings, errors
- Return type:
- 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:
xmltree (
Union
[_Element
,_ElementTree
]) – etree representing the fleur xml fileschema_dict (
InputSchemaDict
|OutputSchemaDict
) – schema dictionary corresponding to the file version of the xmltreelogger (
Optional
[Logger
]) – logger object for logging warnings, errors
- Return type:
- 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 fileschema_dict (
InputSchemaDict
|OutputSchemaDict
) – schema dictionary corresponding to the file version of the xmltreename (
Optional
[str
]) – str, optional, if given only the kpoint set with the given name is returnedindex (
Optional
[int
]) – int, optional, if given only the kpoint set with the given index is returnedonly_used (
bool
) – bool if True only the kpoint list used in the calculation is returnedlogger (
Optional
[Logger
]) – logger object for logging warnings, errors
- Return type:
- 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 fileschema_dict (
InputSchemaDict
|OutputSchemaDict
) – schema dictionary corresponding to the file version of the xmltreename (
Optional
[str
]) – str, optional, if given only the kpoint set with the given name is returnedindex (
Optional
[int
]) – int, optional, if given only the kpoint set with the given index is returnedonly_used (
bool
) – bool if True only the kpoint list used in the calculation is returnedlogger (
Optional
[Logger
]) – logger object for logging warnings, errors
- Return type:
- 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
- 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 ofAtomSiteProperties
instead of the list of tuples (position, symbol)For better compatibility this output is not default in
0.5.0
but instead is enabled bysite_namedtuple=True
and a DeprecationWarning is given when this argument isFalse
.Note
In versions
0.5.0
or later the returned atom positions correspond to the relaxed structure if arelaxation
section is present in the xmltree- Parameters:
xmltree (
Union
[_Element
,_ElementTree
]) – etree representing the fleur xml fileschema_dict (
InputSchemaDict
|OutputSchemaDict
) – schema dictionary corresponding to the file version of the xmltreeinclude_relaxations (
bool
) – bool if True and a relaxation section is included the resulting positions correspond to the relaxed structurelogger (
Optional
[Logger
]) – logger object for logging warnings, errorsconvert_to_angstroem (
bool
) – bool if True the bravais matrix is converted to angstroemextract_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:
- atom_data:
list of (named)tuples containing the absolute positions and symbols of the atoms
- cell:
numpy array, bravais matrix of the given system
- 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:
xmltree (
Union
[_Element
,_ElementTree
]) – etree representing the fleur xml fileschema_dict (
InputSchemaDict
|OutputSchemaDict
) – schema dictionary corresponding to the file version of the xmltreelogger (
Optional
[Logger
]) – logger object for logging warnings, errors
- Return type:
- 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
- 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.
- 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:
vector (
TypeVar
(_TVectorType
, bound=Union
[Tuple
[float
,float
,float
],List
[float
],ndarray
])) – list or np.array of length 3, vector to be convertedcell (
list
[list
[float
]] |ndarray
) – Bravais matrix of a crystal 3x3 Array, List of list or np.arraypbc (
tuple
[bool
,bool
,bool
]) – Boundary conditions, List or Tuple of 3 Boolean
- 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:
- 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:
- 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:
- 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.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
- 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:
from_pos (
Union
[Tuple
[float
,float
,float
],List
[float
],ndarray
]) – vector to rotateto_pos (
Union
[Tuple
[float
,float
,float
],List
[float
],ndarray
]) – vector to rotate torotations (
list
[ndarray
]) – list of np.arrays with the given symmetry rotationsshifts (
list
[ndarray
]) – list of np.arrays with the given shifts for the symmetry operationscell (
list
[list
[float
]] |ndarray
) – Bravais matrix of a crystal 3x3 Array, List of list or np.arrayrelative_pos (
bool
) – bool if True the given vectors are assuemd to be in internal coordinatesfilm (
bool
) – bool if True the vectors are assumed to be film coordinates
- Return type:
- Returns:
tuple of rotation and shift mapping
from_pos
toto_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
- masci_tools.io.common_functions.get_ef_from_potfile(potfile)[source]¶
extract fermi energy from potfile
- Return type:
- 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
- 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
- masci_tools.io.common_functions.get_spin_rotation(alpha, beta)[source]¶
Get matrix to rotate the spin frame by the given angles alpha/beta
- 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
- 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.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()
- masci_tools.io.common_functions.rel_to_abs(vector, cell)[source]¶
Converts a position vector in internal coordinates to absolute coordinates in Angstrom.
- 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).
- masci_tools.io.common_functions.skipHeader(seq, n)[source]¶
Iterate over a sequence skipping the first n elements
- 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)
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:
- 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:
- 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 processflatten (
bool
) – bool, if True the dictionary will be flattened (does not check for lost information)
- Return type:
- 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:
- 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
- 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.
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 evaluationsschema_dict (
SchemaDict
) – dict, containing all the path information and morename (
str
) – str, name of the attributelogger (
Optional
[Logger
]) – logger object for logging warnings, errors, if not provided all errors will be raisediteration_path (
bool
) – bool if True and the SchemaDict is of an output schema an absolute path into the iteration element is constructedfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
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:
- 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 norelaxation
is present in theinp.xml
- Parameters:
xmltree (
_ElementTree
) – an xml-tree which will be processedschema_dict (
InputSchemaDict
) – Schema dictionary containing all the necessary information
- Return type:
- 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 evaluationsschema_dict (
SchemaDict
) – dict, containing all the path information and morename (
str
) – str, name of the taglogger (
Optional
[Logger
]) – logger object for logging warnings, errors, if not provided all errors will be raisediteration_path (
bool
) – bool if True and the SchemaDict is of an output schema an absolute path into the iteration element is constructedfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
for detailslist_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
- 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 evaluationsschema_dict (
SchemaDict
) – dict, containing all the path information and morename (
str
) – str, name of the attributeconstants (
Optional
[dict
[str
,float
]]) – dict, contains the defined constantslogger (
Optional
[Logger
]) – logger object for logging warnings, errors, if not provided all errors will be raisedcomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
,None
]) – an optional xpath to use instead of the simple xpath for the evaluationiteration_path (
bool
) – bool if True and the SchemaDict is of an output schema an absolute path into the iteration element is constructedfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
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:
- 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 evaluationsschema_dict (
SchemaDict
) – dict, containing all the path information and morename (
str
) – str, name of the tagconstants (
Optional
[dict
[str
,float
]]) – dict, contains the defined constantslogger (
Optional
[Logger
]) – logger object for logging warnings, errors, if not provided all errors will be raisedcomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
,None
]) – an optional xpath to use instead of the simple xpath for the evaluationiteration_path (
bool
) – bool if True and the SchemaDict is of an output schema an absolute path into the iteration element is constructedfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
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:
- 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:
node (
Union
[_Element
,_ElementTree
,XPathElementEvaluator
]) – etree Element, on which to execute the xpath evaluationsschema_dict (
SchemaDict
) – dict, containing all the path information and morename (
str
) – str, name of the tagconstants (
Optional
[dict
[str
,float
]]) – dict, contains the defined constantslogger (
Optional
[Logger
]) – logger object for logging warnings, errors, if not provided all errors will be raisedcomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
,None
]) – an optional xpath to use instead of the simple xpath for the evaluation
- 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:
- 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 evaluationsschema_dict (
SchemaDict
) – dict, containing all the path information and morename (
str
) – str, name of the tagconstants (
Optional
[dict
[str
,float
]]) – dict, contains the defined constantslogger (
Optional
[Logger
]) – logger object for logging warnings, errors, if not provided all errors will be raisedsubtags (
bool
) – optional bool, if True the subtags of the given tag are evaluatedtext (
bool
) – optional bool, if True the text of the tag is also parsedcomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
,None
]) – an optional xpath to use instead of the simple xpath for the evaluationiteration_path (
bool
) – bool if True and the SchemaDict is of an output schema an absolute path into the iteration element is constructedfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
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:
- 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 evaluationsschema_dict (
SchemaDict
) – dict, containing all the path information and morename (
str
) – str, name of the tagconstants (
Optional
[dict
[str
,float
]]) – dict, contains the defined constantslogger (
Optional
[Logger
]) – logger object for logging warnings, errors, if not provided all errors will be raisedcomplex_xpath (
Union
[str
,bytes
,XPath
,XPathBuilder
,None
]) – an optional xpath to use instead of the simple xpath for the evaluationiteration_path (
bool
) – bool if True and the SchemaDict is of an output schema an absolute path into the iteration element is constructedfilters (
Optional
[Dict
[str
,Any
]]) – Dict specifying constraints to apply on the xpath. SeeXPathBuilder
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:
- 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:
node (
Union
[_Element
,_ElementTree
,XPathElementEvaluator
]) – etree Element, on which to execute the xpath evaluationsschema_dict (
SchemaDict
) – dict, containing all the path information and morename (
str
) – str, name of the taglogger (
Optional
[Logger
]) – logger object for logging warnings, errors, if not provided all errors will be raised
- 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:
- 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:
root (
Union
[_Element
,_ElementTree
,XPathElementEvaluator
]) – root of the etree of the inp.xml fileschema_dict (
SchemaDict
) – schema_dictionary of the version of the file to read (inp.xml or out.xml)logger (
Optional
[Logger
]) – logger object for logging warnings, errors
- Return type:
- 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 processedschema_dict (
InputSchemaDict
) – Schema dictionary containing all the necessary informationincluded_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:
node (
Union
[_Element
,_ElementTree
,XPathElementEvaluator
]) – etree Element, on which to execute the xpath evaluationsschema_dict (
SchemaDict
) – dict, containing all the path information and morename (
str
) – str, name of the taglogger (
Optional
[Logger
]) – logger object for logging warnings, errors, if not provided all errors will be raised
- 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:
- 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
- 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 parsedconstants (
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:
- 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
- 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
- masci_tools.util.fleur_calculate_expression.get_first_string(expression)[source]¶
Reads the letter string in the beginning of the expression string.
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
- masci_tools.io.parsers.fleur.outxml_conversions.calculate_walltime(out_dict, logger)[source]¶
Calculate the walltime from start and end time
- masci_tools.io.parsers.fleur.outxml_conversions.convert_forces(out_dict, logger)[source]¶
Convert the parsed forces from a iteration
- 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
- 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)
- 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)
- masci_tools.io.parsers.fleur.outxml_conversions.convert_relax_info(out_dict, logger)[source]¶
Convert the general relaxation information
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.
- masci_tools.util.econfig.get_coreconfig(element, full=False)[source]¶
returns the econfiguration as a string of an element.
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:
- Returns:
InputSchemaDict object with the information for the provided file
- 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:
- Return type:
- 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:
- Return type:
- 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 attributecontains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to be in the final pathnot_contains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to NOT be in the final pathexclude (
Optional
[Iterable
[str
]]) – list of str, here specific types of attributes can be excluded valid values are: settable, settable_contains, othertag_name (
Optional
[str
]) – str, if given this name will be used to find a path to a tag with the same name initeration_tag_xpath()
iteration_tag (
str
) – name of the tag containing the iteration information
- Return type:
- Returns:
str, xpath to the tag with the given attribute
- Raises:
NoPathFound – If no path matching the criteria could be found
NoUniquePathFound – If multiple paths matching the criteria are found
- 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 tagcontains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to be in the final pathnot_contains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to NOT be in the final pathiteration_tag (
str
) – name of the tag containing the iteration information
- Return type:
- Returns:
str, xpath for the given tag
- Raises:
NoPathFound – If no path matching the criteria could be found
NoUniquePathFound – If multiple paths matching the criteria are found
- 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 attributeroot_tag (
str
) – str, name of the tag from which the path should be relativecontains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to be in the final pathnot_contains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to NOT be in the final pathexclude (
Optional
[Iterable
[str
]]) – list of str, here specific types of attributes can be excluded valid values are: settable, settable_contains, othertag_name (
Optional
[str
]) – str, if given this name will be used to find a path to a tag with the same name inrelative_iteration_tag_xpath()
iteration_tag (
str
) – name of the tag containing the iteration information
- Return type:
- Returns:
str, xpath for the given tag
- Raises:
NoPathFound – If no path matching the criteria could be found
NoUniquePathFound – If multiple paths matching the criteria are found
- 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 tagcontains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to be in the final pathnot_contains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to NOT be in the final pathiteration_tag (
str
) – name of the tag containing the iteration information
- Return type:
- Returns:
str, xpath for the given tag
- Raises:
NoPathFound – If no path matching the criteria could be found
NoUniquePathFound – If multiple paths matching the criteria are found
- 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
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 attributecontains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to be in the final pathnot_contains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to NOT be in the final pathexclude (
Optional
[Iterable
[str
]]) – list of str, here specific types of attributes can be excluded valid values are: settable, settable_contains, othertag_name (
Optional
[str
]) – str, if given this name will be used to find a path to a tag with the same name intag_xpath()
- Return type:
- Returns:
str, xpath to the tag with the given attribute
- Raises:
NoPathFound – If no path matching the criteria could be found
NoUniquePathFound – If multiple paths matching the criteria are found
- classmethod clear_cache()[source]¶
Remove all stored entries in the schema dictionary cache
- Return type:
- 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 attributeroot_tag (
str
) – str, name of the tag from which the path should be relativecontains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to be in the final pathnot_contains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to NOT be in the final pathexclude (
Optional
[Iterable
[str
]]) – list of str, here specific types of attributes can be excluded valid values are: settable, settable_contains, othertag_name (
Optional
[str
]) – str, if given this name will be used to find a path to a tag with the same name inrelative_tag_xpath()
- Return type:
- Returns:
str, xpath for the given tag
- Raises:
NoPathFound – If no path matching the criteria could be found
NoUniquePathFound – If multiple paths matching the criteria are found
- 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 tagroot_tag (
str
) – str, name of the tag from which the path should be relativecontains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to be in the final pathnot_contains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to NOT be in the final path
- Return type:
- 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 tagcontains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to be in the final pathnot_contains (
Union
[str
,Iterable
[str
],None
]) – str or list of str, this string has to NOT be in the final pathparent (
bool
) – bool, if True the tag_info for the parent of the tag is returned
- Return type:
- 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:
- Return type:
- Returns:
str, xpath for the given tag
- Raises:
NoPathFound – If no path matching the criteria could be found
NoUniquePathFound – If multiple paths matching the criteria are found
- masci_tools.io.parsers.fleur_schema.list_available_versions(output_schema)[source]¶
List the available versions for the schema
- 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
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
- 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:
- 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:
- 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