Fleur tools/utility

Dealing with XML Schema files

This file is just were to hardcode some schema file paths

Structure Data util

Collection of utility routines dealing with StructureData objects

aiida_fleur.tools.StructureData_util.abs_to_rel(vector, cell)[source]

Converts a position vector in absolute coordinates to relative coordinates.

Parameters:
  • vector – list or np.array of length 3, vector to be converted
  • cell – Bravais matrix of a crystal 3x3 Array, List of list or np.array
Returns:

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

aiida_fleur.tools.StructureData_util.abs_to_rel_f(vector, cell, pbc)[source]

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

Parameters:
  • vector – list or np.array of length 3, vector to be converted
  • cell – Bravais matrix of a crystal 3x3 Array, List of list or np.array
  • pbc – Boundary conditions, List or Tuple of 3 Boolean
Returns:

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

aiida_fleur.tools.StructureData_util.adjust_calc_para_to_structure(parameter, structure, add_atom_base_lists=True, write_new_kind_names=False)[source]

Adjust calculation parameters for inpgen to a given structure with several kinds

Rules: 1. Only atom lists are changed in the parameter node 2. If at least one atomlist of a certain element is in parameter all kinds with this elements will have atomlists in the end 3. For a certain kind which has no atom list yet and at least one list with such an element exists it gets the parameters from the atom list with the lowest number (while atom<atom0<atom1) 4. Atom lists with ids are preserved

Parameters:
  • parameter – aiida.orm.Dict node containing calc parameters
  • structure – aiida.orm.StructureData node containing a crystal structure
  • add_atom_base_lists – Bool (default True), if the atom base lists should be added or not
Returns:

new aiida.orm.Dict with new calc_parameters

aiida_fleur.tools.StructureData_util.adjust_film_relaxation(structure, suggestion, scale_as=None, bond_length=None, hold_layers=3)[source]

Tries to optimize interlayer distances. Can be used before RelaxWC to improve its behaviour. This function only works if USER_API_KEY was set.

For now only binary structures are analysed to ensure the closest contact between two elements of the interest. In case of trinary systems (like ABC) I can not not guarantee that A and C will be the nearest neighbours.

The same is true for interlayer distances of the same element. To ensure the nearest-neighbour condition I use unary compounds.

Parameters:
  • structure – ase film structure which will be adjusted
  • suggestion – dictionary containing average bond length between different elements, is is basically the result of request_average_bond_length()
  • scale_as – an element name, for which the El-El bond length will be enforced. It is can be helpful to enforce the same interlayer distance in the substrate, i.e. adjust deposited film interlayer distances only.
  • bond_length – a float that sets the bond length for scale_as element
  • hold_layers – this parameters sets the number of layers that will be marked via the certain label. The label is reserved for future use in the relaxation WC: all the atoms marked with the label will not be relaxed.
aiida_fleur.tools.StructureData_util.break_symmetry(structure, atoms=None, site=None, pos=None, new_kinds_names=None, add_atom_base_lists=True, parameterdata=None)[source]

This routine introduces different ‘kind objects’ in a structure and names them that inpgen will make different species/atomgroups out of them. If nothing specified breaks ALL symmetry (i.e. every atom gets their own kind)

Parameters:
  • structure – StructureData
  • atoms – python list of symbols, exp: [‘W’, ‘Be’]. This would make for all Be and W atoms their own kinds.
  • site – python list of integers, exp: [1, 4, 8]. This would create for atom 1, 4 and 8 their own kinds.
  • pos – python list of tuples of 3, exp [(0.0, 0.0, -1.837927), …]. This will create a new kind for the atom at that position. Be carefull the number given has to match EXACTLY the position in the structure.
  • parameterdata – Dict node, containing calculation_parameters, however, this only works well if you prepare already a node for containing the atom lists from the symmetry breaking, or lists without ids.
  • add_atom_base_lists – Bool (default True), if the atom base lists should be added or not
Returns:

StructureData, a AiiDA crystal structure with new kind specification.

Returns:

DictData, a AiiDA dict with new parameters for inpgen.

aiida_fleur.tools.StructureData_util.break_symmetry_wf(structure, wf_para, parameterdata=None)[source]

This is the calcfunction of the routine break_symmetry, which introduces different ‘kind objects’ in a structure and names them that inpgen will make different species/atomgroups out of them. If nothing specified breaks ALL symmetry (i.e. every atom gets their own kind)

Parameters:
  • structure – StructureData
  • wf_para

    ParameterData which contains the keys atoms, sites, pos (see below)

    ’atoms’:
    python list of symbols, exp: [‘W’, ‘Be’]. This would make for all Be and W atoms their own kinds.
    ’site’:
    python list of integers, exp: [1, 4, 8]. This would create for atom 1, 4 and 8 their own kinds.
    ’pos’:
    python list of tuples of 3, exp [(0.0, 0.0, -1.837927), …]. This will create a new kind for the atom at that position. Be carefull the number given has to match EXACTLY the position in the structure.
  • parameterdata – AiiDa ParameterData
Returns:

StructureData, a AiiDA crystal structure with new kind specification.

aiida_fleur.tools.StructureData_util.center_film(structure)[source]

Centers a film at z=0

Parameters:structure – AiiDA structure
Returns:AiiDA structure
aiida_fleur.tools.StructureData_util.center_film_wf(structure)[source]

Centers a film at z=0, keeps the provenance in the database

Parameters:structure – AiiDA structure
Returns:AiiDA structure
aiida_fleur.tools.StructureData_util.check_structure_para_consistent(parameter, structure, verbose=True)[source]

Check if the given calculation parameters for inpgen match to a given structure

If parameter contains atom lists which do not fit to any kind in the structure, false is returned This knows how the FleurinputgenCalculation prepares structures.

Parameters:
  • parameter – aiida.orm.Dict node containing calc parameters
  • structure – aiida.orm.StructureData node containing a crystal structure
Returns:

Boolean, True if parameter is consistent to structure

aiida_fleur.tools.StructureData_util.create_all_slabs(initial_structure, miller_index, min_slab_size_ang, min_vacuum_size=0, bonds=None, tol=0.001, max_broken_bonds=0, lll_reduce=False, center_slab=False, primitive=False, max_normal_search=1, symmetrize=False)[source]
Returns:a dictionary of structures
aiida_fleur.tools.StructureData_util.create_manual_slab_ase(lattice='fcc', miller=None, host_symbol='Fe', latticeconstant=4.0, size=(1, 1, 5), replacements=None, decimals=10, pop_last_layers=0, inverse=False)[source]

Wraps ase.lattice lattices generators to create a slab having given lattice vectors directions.

Parameters:
  • lattice – ‘fcc’ and ‘bcc’ are supported. Set the host lattice of a slab.
  • miller – a list of directions of lattice vectors
  • symbol – a string specifying the atom type
  • latticeconstant – the lattice constant of a structure
  • size – a 3-element tuple that sets supercell size. For instance, use (1,1,5) to set 5 layers of a slab.
  • decimals – sets the rounding of atom positions. See numpy.around.
  • pop_last_layers – specifies how many bottom layers to remove. Sometimes one does not want to use the integer number of unit cells along z, extra layers can be removed.
Return structure:
 

an ase-lattice representing a slab with replaced atoms

aiida_fleur.tools.StructureData_util.create_slap(initial_structure, miller_index, min_slab_size, min_vacuum_size=0, lll_reduce=False, center_slab=False, primitive=False, max_normal_search=1, reorient_lattice=True)[source]

wraps the pymatgen slab generator

aiida_fleur.tools.StructureData_util.find_equi_atoms(structure)[source]

This routine uses spglib and ASE to provide informations of all equivivalent atoms in the cell.

Parameters:structure – AiiDA StructureData
Returns:equi_info_symbol, list of lists [‘element’: site_indexlist, …] len(equi_info_symbol) = number of symmetryatomtypes and n_equi_info_symbol, dict {‘element’: numberequiatomstypes}
aiida_fleur.tools.StructureData_util.find_primitive_cell(structure)[source]

uses spglib find_primitive to find the primitive cell

Parameters:sructure – AiiDA structure data
Returns:list of new AiiDA structure data
aiida_fleur.tools.StructureData_util.find_primitive_cell_wf(structure)[source]

uses spglib find_primitive to find the primitive cell :param structure: AiiDa structure data

Returns:list of new AiiDa structure data
aiida_fleur.tools.StructureData_util.find_primitive_cells(uuid_list)[source]

