htesp.htepc

Module to prepare QE input files

Module Attributes

UNREQUESTABLE_FIELDS

Summary fields that are nested documents rather than scalars.

SYMPREC

symmetry tolerance used everywhere a standard cell is derived in this module

INTERNATIONAL_MONOCLINIC

2010_SC-style monoclinic setting (alpha < 90, beta = gamma = 90); the international setting puts the unique angle elsewhere, giving a cell that does not match the k-mesh.

SSSP_EFFICIENCY

Wavefunction cutoffs in Ry, mirroring pseudo.PSEUDO of the packaged config.json so the fallback can never contradict the shipped table (a test asserts they are identical).

CARD_RE

start of a QE "card" (everything that is not part of a namelist)

SYSTEM_KEY_RE

&SYSTEM entries that are rebuilt when a magnetic input is written

Functions

ase_cell_to_structure(ase_cell)

bare_element(label)

'Fe,spin=5' / 'Fe1' -> 'Fe'; anything else is returned as is.

convert_species_list(original_list)

Rename elements in the original list with elements with different spins.

extract_elements_with_spin(original_list)

Extract elements with their spin values from the given list.

insert([input_file, output, keyword, where, ...])

Function to insert keyword in input file :param input_file: :type input_file: (str) input file.

mprester(key)

Return an MPRester for key, importing mp_api on first use.

parse_spin(label)

The spin out of a species label such as 'Fe,spin=5'.

pos_to_kpt(structure_filename, kpoint_density)

Obtain k-point mesh from a structure file.

read_lines(path)

Return the lines of path with their trailing newline stripped.

remove_files(*paths)

Delete each path that exists, quietly skipping the ones that do not.

reorder_dictionary(original_dict, new_order)

Reorder the keys of a dictionary based on a new list of keywords and return the list of keys.

scf_to_dos_scf([input_file, out])

Function to change QE input file from using smearing to 'tetrahedra' method, mainly for DOS calculation

section(lines, start, end)

sed -n '/start/,/end/p' | sed '$d' without a shell.

write_lines(path, lines)

Write lines (given without trailing newlines) to path.

Classes

INPUTscf([filename])

class to process QE input files :param filename: :type filename: (str) QE input file

MpConnect()

Class for connecting to Materials Project (MP) via MP API, extracting properties, and preparing input files for Quantum Espresso (QE) calculations.

OUTPUTscf([filename])

class to extract relax structure from QE output file and update input file :param filename: :type filename: (str) QE output file.

htesp.htepc.mprester(key)[source]

Return an MPRester for key, importing mp_api on first use.

FIX(20): from mp_api.client import MPRester at module scope made every importer of this module – cif_to_gsinput, elastic, site_subs, poscar_to_vasp, qe_input – load mp_api, which in turn imports deltalake and its compiled extension. Where that extension cannot be loaded the interpreter aborts (Fatal Python error: Aborted) rather than raising, so the whole process dies during the import – including the test runner, and including commands that only ever write input files.

Nothing but an actual Materials Project query needs mp_api, so it is imported here, at the one point where a query is about to happen.

htesp.htepc.UNREQUESTABLE_FIELDS = ('bandstructure', 'dos')

Summary fields that are nested documents rather than scalars. FIX(31): setting() asked for available_fields[:-29], which still includes these two. emmet-core validates every requested sub-document, and the payload the API returns for them no longer carries the fields its model declares – dos.elemental.Ru.total.1.task_id ... Field required, bandstructure.setyawan_curtarolo.equivalent_labels ... Field required. One unusable sub-document rejects the whole SummaryDoc, so mainprogram download raised ValidationError for every material that has band-structure or DOS data – which is nearly all of them – while the few without it succeeded. Nothing in HTESP reads either field: band structures and densities of states are computed here, not fetched.

htesp.htepc.SYMPREC = 0.01

symmetry tolerance used everywhere a standard cell is derived in this module

htesp.htepc.INTERNATIONAL_MONOCLINIC = False

2010_SC-style monoclinic setting (alpha < 90, beta = gamma = 90); the international setting puts the unique angle elsewhere, giving a cell that does not match the k-mesh.

htesp.htepc.SSSP_EFFICIENCY = {'Ac': 30, 'Ag': 50, 'Al': 30, 'Am': 30, 'Ar': 60, 'As': 35, 'At': 30, 'Au': 45, 'B': 35, 'Ba': 30, 'Be': 40, 'Bi': 45, 'Bk': 60, 'Br': 30, 'C': 45, 'Ca': 30, 'Cd': 60, 'Ce': 50, 'Cf': 60, 'Cl': 40, 'Cm': 30, 'Co': 45, 'Cr': 40, 'Cs': 30, 'Cu': 55, 'Dy': 40, 'Er': 40, 'Es': 60, 'Eu': 40, 'F': 45, 'Fe': 90, 'Fm': 60, 'Fr': 30, 'Ga': 70, 'Gd': 40, 'Ge': 40, 'H': 60, 'He': 50, 'Hf': 50, 'Hg': 50, 'Ho': 40, 'I': 35, 'In': 50, 'Ir': 55, 'K': 60, 'Kr': 45, 'La': 40, 'Li': 40, 'Lr': 60, 'Lu': 45, 'Md': 60, 'Mg': 30, 'Mn': 65, 'Mo': 35, 'N': 60, 'Na': 40, 'Nb': 40, 'Nd': 40, 'Ne': 50, 'Ni': 45, 'No': 60, 'Np': 30, 'O': 60, 'Os': 40, 'P': 30, 'Pa': 30, 'Pb': 40, 'Pd': 45, 'Pm': 40, 'Po': 30, 'Pr': 40, 'Pt': 35, 'Pu': 30, 'Ra': 30, 'Rb': 30, 'Re': 30, 'Rh': 35, 'Rn': 30, 'Ru': 35, 'S': 35, 'Sb': 40, 'Sc': 40, 'Se': 30, 'Si': 30, 'Sm': 40, 'Sn': 60, 'Sr': 30, 'Ta': 45, 'Tb': 40, 'Tc': 30, 'Te': 30, 'Th': 30, 'Ti': 35, 'Tl': 50, 'Tm': 40, 'U': 30, 'V': 35, 'W': 30, 'Xe': 60, 'Y': 35, 'Yb': 40, 'Zn': 40, 'Zr': 30}

Wavefunction cutoffs in Ry, mirroring pseudo.PSEUDO of the packaged config.json so the fallback can never contradict the shipped table (a test asserts they are identical). New elements are taken from SSSP 1.3.0 PBE efficiency; the entries that predate it are left as they were.

htesp.htepc.CARD_RE = re.compile('^\\s*(ATOMIC_SPECIES|ATOMIC_POSITIONS|ATOMIC_VELOCITIES|ATOMIC_FORCES|K_POINTS|CELL_PARAMETERS|OCCUPATIONS|CONSTRAINTS|SOLVENTS|HUBBARD)\\b')

start of a QE “card” (everything that is not part of a namelist)

htesp.htepc.SYSTEM_KEY_RE = re.compile('^\\s*(nspin|ntyp|nat|starting_magnetization\\s*\\(\\s*\\d+\\s*\\))\\s*=')

&SYSTEM entries that are rebuilt when a magnetic input is written

htesp.htepc.read_lines(path)[source]

Return the lines of path with their trailing newline stripped.

htesp.htepc.write_lines(path, lines)[source]

Write lines (given without trailing newlines) to path.

htesp.htepc.section(lines, start, end)[source]

sed -n '/start/,/end/p' | sed '$d' without a shell.

Returns the lines from the first one containing start up to, but not including, the first following line containing end. An empty list is returned when start never appears.

htesp.htepc.bare_element(label)[source]

'Fe,spin=5' / 'Fe1' -> 'Fe'; anything else is returned as is.

htesp.htepc.remove_files(*paths)[source]

Delete each path that exists, quietly skipping the ones that do not.

htesp.htepc.pos_to_kpt(structure_filename, kpoint_density)[source]

Obtain k-point mesh from a structure file.

Parameters:

structure_filenamestr

Structure file (e.g., QE scf.in or VASP POSCAR).

kpoint_densityfloat

K-point density.

Returns:

kmeshlist

K-point mesh according to the k-point density.

class htesp.htepc.MpConnect[source]