uses spglib find_primitive to find the primitive cell :param uuid_list: list of structureData uuids, or pks

Returns:list of new AiiDa structure datas
aiida_fleur.tools.StructureData_util.get_all_miller_indices(structure, highestindex)[source]

wraps the pymatgen function get_symmetrically_distinct_miller_indices for an AiiDa structure

aiida_fleur.tools.StructureData_util.get_layers(structure, decimals=10)[source]

Extracts atom positions and their types belonging to the same layer

Parameters:
  • structure – ase lattice or StructureData which represents a slab
  • number – the layer number. Note, that layers will be sorted according to z-position
  • decimals – sets the tolerance of atom positions determination. See more in numpy.around.
Return layer, layer_z_positions:
 

layer is a list of tuples, the first element of which is atom positions and the second one is atom type. layer_z_position is a sorted list of all layer positions

aiida_fleur.tools.StructureData_util.get_spacegroup(structure)[source]
Parameters:structure – AiiDA StructureData
Returns:the spacegroup (spglib class) of a given AiiDA structure
aiida_fleur.tools.StructureData_util.is_primitive(structure)[source]

Checks if a structure is primitive or not, :param structure: AiiDA StructureData :return: True if the structure can not be anymore refined. prints False if the structure can be futher refined.

aiida_fleur.tools.StructureData_util.is_structure(structure)[source]

Test if the given input is a StructureData node, by object, id, or pk :param structure: AiiDA StructureData :return: if yes returns a StructureData node in all cases, if no returns None

aiida_fleur.tools.StructureData_util.magnetic_slab_from_relaxed(relaxed_structure, orig_structure, total_number_layers, num_relaxed_layers, tolerance_decimals=10)[source]

Transforms a structure that was used for interlayer distance relaxation to a structure that can be further used for magnetic calculations.

Usually one uses a slab having z-reflection symmetry e.g. A-B1-B2-B3-B2-B1-A where A is a magnetic element (Fe, Ni, Co, Cr) and B is a substrate. However, further magnetic calculations are done using assymetric slab A-B1-B2-B3-B4-B5-B6-B7-B8. The function uses A-B1, B1-B2 etc. iterlayer distances for constraction of assymetric relaxed film.

The function works as follows: it constructs a new StructureData object taking x and y positions from the orig_structure and z positions from relax_structure for first num_relaxed_interlayers. Then it appends orig_structure slab to the bottom it a way the total number of layers is total_number_layers.

Parameters:
  • relaxed_structure – Structure which is the output of Relax WorkChain. In thin function it is assumed to have inversion or at least z-reflection symmetry.
  • orig_structure – The host structure slab having the lattice perioud corresponding to the bulk structure of the substrate.
  • total_number_layers – the total number of layers to produce
  • num_relaxed_layers – the number of top layers to adjust according to relaxed_struct
  • tolerance_decimals – sets the rounding of atom positions. See numpy.around.
Return magn_structure:
 

Resulting assymetric structure with adjusted interlayer distances for several top layers.

aiida_fleur.tools.StructureData_util.move_atoms_incell(structure, vector)[source]

moves all atoms in a unit cell by a given vector

Parameters:
  • structure – AiiDA structure
  • vector – tuple of 3, or array
Returns:

AiiDA structure

aiida_fleur.tools.StructureData_util.move_atoms_incell_wf(structure, wf_para)[source]

moves all atoms in a unit cell by a given vector

Parameters:
  • structure – AiiDA structure
  • wf_para – AiiDA Dict node with vector: tuple of 3, or array (currently 3 AiiDA Floats to make it a wf, In the future maybe a list or vector if AiiDa basetype exists)
Returns:

AiiDA stucture

aiida_fleur.tools.StructureData_util.rel_to_abs(vector, cell)[source]

Converts a position vector in internal coordinates to absolute coordinates in Angstrom.

Parameters:
  • vector – list or np.array of length 3, vector to be converted
  • cell – Bravais matrix of a crystal 3x3 Array, List of list or np.array
Returns:

list of legth 3 of scaled vector, or False if vector was not lenth 3

aiida_fleur.tools.StructureData_util.rel_to_abs_f(vector, cell)[source]

Converts a position vector in internal coordinates to absolute coordinates in Angstrom for a film structure (2D).

aiida_fleur.tools.StructureData_util.request_average_bond_length(main_elements, sub_elements, user_api_key)[source]

Requests MaterialsProject to estimate thermal average bond length between given elements. Also requests information about lattice constants of fcc and bcc structures.

Parameters:
  • main_elements – element list to calculate the average bond length only combinations of AB, AA and BB are calculated, where A belongs to main_elements, B belongs to sub_elements.
  • sub_elements – element list, see main_elements
Returns:

bond_data, a dict containing obtained lattice constants.

aiida_fleur.tools.StructureData_util.request_average_bond_length_store(main_elements, sub_elements, user_api_key)[source]

Requests MaterialsProject to estimate thermal average bond length between given elements. Also requests information about lattice constants of fcc and bcc structures. Stores the result in the Database. Notice that this is not a calcfunction! Therefore, the inputs are not stored and the result node is unconnected.

Parameters:
  • main_elements – element list to calculate the average bond length only combinations of AB, AA and BB are calculated, where A belongs to main_elements, B belongs to sub_elements.
  • sub_elements – element list, see main_elements
Returns:

bond_data, a dict containing obtained lattice constants.

aiida_fleur.tools.StructureData_util.rescale(inp_structure, scale)[source]

Rescales a crystal structures Volume, atoms stay at their same relative postions, therefore the absolute postions change. Keeps the provenance in the database.

Parameters:
  • inp_structure – a StructureData node (pk, or uuid)
  • scale – float scaling factor for the cell
Returns:

New StructureData node with rescalled structure, which is linked to input Structure and None if inp_structure was not a StructureData

aiida_fleur.tools.StructureData_util.rescale_nowf(inp_structure, scale)[source]

Rescales a crystal structures Volume, atoms stay at their same relative postions, therefore the absolute postions change. DOES NOT keep the provenance in the database.

Parameters:
  • inp_structure – a StructureData node (pk, or uuid)
  • scale – float scaling factor for the cell
Returns:

New StructureData node with rescalled structure, which is linked to input Structure and None if inp_structure was not a StructureData

aiida_fleur.tools.StructureData_util.sort_atoms_z_value(structure)[source]

Resorts the atoms in a structure by there Z-value

Parameters:structure – AiiDA structure
Returns:AiiDA structure
aiida_fleur.tools.StructureData_util.supercell(inp_structure, n_a1, n_a2, n_a3)[source]

Creates a super cell from a StructureData node. Keeps the provenance in the database.

Parameters:
  • StructureData – a StructureData node (pk, or uuid)
  • scale – tuple of 3 AiiDA integers, number of cells in a1, a2, a3, or if cart =True in x,y,z
Returns:

StructureData Node with supercell

aiida_fleur.tools.StructureData_util.supercell_ncf(inp_structure, n_a1, n_a2, n_a3)[source]

Creates a super cell from a StructureData node. Does NOT keeps the provenance in the database.

Parameters:
  • StructureData – a StructureData node (pk, or uuid)
  • scale – tuple of 3 AiiDA integers, number of cells in a1, a2, a3, or if cart=True in x,y,z
Returns:

StructureData Node with supercell

XML utility

In this module contains useful methods for handling xml trees and files which are used by the Fleur code and the fleur plugin.

aiida_fleur.tools.xml_util.add_num_to_att(xmltree, xpathn, attributename, set_val, mode='abs', occ=None)[source]

Routine adds something to the value of an attribute in the xml file (should be a number here) This is a lower-level version of shift_value() which allows one to specife an arbitrary xml path.

Param:

an etree a xpath from root to the attribute and the attribute value

Parameters:
  • xpathn – an xml path to the attribute to change
  • attributename – a name of the attribute to change
  • set_val – a value to be added/multiplied to the previous value
  • mode – ‘abs’ if to add set_val, ‘rel’ if multiply
  • occ – a list of integers specifying number of occurrence to be set
Comment: Element.set will add the attribute if it does not exist,
xpath expression has to exist
example: add_num_to_add(tree, ‘/fleurInput/bzIntegration’, ‘valenceElectrons’, ‘1’)
add_num_to_add(tree, ‘/fleurInput/bzIntegration’, ‘valenceElectrons’, ‘1.1’, mode=’rel’)
aiida_fleur.tools.xml_util.change_atomgr_att(fleurinp_tree_copy, attributedict, position=None, species=None)[source]

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

Parameters:
  • fleurinp_tree_copy – xml etree of the inp.xml
  • attributedict – a python dict specifying what you want to change.
  • position – position of an atom group to be changed. If equals to ‘all’, all species will be changed
  • species – atom groups, corresponding to the given specie will be changed
  • create – bool, if species does not exist create it and all subtags?
Return fleurinp_tree_copy:
 

xml etree of the new inp.xml

attributedict 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:

'attributedict': {'nocoParams': [('beta', val)]}

force and nocoParams keys are supported. To find possible keys of the inner dictionary please refer to the FLEUR documentation flapw.de

aiida_fleur.tools.xml_util.change_atomgr_att_label(fleurinp_tree_copy, attributedict, at_label)[source]

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

Parameters:
  • fleurinp_tree_copy – xml etree of the inp.xml
  • at_label – string, a label of the atom which specie will be changed. ‘all’ to change all the species
  • attributedict – a python dict specifying what you want to change.
Return fleurinp_tree_copy:
 

xml etree of the new inp.xml

attributedict 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:

'attributedict': {'nocoParams': [('beta', val)]}

force and nocoParams keys are supported. To find possible keys of the inner dictionary please refer to the FLEUR documentation flapw.de

aiida_fleur.tools.xml_util.clear_xml(tree)[source]

Removes comments and executes xinclude tags of an xml tree.

Parameters:tree – an xml-tree which will be processes
Return cleared_tree:
 an xml-tree without comments and with replaced xinclude tags
aiida_fleur.tools.xml_util.convert_ev_to_htr(value, parser_info_out=None)[source]

Divides the value given with the Hartree factor (converts htr to eV)

aiida_fleur.tools.xml_util.convert_fleur_lo(loelements)[source]

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

aiida_fleur.tools.xml_util.convert_from_fortran_bool(stringbool)[source]

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

Parameters:stringbool – a string (‘t’, ‘f’, ‘F’, ‘T’)
Returns:boolean (either True or False)
aiida_fleur.tools.xml_util.convert_htr_to_ev(value, parser_info_out=None)[source]

Multiplies the value given with the Hartree factor (converts htr to eV)

aiida_fleur.tools.xml_util.convert_to_float(value_string, parser_info_out=None, suc_return=True)[source]

Tries to make a float out of a string. If it can’t it logs a warning and returns True or False if convertion worked or not.

Parameters:value_string – a string
Returns value:the new float or value_string: the string given
Returns:True or False
aiida_fleur.tools.xml_util.convert_to_fortran_bool(boolean)[source]

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

Parameters:boolean – either a boolean or a string (‘True’, ‘False’, ‘F’, ‘T’)
Returns:a string (either ‘t’ or ‘f’)
aiida_fleur.tools.xml_util.convert_to_fortran_string(string)[source]

converts some parameter strings to the format for the inpgen :param string: some string :returns: string in right format (extra “”)

aiida_fleur.tools.xml_util.convert_to_int(value_string, parser_info_out=None, suc_return=True)[source]

Tries to make a int out of a string. If it can’t it logs a warning and returns True or False if convertion worked or not.

Parameters:value_string – a string
Returns value:the new int or value_string: the string given
Returns:True or False, if suc_return=True
aiida_fleur.tools.xml_util.create_tag(xmlnode, xpath, newelement, create=False, place_index=None, tag_order=None)[source]

This method evaluates an xpath expresion and creates tag in an xmltree under the returned nodes. If the path does exist things will be overwritten, or created. Per default the new element is appended to the elements, but it can also be inserted in a certain position or after certain other tags.

Parameters:
  • xmlnode – an xmltree that represents inp.xml
  • xpathn – a path where to place a new tag
  • newelement – a tag name to be created
  • create – if True and there is no given xpath in the FleurinpData, creates it
  • place_index – defines the place where to put a created tag
  • tag_order – defines a tag order
aiida_fleur.tools.xml_util.delete_att(xmltree, xpath, attrib)[source]

Deletes an xml tag in an xmletree.

Parameters:
  • xmltree – an xmltree that represents inp.xml
  • xpathn – a path to the attribute to be deleted
  • attrib – the name of an attribute
aiida_fleur.tools.xml_util.delete_tag(xmltree, xpath)[source]

Deletes an xml tag in an xmletree.

Parameters:
  • xmltree – an xmltree that represents inp.xml
  • xpathn – a path to the tag to be deleted
aiida_fleur.tools.xml_util.eval_xpath(node, xpath, parser_info=None)[source]

Tries to evalutate an xpath expression. If it fails it logs it. If seferal paths are found, return a list. If only one - returns the value.

:param root node of an etree and an xpath expression (relative, or absolute) :returns either nodes, or attributes, or text

aiida_fleur.tools.xml_util.eval_xpath2(node, xpath, parser_info=None)[source]

Tries to evalutate an xpath expression. If it fails it logs it. Always return a list.

:param root node of an etree and an xpath expression (relative, or absolute) :returns a node list

aiida_fleur.tools.xml_util.eval_xpath3(node, xpath, create=False, place_index=None, tag_order=None)[source]

Tries to evalutate an xpath expression. If it fails it logs it. If create == True, creates a tag

:param root node of an etree and an xpath expression (relative, or absolute) :returns always a node list

aiida_fleur.tools.xml_util.get_inpgen_para_from_xml(inpxmlfile, inpgen_ready=True)[source]

This routine returns an python dictionary produced from the inp.xml file, which can be used as a calc_parameters node by inpgen. Be aware that inpgen does not take all information that is contained in an inp.xml file

Parameters:
  • inpxmlfile – and xml etree of a inp.xml file
  • inpgen_ready – Bool, return a dict which can be inputed into inpgen while setting atoms
Return new_parameters:
 

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

aiida_fleur.tools.xml_util.get_inpgen_paranode_from_xml(inpxmlfile)[source]

This routine returns an AiiDA Parameter Data type produced from the inp.xml file, which can be used by inpgen.

Returns:ParameterData node
aiida_fleur.tools.xml_util.get_inpxml_file_structure()[source]

This routine returns the structure/layout of the ‘inp.xml’ file.

Basicly the plug-in should know from this routine, what things are allowed to be set and where, i.e all attributes and their xpaths. As a developer make sure to use this routine always of you need information about the inp.xml file structure. Therefore, this plug-in should be easy to adjust to other codes with xml files as input files. Just rewrite this routine.

For now the structure of the xmlinp file for fleur is hardcoded. If big changes are in the ‘inp.xml’ file, maintain this routine. TODO: Maybe this is better done, by reading the xml schema datei instead. And maybe it should also work without the schema file, do we want this?

Parameters:Nothing – TODO xml schema
Return all_switches_once:
 list of all switches (‘T’ or ‘F’) which are allowed to be set
Return all_switches_several:
 list of all switches (‘T’ or ‘F’) which are allowed to be set
Return other_attributes_once:
 list of all attributes, which occur just once (can be tested)
Return other_attributes_several:
 list of all attributes, which can occur more then once
Return all_text:
 list of all text of tags, which can be set
Return all_attrib_xpath:
 dictonary (attrib, xpath), of all possible attributes with their xpath expression for the xmp inp
Return expertkey:
 keyname (should not be in any other list), which can be used to set anything in the file, by hand, (for experts, and that plug-in does not need to be directly maintained if xmlinp gets a new switch)
aiida_fleur.tools.xml_util.get_xml_attribute(node, attributename, parser_info_out=None)[source]

Get an attribute value from a node.

Params node:a node from etree
Params attributename:
 a string with the attribute name.
Returns:either attributevalue, or None
aiida_fleur.tools.xml_util.inpxml_todict(parent, xmlstr)[source]

Recursive operation which transforms an xml etree to python nested dictionaries and lists. Decision to add a list is if the tag name is in the given list tag_several