Class for connecting to Materials Project (MP) via MP API, extracting properties, and preparing input files for Quantum Espresso (QE) calculations.

Parameters:

keystr, optional

MP API KEY. Use your own key. If not provided, it should be available in config.json or ../../config.json file.

Attributes:

proplist

List of available properties.

mpidstr

Materials ID.

compstr

Compound name.

datadict

Dictionary containing materials data.

prefixstr

Prefix for the compound.

ecutwfcfloat

Kinetic energy cutoff for wavefunction.

ecutrhofloat

Kinetic energy cutoff for charge density.

kptlist

K-point grid.

structureStructure

Structure object.

pseudo_dirstr

Path to pseudopotential files.

outdirstr

Directory for output files.

evenkpttuple

K-grid with an even number of points in all directions.

kpshiftlist

K-point grid shifts.

kptypestr

K-point grid type.

calcstr

Type of calculation.

smearfloat

Degauss value for smearing.

smear_typestr

Type of smearing.

etot_conv_thrfloat

Total energy convergence threshold.

forc_conv_thrfloat

Force convergence threshold.

conv_thrfloat

Convergence threshold.

dict_elementdict

Dictionary containing kinetic energy cutoffs for different elements.

comp_listlist

List of elements in the compound.

Example of using MpConnect class: >>> obj = MpConnect() # Initialize MpConnect object >>> obj.setting(‘mp-763’) # Set Materials ID to ‘mp-763’ >>> obj.getkpt() # Get k-points for the structure >>> obj.maxecut_sssp() # Calculate maximum recommended energy cutoff using SSSP >>> obj.setting_qeinput() # Set up Quantum Espresso input files based on the retrieved data

setting(comp)[source]

Initialize the process with a Materials ID.

Parameters:

compstr

Materials ID.

Returns:

compstr

Materials ID.

Notes:

This function initializes the process with a Materials ID. It retrieves the data related to the given ID from the Materials Project (MP) database, sets up necessary parameters, and prepares the structure for further calculations.

get_prop_list()[source]

Print the list of properties available when downloading the data.

Returns:

prop_listdict_keys

A list of keys representing the available properties.

Notes:

This function retrieves the list of properties available for download from the Materials Project (MP) database for the current Materials ID (mpid). It returns a list of keys that represent the available properties that can be downloaded and accessed for analysis or further processing.

download(filetype='cif')[source]

Download the structure file.

Parameters:

filetypestr, optional

File format for downloading. Default is ‘cif’.

Notes:

This function downloads the structure file for the current Materials ID (mpid) from the Materials Project (MP) database. It saves the file in the specified format, with the default format being CIF (‘.cif’). Other supported formats may be specified as needed.

property(name)[source]

Extract a particular property.

Parameters:

namestr

The name of the property available from the list obtained from the get_prop_list() function.

Returns:

value

The value of the specified property.

Notes:

This function extracts the value of a specific property identified by its name from the data retrieved for the current Materials ID (mpid). The property name should be one of the properties listed in the output of the get_prop_list() function.

getkpt(primitive=True)[source]

Compute k-points based on k-point density.

Parameters:

  • primitive (bool): use the primitive standard structure.

Returns:

  • kpt (list): the k-point grid.

  • kptype (str): the type of k-point grid.

  • kptshift (list): the shifts in the k-point grid, returns [0,0,0].

Notes:

This function computes the k-point grid based on a specified k-point density, defaulting to 0.05 if unspecified. It returns the k-point grid, type, and shifts.

getevenkpt()[source]

Make the k-point mesh even.

Returns:

evenkpttuple

K-grid with an even number of points in all directions.

Notes:

Ensures the generated k-point grid has even points in each dimension by incrementing odd components to the next even number. Returns the resulting even k-point grid as a tuple.

getecut_sssp(element)[source]

Obtain the kinetic energy cutoff for a specific element.

Parameters:

elementstr

The type of element for which the kinetic energy cutoff is required.

Returns:

float

Kinetic energy cutoff for the particular element.

Raises:

KeyError

When the element is in neither config['pseudo']['PSEUDO'] nor the module’s SSSP_EFFICIENCY table.

Notes:

Gets cutoff values for elements from config.json and falls back to the SSSP efficiency set for anything the configuration does not cover.

maxecut_sssp()[source]

Choose the maximum kinetic energy cutoff among elements in a compound.

Returns:

tuple

A tuple containing the maximum kinetic energy cutoff for waveFunction (ecutwfc) and the maximum kinetic energy cutoff for charge density (ecutrho).

Notes:

This function finds the maximum kinetic energy cutoff for compound elements, then returs the cutoffs for waveFunction and density.

maxecut_sssp_for_subs()[source]

Determine the maximum kinetic energy cutoff among elements in a compound during the substitution process.

Returns:

tuple

A tuple containing the maximum kinetic energy cutoff for waveFunction (ecutwfc) and the maximum kinetic energy cutoff for charge density (ecutrho).

Notes:

Similar to maxecut_sssp but for substitution process.

ecut_set(ecutwfc=50.0, ecutrho=400.0)[source]

Function to set kinetic energy cutoffs

get_properties(property_name)[source]

Function to extract multiple properties from MP. :param property_name: :type property_name: list of properties: Default: [‘material_id’]

Returns:

property_list

Return type:

list of properties extracted.

setting_qeinput(calculation='vc-relax', occupations='smearing', restart_mode='from_scratch', pseudo_dir='./', smearing=0.02, smearing_type='gauss', etot_conv_thr=1e-05, forc_conv_thr=0.0001, conv_thr=1e-16, ion_dynamics='bfgs', cell_dynamics='bfgs', magnetic=False, primitive=True)[source]

Function to create input file for QE ground-state calculations.

Parameters: - calculation (str): Type of calculation. Default: ‘vc-relax’. Other options are ‘relax’ (ionic only), ‘bands’ for band structure, ‘scf’ for SCF calculations. - occupations (str): Occupation. Default: ‘smearing’. Other options could be ‘tetrahedra’ and so on. - restart_mode (str): How to start the calculations. - pseudo_dir (str): Path to pseudopotential files. Default: ‘./’ (current directory). - smearing (float): Degauss value. Default: 0.02. - smearing_type (str): Type of smearing. Default: ‘gauss’. - etot_conv_thr, forc_conv_thr, conv_thr (float): Convergence parameters of QE calculations. - ion_dynamics, cell_dynamics (str): Algorithm to perform relaxation. Default: ‘bfgs’. - magnetic (logical): Magnetic flag if magnetic input need to be created - primitive (logical): if True, then use primitive structure

Returns: Creates input files in scf-mpid.in format inside scf_dir/.

htesp.htepc.reorder_dictionary(original_dict, new_order)[source]

Reorder the keys of a dictionary based on a new list of keywords and return the list of keys.

Parameters: - original_dict (dict): The original dictionary whose keys are to be reordered. - new_order (list): The new list of keywords specifying the desired order of keys.

Returns: - list: The list of keys of the reordered dictionary based on the new order.

Example: >>> original_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4} >>> new_order = [‘c’, ‘a’, ‘d’, ‘b’] >>> reorder_dictionary(original_dict, new_order)

htesp.htepc.extract_elements_with_spin(original_list)[source]

Extract elements with their spin values from the given list.

Parameters: - original_list (list): List containing strings representing elements with spin values.

Returns: - dict: A dictionary where keys are elements and values are lists of spin values.

htesp.htepc.parse_spin(label)[source]

The spin out of a species label such as 'Fe,spin=5'.

FIX(37): this was float(item.split('=')[-1]), which numpy 2 broke. Species.__str__ renders the spin with repr, and numpy 2 changed the repr of a scalar from 5.0 to np.float64(5.0) – so a structure decorated from config['magmom']['magmom'] (whose values arrive as numpy floats through pymatgen) produced 'Fe,spin=np.float64(5.0)' and mainprogram magenum died with

ValueError: could not convert string to float: ‘np.float64(5.0)’

Pull the first number out of whatever the label says instead of assuming the text after = is already a bare float. Returns 0.0 when the label carries no number at all.

htesp.htepc.convert_species_list(original_list)[source]

Rename elements in the original list with elements with different spins.

Parameters: - original_list (list): List containing strings representing elements.

Returns: - list: Updated list where elements are replaced with generic names for different spins.