Parameters:
  • parent – some xmltree, or xml element
  • xmlstr – structure/layout of the xml file in xmlstr is tags_several: a list of the tags, which should be converted to a list, not a dictionary(because they are known to occur more often, and want to be accessed in a list later.
Returns:

a python dictionary

aiida_fleur.tools.xml_util.is_sequence(arg)[source]

Checks if arg is a sequence

aiida_fleur.tools.xml_util.replace_tag(xmltree, xpath, newelement)[source]

replaces a xml tag by another tag on an xmletree in place

Parameters:
  • xmltree – an xmltree that represents inp.xml
  • xpathn – a path to the tag to be replaced
  • newelement – a new tag
aiida_fleur.tools.xml_util.set_dict_or_not(para_dict, key, value)[source]

setter method for a dictionary that will not set the key, value pair. if the key is [] or None.

aiida_fleur.tools.xml_util.set_inpchanges(fleurinp_tree_copy, change_dict)[source]

Makes given changes directly in the inp.xml file. Afterwards updates the inp.xml file representation and the current inp_userchanges dictionary with the keys provided in the ‘change_dict’ dictionary.

Parameters:
  • fleurinp_tree_copy – a lxml tree that represents inp.xml
  • change_dict – a python dictionary with the keys to substitute. It works like dict.update(), adding new keys and overwriting existing keys.
Returns new_tree:
 

a lxml tree with applied changes

An example of change_dict:

change_dict = {'itmax' : 1,
               'l_noco': True,
               'ctail': False,
               'l_ss': True}

A full list of supported keys in the change_dict can be found in get_inpxml_file_structure():

'comment': '/fleurInput/comment',
'relPos': '/fleurInput/atomGroups/atomGroup/relPos',
'filmPos': '/fleurInput/atomGroups/atomGroup/filmPos',
'absPos': '/fleurInput/atomGroups/atomGroup/absPos',
'qss': '/fleurInput/calculationSetup/nocoParams/qss',
'l_ss': '/fleurInput/calculationSetup/nocoParams',
'row-1': '/fleurInput/cell/bulkLattice/bravaisMatrix',
'row-2': '/fleurInput/cell/bulkLattice/bravaisMatrix',
'row-3': '/fleurInput/cell/bulkLattice/bravaisMatrix',
'a1': '/fleurInput/cell/filmLattice/a1',  # switches once
'dos': '/fleurInput/output',
'band': '/fleurInput/output',
'secvar': '/fleurInput/calculationSetup/expertModes',
'ctail': '/fleurInput/calculationSetup/coreElectrons',
'frcor': '/fleurInput/calculationSetup/coreElectrons',
'l_noco': '/fleurInput/calculationSetup/magnetism',
'l_J': '/fleurInput/calculationSetup/magnetism',
'swsp': '/fleurInput/calculationSetup/magnetism',
'lflip': '/fleurInput/calculationSetup/magnetism',
'off': '/fleurInput/calculationSetup/soc',
'spav': '/fleurInput/calculationSetup/soc',
'l_soc': '/fleurInput/calculationSetup/soc',
'soc66': '/fleurInput/calculationSetup/soc',
'pot8': '/fleurInput/calculationSetup/expertModes',
'eig66': '/fleurInput/calculationSetup/expertModes',
'l_f': '/fleurInput/calculationSetup/geometryOptimization',
'gamma': '/fleurInput/calculationSetup/bzIntegration/kPointMesh',
'gauss': '',
'tria': '',
'invs': '',
'zrfs': '',
'vchk': '/fleurInput/output/checks',
'cdinf': '/fleurInput/output/checks',
'disp': '/fleurInput/output/checks',
'vacdos': '/fleurInput/output',
'integ': '/fleurInput/output/vacuumDOS',
'star': '/fleurInput/output/vacuumDOS',
'iplot': '/fleurInput/output/plotting',
'score': '/fleurInput/output/plotting',
'plplot': '/fleurInput/output/plotting',
'slice': '/fleurInput/output',
'pallst': '/fleurInput/output/chargeDensitySlicing',
'form66': '/fleurInput/output/specialOutput',
'eonly': '/fleurInput/output/specialOutput',
'bmt': '/fleurInput/output/specialOutput',
'relativisticCorrections': '/fleurInput/xcFunctional',
'calculate': '/fleurInput/atomGroups/atomGroup/force',
'flipSpin': '/fleurInput/atomSpecies/species',
'Kmax': '/fleurInput/calculationSetup/cutoffs',
'Gmax': '/fleurInput/calculationSetup/cutoffs',
'GmaxXC': '/fleurInput/calculationSetup/cutoffs',
'numbands': '/fleurInput/calculationSetup/cutoffs',
'itmax': '/fleurInput/calculationSetup/scfLoop',
'minDistance': '/fleurInput/calculationSetup/scfLoop',
'maxIterBroyd': '/fleurInput/calculationSetup/scfLoop',
'imix': '/fleurInput/calculationSetup/scfLoop',
'alpha': '/fleurInput/calculationSetup/scfLoop',
'spinf': '/fleurInput/calculationSetup/scfLoop',
'kcrel': '/fleurInput/calculationSetup/coreElectrons',
'jspins': '/fleurInput/calculationSetup/magnetism',
'theta': '/fleurInput/calculationSetup/soc',
'phi': '/fleurInput/calculationSetup/soc',
'gw': '/fleurInput/calculationSetup/expertModes',
'lpr': '/fleurInput/calculationSetup/expertModes',
'isec1': '/fleurInput/calculationSetup/expertModes',
'forcemix': '/fleurInput/calculationSetup/geometryOptimization',
'forcealpha': '/fleurInput/calculationSetup/geometryOptimization',
'force_converged': '/fleurInput/calculationSetup/geometryOptimization',
'qfix': '/fleurInput/calculationSetup/geometryOptimization',
'epsdisp': '/fleurInput/calculationSetup/geometryOptimization',
'epsforce': '/fleurInput/calculationSetup/geometryOptimization',
'valenceElectrons': '/fleurInput/calculationSetup/bzIntegration',
'mode': '/fleurInput/calculationSetup/bzIntegration',
'fermiSmearingEnergy': '/fleurInput/calculationSetup/bzIntegration',
'nx': '/fleurInput/calculationSetup/bzIntegration/kPointMesh',
'ny': '/fleurInput/calculationSetup/bzIntegration/kPointMesh',
'nz': '/fleurInput/calculationSetup/bzIntegration/kPointMesh',
'count': '/fleurInput/calculationSetup/kPointCount',
'ellow': '/fleurInput/calculationSetup/energyParameterLimits',
'elup': '/fleurInput/calculationSetup',
'filename': '/fleurInput/cell/symmetryFile',
'scale': '/fleurInput/cell/bulkLattice',
'ndir': '/fleurInput/output/densityOfStates',
'minEnergy': '/fleurInput/output/densityOfStates',
'maxEnergy': '/fleurInput/output/densityOfStates',
'sigma': ' /fleurInput/output/densityOfStates',
'layers': '/fleurInput/output/vacuumDOS',
'nstars': '/fleurInput/output/vacuumDOS',
'locx1': '/fleurInput/output/vacuumDOS',
'locy1': '/fleurInput/output/vacuumDOS',
'locx2': '/fleurInput/output/vacuumDOS',
'locy2': '/fleurInput/output/vacuumDOS',
'nstm': '/fleurInput/output/vacuumDOS',
'tworkf': '/fleurInput/output/vacuumDOS',
'numkpt': '/fleurInput/output/chargeDensitySlicing',
'minEigenval': '/fleurInput/output/chargeDensitySlicing',
'maxEigenval': '/fleurInput/output/chargeDensitySlicing',
'nnne': '/fleurInput/output/chargeDensitySlicing',
'dVac': '/fleurInput/cell/filmLattice',
'dTilda': '/fleurInput/cell/filmLattice',
'xcFunctional': '/fleurInput/xcFunctional/name',  # other_attributes_more
'name': {'/fleurInput/constantDefinitions', '/fleurInput/xcFunctional',
        '/fleurInput/atomSpecies/species'},
'value': '/fleurInput/constantDefinitions',
'element': '/fleurInput/atomSpecies/species',
'atomicNumber': '/fleurInput/atomSpecies/species',
'coreStates': '/fleurInput/atomSpecies/species',
'magMom': '/fleurInput/atomSpecies/species',
'radius': '/fleurInput/atomSpecies/species/mtSphere',
'gridPoints': '/fleurInput/atomSpecies/species/mtSphere',
'logIncrement': '/fleurInput/atomSpecies/species/mtSphere',
'lmax': '/fleurInput/atomSpecies/species/atomicCutoffs',
'lnonsphr': '/fleurInput/atomSpecies/species/atomicCutoffs',
's': '/fleurInput/atomSpecies/species/energyParameters',
'p': '/fleurInput/atomSpecies/species/energyParameters',
'd': '/fleurInput/atomSpecies/species/energyParameters',
'f': '/fleurInput/atomSpecies/species/energyParameters',
'type': '/fleurInput/atomSpecies/species/lo',
'l': '/fleurInput/atomSpecies/species/lo',
'n': '/fleurInput/atomSpecies/species/lo',
'eDeriv': '/fleurInput/atomSpecies/species/lo',
'species': '/fleurInput/atomGroups/atomGroup',
'relaxXYZ': '/fleurInput/atomGroups/atomGroup/force'
aiida_fleur.tools.xml_util.set_kpath(fleurinp_tree_copy, kpath, count, gamma)[source]

Sets a k-path directly into inp.xml

Parameters:
  • fleurinp_tree_copy – a lxml tree that represents inp.xml
  • kpath – a dictionary with kpoint name as key and k point coordinate as value
  • count – number of k-points
  • gamma – a fortran-type boolean that controls if the gamma-point should be included in the k-point mesh
Returns new_tree:
 

a lxml tree with applied changes

aiida_fleur.tools.xml_util.set_nkpts(fleurinp_tree_copy, count, gamma)[source]

Sets a k-point mesh directly into inp.xml

Parameters:
  • fleurinp_tree_copy – a lxml tree that represents inp.xml
  • count – number of k-points
  • gamma – a fortran-type boolean that controls if the gamma-point should be included in the k-point mesh
Returns new_tree:
 

a lxml tree with applied changes

aiida_fleur.tools.xml_util.set_species(fleurinp_tree_copy, species_name, attributedict, create=False)[source]

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

Parameters:
  • fleurinp_tree_copy – xml etree of the inp.xml
  • species_name – string, name of the specie you want to change
  • attributedict – a python dict specifying what you want to change.
  • create – bool, if species does not exist create it and all subtags?
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 fleurinp_tree_copy:
 

xml etree of the new inp.xml

attributedict 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:

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

Another example:

'attributedict': {'special': {'socscale': 0.0}}

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

aiida_fleur.tools.xml_util.set_species_label(fleurinp_tree_copy, at_label, attributedict, create=False)[source]

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

Parameters:
  • fleurinp_tree_copy – xml etree of the inp.xml
  • at_label – string, a label of the atom which specie will be changed. ‘all’ to change all the species
  • attributedict – a python dict specifying what you want to change.
  • create – bool, if species does not exist create it and all subtags?
aiida_fleur.tools.xml_util.shift_value(fleurinp_tree_copy, change_dict, mode='abs')[source]

Shifts numertical values of some tags directly in the inp.xml file.

Parameters:
  • fleurinp_tree_copy – a lxml tree that represents inp.xml
  • change_dict – a python dictionary with the keys to shift.
  • mode – ‘abs’ if change given is absolute, ‘rel’ if relative
Returns new_tree:
 

a lxml tree with shifted values

An example of change_dict:

change_dict = {'itmax' : 1, 'dVac': -0.123}
aiida_fleur.tools.xml_util.shift_value_species_label(fleurinp_tree_copy, at_label, attr_name, value_given, mode='abs')[source]

Shifts value of a specie by label if at_label contains ‘all’ then applies to all species

Parameters:
  • fleurinp_tree_copy – xml etree of the inp.xml
  • at_label – string, a label of the atom which specie will be changed. ‘all’ if set up all species
  • attr_name – name of the attribute to change
  • value_given – value to add or to multiply by
  • mode – ‘rel’ for multiplication or ‘abs’ for addition
aiida_fleur.tools.xml_util.write_new_fleur_xmlinp_file(inp_file_xmltree, fleur_change_dic, xmlinpstructure)[source]

This modifies the xml-inp file. Makes all the changes wanted by the user or sets some default values for certain modes

Params inp_file_xmltree:
 xml-tree of the xml-inp file
Params fleur_change_dic:
 dictionary {attrib_name : value} with all the wanted changes.
Returns:an etree of the xml-inp file with changes.
aiida_fleur.tools.xml_util.xml_set_all_attribv(xmltree, xpathn, attributename, attribv, create=False)[source]

Routine sets the value of an attribute in the xml file on all places it occurs

Parameters:
  • xmltree – an xmltree that represents inp.xml
  • xpathn – a path to the attribute
  • attributename – an attribute name
  • attribv – an attribute value which will be set
  • create – if True and there is no given xpath in the FleurinpData, creates it
Returns:

None, or an etree

Comment: Element.set will add the attribute if it does not exist,
xpath expression has to exist
example: xml_set_first_attribv(tree, ‘/fleurInput/atomGroups/atomGroup/force’, ‘relaxXYZ’, ‘TTF’)
xml_set_first_attribv(tree, ‘/fleurInput/atomGroups/atomGroup/force’, ‘calculate’, ‘F’)
aiida_fleur.tools.xml_util.xml_set_all_text(xmltree, xpathn, text, create=False, tag_order=None)[source]

Routine sets the text of a tag in the xml file

Parameters:
  • xmltree – an xmltree that represents inp.xml
  • xpathn – a path to the attribute
  • text – text to be set
  • create – if True and there is no given xpath in the FleurinpData, creates it
  • place_index – if create=True, defines the place where to put a created tag
  • tag_order – if create=True, defines a tag order
aiida_fleur.tools.xml_util.xml_set_attribv_occ(xmltree, xpathn, attributename, attribv, occ=None, create=False)[source]

Routine sets the value of an attribute in the xml file on only the places specified in occ

Parameters:
  • xmltree – an xmltree that represents inp.xml
  • xpathn – a path to the attribute
  • attributename – an attribute name
  • attribv – an attribute value which will be set
  • occ – a list of integers specifying number of occurrence to be set
  • create – if True and there is no given xpath in the FleurinpData, creates it
Comment: Element.set will add the attribute if it does not exist,
xpath expression has to exist
example: xml_set_first_attribv(tree, ‘/fleurInput/calculationSetup’, ‘band’, ‘T’)
xml_set_first_attribv(tree, ‘/fleurInput/calculationSetup’, ‘dos’, ‘F’)
aiida_fleur.tools.xml_util.xml_set_first_attribv(xmltree, xpathn, attributename, attribv, create=False)[source]

Routine sets the value of the first found attribute in the xml file

Parameters:
  • xmltree – an xmltree that represents inp.xml
  • xpathn – a path to the attribute
  • attributename – an attribute name
  • attribv – an attribute value which will be set
  • create – if True and there is no given xpath in the FleurinpData, creates it
Returns:

None, or an etree

Comment: Element.set will add the attribute if it does not exist,
xpath expression has to exist
example: xml_set_first_attribv(tree, ‘/fleurInput/calculationSetup’, ‘band’, ‘T’)
xml_set_first_attribv(tree, ‘/fleurInput/calculationSetup’, ‘dos’, ‘F’)
aiida_fleur.tools.xml_util.xml_set_text(xmltree, xpathn, text, create=False, place_index=None, tag_order=None)[source]

Routine sets the text of a tag in the xml file

Parameters:
  • xmltree – an xmltree that represents inp.xml
  • xpathn – a path to the attribute
  • text – text to be set
  • create – if True and there is no given xpath in the FleurinpData, creates it
  • place_index – if create=True, defines the place where to put a created tag
  • tag_order – if create=True, defines a tag order

example:

xml_set_text(tree, ‘/fleurInput/comment’, ‘Test Fleur calculation for AiiDA plug-in’)

but also coordinates and Bravais Matrix!:

xml_set_text(tree, ‘/fleurInput/atomGroups/atomGroup/relPos’,’1.20000 PI/3 5.1-MYCrazyCostant’)
aiida_fleur.tools.xml_util.xml_set_text_occ(xmltree, xpathn, text, create=False, occ=0, place_index=None, tag_order=None)[source]

Routine sets the text of a tag in the xml file

Parameters:
  • xmltree – an xmltree that represents inp.xml
  • xpathn – a path to the attribute
  • text – text to be set
  • create – if True and there is no given xpath in the FleurinpData, creates it
  • occ – an integer that sets occurrence number to be set
  • place_index – if create=True, defines the place where to put a created tag
  • tag_order – if create=True, defines a tag order

Utility for LDA+U density matrix files

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

aiida_fleur.tools.set_nmmpmat.fac(n)[source]

Returns the factorial of n

aiida_fleur.tools.set_nmmpmat.get_wigner_matrix(l, phi, theta)[source]

Produces the wigner rotation matrix for the density matrix

Parameters:
  • l – int, orbital quantum number
  • phi – float, angle (radian) corresponds to euler angle alpha
  • theta – float, angle (radian) corresponds to euler angle beta
aiida_fleur.tools.set_nmmpmat.set_nmmpmat(fleurinp_tree_copy, nmmp_lines_copy, species_name, orbital, spin, occStates=None, denmat=None, phi=None, theta=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:
  • fleurinp_tree_copy – an xmltree that represents inp.xml
  • nmmp_lines_copy – list of lines in the n_mmp_mat file
  • species_name – string, name of the species you want to change
  • orbital – integer, orbital quantum number of the LDA+U procedure to be modified
  • spin – integer, specifies which spin block should be modified
  • occStates – list, sets the diagonal elements of the density matrix and everything else to zero
  • denmat – matrix, specify the density matrix explicitely
  • phi – float, optional angle (radian), by which to rotate the density matrix before writing it
  • theta – float, optional angle (radian), by which to rotate the density matrix before writing it
Raises:
  • ValueError – If something in the input is wrong
  • KeyError – If no LDA+U procedure is found on a species
aiida_fleur.tools.set_nmmpmat.validate_nmmpmat(fleurinp_tree, nmmp_lines)[source]

Checks that the given nmmp_lines is valid with the given fleurinp_tree

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:
  • fleurinp_tree_copy – an xmltree that represents inp.xml
  • nmmp_lines_copy – list of lines in the n_mmp_mat file
Raises:

ValueError – if any of the above checks are violated.

Parameter utility

General Parameter

This contains code snippets and utility useful for dealing with parameter data nodes commonly used by the fleur plugin and workflows

aiida_fleur.tools.dict_util.clean_nones(dict_to_clean)[source]

Recursively remove all keys which values are None from a nested dictionary return the cleaned dictionary

Parameters:dict_to_clean – (dict): python dictionary to remove keys with None as value
Returns:dict, cleaned dictionary
aiida_fleur.tools.dict_util.dict_merger(dict1, dict2)[source]

Merge recursively two nested python dictionaries and if key is in both digionaries tries to add the entries in both dicts. (merges two subdicts, adds lists, strings, floats and numbers together!)

Parameters:
  • dict1 – dict
  • dict2 – dict
Return dict:

Merged dict

aiida_fleur.tools.dict_util.extract_elementpara(parameter_dict, element)[source]
Parameters:
  • parameter_dict – python dict, parameter node for inpgen
  • element – string, i.e ‘W’
Returns:

python dictionary, parameter node which contains only the atom parameters for the given element

aiida_fleur.tools.dict_util.recursive_merge(left: Dict[str, Any], right: Dict[str, Any]) → Dict[str, Any][source]

Recursively merge two dictionaries into a single dictionary.

keys in right override keys in left!

Parameters:
  • left – first dictionary.
  • right – second dictionary.
Returns:

the recursively merged dictionary.

Merge Parameter

This module, contains a method to merge Dict nodes used by the FLEUR inpgen. This might also be of interest for other all-electron codes

aiida_fleur.tools.merge_parameter.merge_parameter(Dict1, Dict2, overwrite=True, merge=True)[source]

Merges two Dict nodes. Additive: uses all namelists of both. If they have a namelist in common. Dict2 will overwrite the namelist of Dict. If this is not wanted. set overwrite = False. Then attributes of both will be added, but attributes from Dict1 won’t be overwritten.

Parameters:
  • Dict1 – AiiDA Dict Node
  • Dict2 – AiiDA Dict Node
  • overwrite – bool, default True
  • merge – bool, default True

returns: AiiDA Dict Node

#TODO be more carefull how to merge ids in atom namelists, i.e species labels

aiida_fleur.tools.merge_parameter.merge_parameter_cf(Dict1, Dict2, overwrite=None)[source]

calcfunction of merge_parameters

aiida_fleur.tools.merge_parameter.merge_parameters(DictList, overwrite=True)[source]

Merge together all parameter nodes in the given list.

Corehole/level utility

Contains helper functions to create core-holes in Fleur input files from AiiDA data nodes.

aiida_fleur.tools.create_corehole.create_corehole_para(structure, kind, econfig, species_name='corehole', parameterdata=None)[source]

This methods sets of electron configurations for a kind or position given, make sure to break the symmetry for this position/kind beforehand, otherwise you will create several coreholes.

Parameters:
  • structure – StructureData
  • kind – a string with the kind_name (TODO: alternative the kind object)
  • econfig – string, e.g. econfig = “[Kr] 5s2 4d10 4f13 | 5p6 5d5 6s2” to set, i.e. the corehole
Returns:

a Dict node

In this module you find methods to parse/extract corelevel shifts from an out.xml file of FLEUR.

aiida_fleur.tools.extract_corelevels.clshifts_to_be(coreleveldict, reference_dict, warn=False)[source]

This methods converts corelevel shifts to binding energies, if a reference is given. These can than be used for plotting.

Params reference_dict:
 An example:
reference_dict = {'W' : {'4f7/2' : [124],
                         '4f5/2' : [102]},
                  'Be' : {'1s': [117]}}
Params coreleveldict:
 An example:
coreleveldict = {'W' : {'4f7/2' : [0.4, 0.3, 0.4 ,0.1],
                        '4f5/2' : [0, 0.3, 0.4, 0.1]},
                 'Be' : {'1s': [0, 0.2, 0.4, 0.1, 0.3]}
aiida_fleur.tools.extract_corelevels.convert_to_float(value_string, parser_info=None)[source]

Tries to make a float out of a string. If it can’t it logs a warning and returns True or False if convertion worked or not.

Parameters:value_string – a string
Returns value:the new float or value_string: the string given
Retruns:True or False
aiida_fleur.tools.extract_corelevels.extract_corelevels(outxmlfile, options=None)[source]

Extracts corelevels out of out.xml files

Params outxmlfile:
 path to out.xml file
Parameters:options – A dict: ‘iteration’ : X/’all’
Returns corelevels:
 A list of the form:
[atomtypes][spin][dict={atomtype : '', corestates : list_of_corestates}]
[atomtypeNumber][spin]['corestates'][corestate number][attribute]
get corelevel energy of first atomtype, spin1, corelevels[0][0]['corestates'][i]['energy']
Example of output:
 
[[{'atomtype': '     1',
'corestates': [{'energy': -3.6489930627,
                'j': ' 0.5',
                'l': ' 0',
                'n': ' 1',
                'weight': 2.0}],
'eigenvalue_sum': '     -7.2979861254',
'kin_energy': '     13.4757066163',
'spin': '1'}],
[{'atomtype': '     2',
'corestates': [{'energy': -3.6489930627,
                'j': ' 0.5',
                'l': ' 0',
                'n': ' 1',
                'weight': 2.0}],
'eigenvalue_sum': '     -7.2979861254',
'kin_energy': '     13.4757066163',
'spin': '1'}]]
aiida_fleur.tools.extract_corelevels.parse_state_card(corestateNode, iteration_node, parser_info=None)[source]

Parses the ONE core state card

Params corestateNode:
 an etree element (node), of a fleur output corestate card
Params iteration_node:
 an etree element, iteration node
Params jspin:integer 1 or 2
Returns:a pythondict of type:
{'eigenvalue_sum' : eigenvalueSum,
 'corestates': states,
 'spin' : spin,
 'kin_energy' : kinEnergy,
 'atomtype' : atomtype}

You find the usual binding_energy for all elements in the periodic table.

aiida_fleur.tools.element_econfig_list.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.

aiida_fleur.tools.element_econfig_list.econfigstr_hole(econfigstr, corelevel, highesunoccp, htype='valence')[source]

# ‘1s2 | 2s2’ , ‘1s2’ , ‘2p0’ -> ‘1s1 | 2s2 2p1’

Param:string
Param:string
Param:string
Returns:string
aiida_fleur.tools.element_econfig_list.get_coreconfig(element, full=False)[source]

returns the econfiguration as a string of an element.

Param:element string
Param:full, bool (econfig without [He]…)
Returns:string
Note:Be careful with base strings…
aiida_fleur.tools.element_econfig_list.get_econfig(element, full=False)[source]

returns the econfiguration as a string of an element.

Params element:element string
Params full:a bool (econfig without [He]…)
Returns:a econfig string
aiida_fleur.tools.element_econfig_list.get_spin_econfig(fulleconfigstr)[source]

converts and econfig string to a full spin econfig 1s2 2s2 2p6’ - > ‘1s1/2 2s1/2 2p1/2 2p3/2’

aiida_fleur.tools.element_econfig_list.get_state_occ(econfigstr, corehole='', valence='', ch_occ=1.0)[source]

finds out all not full occupied states and returns a dictionary of them return a dict i.e corehole ‘4f 5/2’ ch_occ full or fractional corehole occupation? valence: orbital sting ‘5d’, is to adjust the charges for fractional coreholes To that orbital occupation ch_occ - 1 will be added.

aiida_fleur.tools.element_econfig_list.highest_unocc_valence(econfigstr)[source]

returns the highest not full valence orbital. If all are full, it returns ‘’ #maybe should be advanced to give back the next highest unocc

aiida_fleur.tools.element_econfig_list.rek_econ(econfigstr)[source]

recursive routine to return a full econfig ‘[Xe] 4f14 | 5d10 6s2 6p4’ -> ‘1s 2s … 4f14 | 5d10 6s2 6p4’

Common aiida utility

In here we put all things util (methods, code snipets) that are often useful, but not yet in AiiDA itself. So far it contains:

export_extras import_extras delete_nodes (FIXME) delete_trash (FIXME) create_group

aiida_fleur.tools.common_aiida.create_group(name, nodes, description=None, add_if_exist=False)[source]

Creates a group for a given node list.

!!! Now aiida-core has these functionality, use it from there instead!!! So far this is only an AiiDA verdi command.

Params name:string name for the group
Params nodes:list of AiiDA nodes, pks, or uuids
Params description:
 optional string that will be stored as description for the group
Returns:the group, AiiDa group

Usage example:

group_name = 'delta_structures_gustav'
nodes_to_group_pks =[2142, 2084]
create_group(group_name, nodes_to_group_pks,
             description='delta structures added by hand. from Gustavs inpgen files')
aiida_fleur.tools.common_aiida.export_extras(nodes, filename='node_extras.txt')[source]

Writes uuids and extras of given nodes to a json-file. This is useful for import/export because currently extras are lost. Therefore this can be used to save and restore the extras via import_extras().

Param:nodes: list of AiiDA nodes, pks, or uuids
Param:filename, string where to store the file and its name

example use: .. code-block:: python

node_list = [120,121,123,46] export_extras(node_list)
aiida_fleur.tools.common_aiida.get_nodes_from_group(group, return_format='uuid')[source]

Returns a list of pk or uuid of a nodes in a given group. Since 1.1.0, this function does !!! Now aiida-core has these functionality, use it from there instead!!!

not load a group using the label or any other identification. Use Group.objects.get(filter=ID) to pre-load this, available filters are: id, uuid, label, type_string, time, description, user_id.

aiida_fleur.tools.common_aiida.import_extras(filename)[source]

Reads in node uuids and extras from a file (most probably generated by export_extras()) and applies them to nodes in the DB.

This is useful for import/export because currently extras are lost. Therefore this can be used to save and restore the extras on the nodes.

Param:filename, string what file to read from (has to be json format)

example use: import_extras(‘node_extras.txt’)

Reading in Cif files

In this module you find a method (read_cif_folder) to read in all .cif files from a folder and store the structures in the database.

aiida_fleur.tools.read_cif_folder.read_cif_folder(path='/home/docs/checkouts/readthedocs.org/user_builds/aiida-fleur/checkouts/v1.1.3/docs/source', recursive=True, store=False, log=False, comments='', extras='', logfile_name='read_cif_folder_logfile')[source]

Method to read in cif files from a folder and its subfolders. It can convert them into AiiDA structures and store them.

defaults input parameter values are: path=”.”, recursive=True, store=False, log=False, comments=’’, extras=’’

Params:path: Path to the dictionary with the files (default, where this method is called)
Params:recursive: bool, If True: looks aso in subfolders, if False: just given dir
Params:store: bool, if True: stores structures in database
Params:log: bool, if True, writes a logfile with information (pks, and co)
Params:comments: string: comment to add to the structures
Params:extras: dir/string/arb: extras added to the structures stored in the db

IO routines

Here we collect IO routines and their utility, for writting certain things to files, or post process files. For example collection of data or database evaluations, for other people.

Common utitlity for fleur workchains

In here we put all things (methods) that are common to workflows AND depend on AiiDA classes, therefore can only be used if the dbenv is loaded. Util that does not depend on AiiDA classes should go somewhere else.

aiida_fleur.tools.common_fleur_wf.calc_time_cost_function(natom, nkpt, kmax, nspins=1)[source]

Estimates the cost of simulating a single iteration of a system

aiida_fleur.tools.common_fleur_wf.calc_time_cost_function_total(natom, nkpt, kmax, niter, nspins=1)[source]

Estimates the cost of simulating a all iteration of a system

aiida_fleur.tools.common_fleur_wf.cost_ratio(total_costs, walltime_sec, ncores)[source]

Estimates if simulation cost matches resources

aiida_fleur.tools.common_fleur_wf.determine_favorable_reaction(reaction_list, workchain_dict)[source]

Finds out with reaction is more favorable by simple energy standpoints

# TODO check physics reaction list: list of reaction strings workchain_dict = {‘Be12W’ : uuid_wc or output, ‘Be2W’ : uuid, …}

return dictionary that ranks the reactions after their enthalpy

TODO: refactor aiida part out of this, leaving an aiida independent part and one more universal

aiida_fleur.tools.common_fleur_wf.find_last_submitted_calcjob(restart_wc)[source]

Finds the last CalcJob submitted in a higher-level workchain and returns it’s uuid

aiida_fleur.tools.common_fleur_wf.find_last_submitted_workchain(restart_wc)[source]

Finds the last WorkChain submitted in a higher-level workchain and returns it’s uuid

aiida_fleur.tools.common_fleur_wf.get_inputs_fleur(code, remote, fleurinp, options, label='', description='', settings=None, serial=False, only_even_MPI=False)[source]

Assembles the input dictionary for Fleur Calculation. Does not check if a user gave correct input types, it is the work of FleurCalculation to check it.

Parameters:
  • code – FLEUR code of Code type
  • remote – remote_folder from the previous calculation of RemoteData type
  • fleurinp – FleurinpData object representing input files
  • options – calculation options that will be stored in metadata
  • label – a string setting a label of the CalcJob in the DB
  • description – a string setting a description of the CalcJob in the DB
  • settings – additional settings of Dict type
  • serial – True if run a calculation in a serial mode

Example of use:

inputs_build = get_inputs_inpgen(structure, inpgencode, options, label,
                                 description, params=params)
future = self.submit(inputs_build)
aiida_fleur.tools.common_fleur_wf.get_inputs_inpgen(structure, inpgencode, options, label='', description='', settings=None, params=None, **kwargs)[source]

Assembles the input dictionary for Fleur Calculation.

Parameters:
  • structure – input structure of StructureData type
  • inpgencode – inpgen code of Code type
  • options – calculation options that will be stored in metadata
  • label – a string setting a label of the CalcJob in the DB
  • description – a string setting a description of the CalcJob in the DB
  • params – input parameters for inpgen code of Dict type

Example of use:

inputs_build = get_inputs_inpgen(structure, inpgencode, options, label,
                                 description, params=params)
future = self.submit(inputs_build)
aiida_fleur.tools.common_fleur_wf.get_kpoints_mesh_from_kdensity(structure, kpoint_density)[source]

params: structuredata, Aiida structuredata params: kpoint_density

returns: tuple (mesh, offset) returns: kpointsdata node

aiida_fleur.tools.common_fleur_wf.get_mpi_proc(resources)[source]

Determine number of total processes from given resource dict

aiida_fleur.tools.common_fleur_wf.is_code(code)[source]

Test if the given input is a Code node, by object, id, uuid, or pk if yes returns a Code node in all cases if no returns None

aiida_fleur.tools.common_fleur_wf.optimize_calc_options(nodes, mpi_per_node, omp_per_mpi, use_omp, mpi_omp_ratio, fleurinpData=None, kpts=None, sacrifice_level=0.9, only_even_MPI=False)[source]

Makes a suggestion on parallelisation setup for a particular fleurinpData. Only the total number of k-points is analysed: the function suggests ideal k-point parallelisation + OMP parallelisation (if required). Note: the total number of used CPUs per node will not exceed mpi_per_node * omp_per_mpi.

Sometimes perfect parallelisation is terms of idle CPUs is not what used wanted because it can harm MPI/OMP ratio. Thus the function first chooses first top parallelisations in terms of total CPUs used (bigger than sacrifice_level * maximal_number_CPUs_possible). Then a parallelisation which is the closest to the MPI/OMP ratio is chosen among them and returned.

Parameters:
  • nodes – maximal number of nodes that can be used
  • mpi_per_node – an input suggestion of MPI tasks per node
  • omp_per_mpi – an input suggestion for OMP tasks per MPI process
  • use_omp – False if OMP parallelisation is not needed
  • mpi_omp_ratio – requested MPI/OMP ratio
  • fleurinpData – FleurinpData to extract total number of kpts from
  • kpts – the total number of kpts
  • sacrifice_level – sets a level of performance sacrifice that a user can afford for better MPI/OMP ratio.
Parm only_even_MPI:
 

if set to True, the function does not set MPI to an odd number (if possible)

Returns nodes, MPI_tasks, OMP_per_MPI, message:
 

first three are parallelisation info and the last one is an exit message.

aiida_fleur.tools.common_fleur_wf.performance_extract_calcs(calcs)[source]

Extracts some runtime and system data from given fleur calculations

Params calcs:list of calculation nodes/pks/or uuids. Fleur calc specific
Returns data_dict:
 dictionary, dictionary of arrays with the same length, from with a panda frame can be created.

Note: Is not the fastest for many calculations > 1000.

aiida_fleur.tools.common_fleur_wf.test_and_get_codenode(codenode, expected_code_type, use_exceptions=False)[source]

Pass a code node and an expected code (plugin) type. Check that the code exists, is unique, and return the Code object.

Parameters:
  • codenode – the name of the code to load (in the form label@machine)
  • expected_code_type – a string with the plugin that is expected to be loaded. In case no plugins exist with the given name, show all existing plugins of that type
  • use_exceptions – if True, raise a ValueError exception instead of calling sys.exit(1)
Returns:

a Code object

In here we put all things (methods) that are common to workflows AND DO NOT depend on AiiDA classes, therefore can be used without loading the dbenv. Util that does depend on AiiDA classes should go somewhere else.

aiida_fleur.tools.common_fleur_wf_util.balance_equation(equation_string, allow_negativ=False, allow_zero=False, eval_linear=True)[source]

Method that balances a chemical equation.

param equation_string: string (with ‘->’) param allow_negativ: bool, default False, allows for negative coefficients for the products.

return string: balanced equation

balance_equation(“C7H16+O2 -> CO2+H2O”)) balance_equation(“Be12W->Be22W+Be12W”) balance_equation(“Be12W->Be12W”)

have to be intergers everywhere in the equation, factors and formulas

1*C7H16+11*O2 ->7* CO2+8*H2O None 1*Be12W->1*Be12W #TODO The solver better then what we need. Currently if system is over #”Be12W->Be2W+W+Be” solves to {a: 24, b: -d/2 + 144, c: d/2 - 120}-> FAIL-> None # The code fails in the later stage, but this solution should maybe be used.

code adapted from stack exchange (the messy part): https://codegolf.stackexchange.com/questions/8728/balance-chemical-equations

aiida_fleur.tools.common_fleur_wf_util.calc_stoi(unitcellratios, formulas, error_ratio=None)[source]

Calculate the Stoichiometry with errors from a given unit cell ratio, formulas.

Example: calc_stoi([10, 1, 7], [‘Be12Ti’, ‘Be17Ti2’, ‘Be2’], [0.1, 0.01, 0.1]) ({‘Be’: 12.583333333333334, ‘Ti’: 1.0}, {‘Be’: 0.12621369924887876, ‘Ti’: 0.0012256517540566825}) calc_stoi([10, 1, 7], [‘Be12Ti’, ‘Be17Ti2’, ‘Be2’]) ({‘Be’: 12.583333333333334, ‘Ti’: 1.0}, {})

aiida_fleur.tools.common_fleur_wf_util.check_eos_energies(energylist)[source]

Checks if there is an abnormality in the total energies from the Equation of states. i.e. if one point has a larger energy then its two neighbors

Parameters:energylist – list of floats
Returns nnormalies:
 integer
aiida_fleur.tools.common_fleur_wf_util.convert_eq_to_dict(equationstring)[source]

Converts an equation string to a dictionary convert_eq_to_dict(‘1*Be12Ti->10*Be+1*Be2Ti+5*Be’) -> {‘products’: {‘Be’: 15, ‘Be2Ti’: 1}, ‘educts’: {‘Be12Ti’: 1}}

aiida_fleur.tools.common_fleur_wf_util.convert_formula_to_formula_unit(formula)[source]

Converts a formula to the smallest chemical formula unit ‘Be4W2’ -> ‘Be2W’

aiida_fleur.tools.common_fleur_wf_util.convert_frac_formula(formula, max_digits=3)[source]

Converts a formula with fractions to a formula with integer factors only

Be0.5W0.5 -> BeW

Parameters:
  • formula – str, crystal formula i.e. Be2W, Be0.2W0.7
  • max_digits – int default=3, number of digits after which fractions will be cut off
Returns:

string

aiida_fleur.tools.common_fleur_wf_util.determine_convex_hull(formation_en_grid)[source]

Wraps the pyhull packge implementing the qhull algo for our purposes. For now only for 2D phase diagrams Adds the points [1.0, 0.0] and [0.0, 1.0], because in material science these are always there.

Params:formation_en_grid: list of points in phase space [[x, formation_energy]]
Returns:a hul datatype
aiida_fleur.tools.common_fleur_wf_util.determine_formation_energy(struc_te_dict, ref_struc_te_dict)[source]

This method determines the formation energy. E_form = E(A_xB_y) - x*E(A) - y*E(B)

Params struc_te_dict:
 python dictionary in the form of {‘formula’ : total_energy} for the compound(s)
Params ref_struc_te_dict:
 python dictionary in the form of {‘formula’ : total_energy per atom, or per unit cell} for the elements (if the formula of the elements contains a number the total energy is divided by that number)
Returns:list of floats, dict {formula : eform, ..} units energy/per atom, energies have some unit as energies given
aiida_fleur.tools.common_fleur_wf_util.determine_reactions(formula, available_data)[source]

Determines and balances theoretical possible reaction. Stoichiometry ‘Be12W’, [Be12W, Be2W, Be, W, Be22W] -> [[Be22W+Be2W], [Be12W], [Be12+W],…]

Params formula:string, given educts (left side of equation)
Params available_data:
 list of strings of compounds (products), from which all possibilities will be constructed
aiida_fleur.tools.common_fleur_wf_util.get_atomprocent(formula)[source]

This converts a formula to a dictionary with element : atomprocent example converts ‘Be24W2’ to {‘Be’: 24/26, ‘W’ : 2/26}, also BeW to {‘Be’ : 0.5, ‘W’ : 0.5} :params: formula: string :returns: a dict, element : atomprocent

# Todo alternative with structuredata

aiida_fleur.tools.common_fleur_wf_util.get_enhalpy_of_equation(reaction, formenergydict)[source]

calculate the enthalpy per atom of a given reaction from the given data.

param reaction: string param fromenergydict: dictionary that contains the {compound: formationenergy per atom}

# TODO check if physics is right

aiida_fleur.tools.common_fleur_wf_util.get_natoms_element(formula)[source]

Converts ‘Be24W2’ to {‘Be’: 24, ‘W’ : 2}, also BeW to {‘Be’ : 1, ‘W’ : 1}

aiida_fleur.tools.common_fleur_wf_util.inpgen_dict_set_mesh(inpgendict, mesh)[source]

params: python dict, used for inpgen parameterdata node params: mesh either as returned by kpointsdata or tuple of 3 integers

returns: python dict, used for inpgen parameterdata node

aiida_fleur.tools.common_fleur_wf_util.powerset(L)[source]

Constructs the power set, ‘potenz Menge’ of a given list.

return list: of all possible subsets

aiida_fleur.tools.common_fleur_wf_util.ucell_to_atompr(ratio, formulas, element, error_ratio=None)[source]

Converts unit cell ratios into atom ratios.

len(ratio) == len(formulas) (== len(error_ratio)) ucell_to_atompr([10, 1, 7], [‘Be12Ti’, ‘Be17Ti2’, ‘Be2’], element=’Be’, [0.1, 0.1, 0.1])