Example: >>> original_list = [‘Fe,spin=5’, ‘Fe,spin=-5’, ‘pd’, ‘pd’, ‘I,spin=1’, ‘I,spin=-1’] >>> convert_species_list(original_list) [‘Fe1’, ‘Fe2’, ‘pd’, ‘pd’, ‘I1’, ‘I2’]

class htesp.htepc.INPUTscf(filename='scf.in')[source]

class to process QE input files :param filename: :type filename: (str) QE input file

scftocif(output='file.cif')[source]

Function to convert QE input file to structure file in .cif format :param output: :type output: (str) name of the output file

Returns:

file2

Return type:

output file object

cellpar()[source]

Function to calculate cell lengths and angles :rtype: list of lenghts and angles

standardize(mpid, output='standard.in')[source]

Function to get symmetrized structure. :param mpid: :type mpid: (str) materials project ID :param output: :type output: (str) output file. Default: ‘standard.in’

generate_kpath(nqpoint=200, kcut=0, out='kpath.in', qualifier='crystal')[source]

Function to generate and write k-point mesh for bandstructure calculation to a file :param nqpoint: :type nqpoint: (int) size of the k-point mesh. Default: 200 :param kcut: :type kcut: (int) cutoff to the high-symmetry path of the Brillouin zone. Default: 0 for full Brillouin zone :param out: :type out: (str) output file. Default: ‘kpath.in’ :param qualifier: htesp.kpath.printk(). Use ‘crystal_b’ for the segment form. :type qualifier: (str) K_POINTS unit. Default: ‘crystal’, matching

Returns:

  • kpts (numpy array of kpoints in linear axis after processing)

  • n ((int) size of kpts)

setting_input(comp, mass, qpoint)[source]

Function to setup input :param comp: :type comp: compound name :param mass: :type mass: List of masses of elements :param qpoint: :type qpoint: List of qpoint

create_elph(output='elph.in', tol=1e-14, sigma=0.005)[source]

Function similar to elph.py file inside src/

create_q2r(output='q2r.in')[source]

Function similar to q2r.py file inside src/

create_matdyn(out='matdyn.in', nqpt=60, kcut=0)[source]

Function similar to matdyn.py file inside src/

create_phdos(kpts, out='phdos.in', ndos=200)[source]

Function similar to matdyn_dos.py file inside src/

create_dos(out1='dos.in', out2='pdos.in')[source]

Function similar to dos.py file inside src/

post_band(out='band.in')[source]

Function similar to band.py file inside src/

post_phband(out='phonband.in')[source]

Function similar to phonband.py file inside src/

htesp.htepc.scf_to_dos_scf(input_file='scf.in', out='scf-dos.in')[source]

Function to change QE input file from using smearing to ‘tetrahedra’ method, mainly for DOS calculation

Parameters:
  • input_file ((str) input file for QE scf calculation)

  • out ((str) output file after modification)

htesp.htepc.insert(input_file='scf.in', output='scf-new.in', keyword=None, where='after', what='')[source]

Function to insert keyword in input file :param input_file: :type input_file: (str) input file. Default: ‘scf.in’ :param output: :type output: (str) output file. Default: ‘scf-new.in’ :param keyword: :type keyword: (str) keyword to look after :param where: :type where: (str) where to insert. Default: ‘after’, otherwise ‘before’ :param what: :type what: (str) what to insert. Default: ‘’

class htesp.htepc.OUTPUTscf(filename='scf.out')[source]

class to extract relax structure from QE output file and update input file :param filename: :type filename: (str) QE output file. Default: ‘scf.out’

extract_relax(output='relax.dat')[source]

Function to extract cell and positions of crystal structures from scf output file and write to a file :param output: :type output: (str) output file. Default: ‘relax.dat’

Return type:

list of the lines written (empty when the run produced no coordinates)

update_scf(input_file='scf.in', output='scf-new.in', what='structure')[source]

Function to update QE input file and update with new structure :param input_file: :type input_file: (str) QE scf input file to update. Default: ‘scf.in’ :param output: :type output: (str) QE scf output file, updated with new structure. Default: ‘scf-new.in’ :param what: :type what: (str) what to update. Default: ‘structure’. Other, not implemented yet !