diff --git a/abipy/abilab.py b/abipy/abilab.py index 08cf6db5f..ba66fdf5c 100644 --- a/abipy/abilab.py +++ b/abipy/abilab.py @@ -34,7 +34,7 @@ from abipy.core.func1d import Function1D from abipy.core.kpoints import set_atol_kdiff from abipy.abio.robots import Robot -from abipy.abio.inputs import AbinitInput, MultiDataset, AnaddbInput, OpticInput +from abipy.abio.inputs import AbinitInput, MultiDataset, AnaddbInput, OpticInput, AtdepInput from abipy.abio.abivars import AbinitInputFile from abipy.abio.outputs import AbinitLogFile, AbinitOutputFile, OutNcFile, AboRobot from abipy.tools.printing import print_dataframe diff --git a/abipy/abio/abivar_database/variables_atdep.py b/abipy/abio/abivar_database/variables_atdep.py new file mode 100644 index 000000000..92544777b --- /dev/null +++ b/abipy/abio/abivar_database/variables_atdep.py @@ -0,0 +1,583 @@ +# coding: utf-8 +from __future__ import print_function, division, unicode_literals, absolute_import + +try: + from abimkdocs.variables import ValueWithUnit, MultipleValue, Range +except ImportError: + # This is needed for importing this module within Abipy. + from abipy.abio.abivar_database.variables import ValueWithUnit, MultipleValue, Range + +executable = "atdep" + +ValueWithConditions = dict + +Variable=dict +variables = [ + +Variable( + abivarname="alloy@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_expert'], + dimensions="3", + defaultval="0", + mnemonics="ALLOY treatment", + added_in_version="9.5.1", + text=r""" +OPTIONAL: Defines the treatment of the alloy. The first value defines the approximation used (0=nothing and 1=Virtual Crystal Approximation). The second and the third values define the [[typat_unitcell] of the atoms which have to be alloyed. +""", +), + +Variable( + abivarname="amu@atdep", + varset="atdep", + vartype="real", + topics=['aTDEP_basic'], + dimensions=['[[atdep:ntypat]]'], + defaultval="[[atdep:ntypat]]*0.d0", + mnemonics="Atomic masses in Mass Units", + added_in_version="before_v9", + text=r""" +Defines the masses in atomic mass units for each kind of atom. See the ABINIT variable [[amu]] for more details. (Only required when the NetCDF file is absent). +""", +), + +Variable( + abivarname="angle@atdep", + varset="atdep", + vartype="real", + topics=['aTDEP_basic'], + dimensions="scalar", + defaultval="90.d0", + mnemonics="ANGLE alpha", + added_in_version="before_v9", + text=r""" +This angle has to be defined if the bravais lattice is monoclinic. That is to say if [[atdep:brav]](1)=2. +""", +), + +Variable( + abivarname="born_charge@atdep", + varset="atdep", + vartype="real", + topics=['aTDEP_expert'], + dimensions=['[[atdep:ntypat]]'], + defaultval="[[atdep:ntypat]]*0.d0", + mnemonics="BORN effective CHARGE", + added_in_version="before_v9", + text=r""" +OPTIONAL : Defines the Born effective charge (for each kind of atom) used to compute the dipole-dipole interaction. +""", +), + +Variable( + abivarname="brav@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_basic'], + dimensions=[2], + defaultval="2*0", + mnemonics="BRAVais", + added_in_version="before_v9", + text=""" +These two parameters define the Bravais lattice (as defined in the ABINIT code) and the primitive vectors [[rprim]] in the aTDEP code. + +- For bravais(1): The holohedral groups are numbered as follows (see international tables for crystallography (1983), p. 13): +iholohedry=1 triclinic 1bar +iholohedry=2 monoclinic 2/m +iholohedry=3 orthorhombic mmm +iholohedry=4 tetragonal 4/mmm +iholohedry=5 trigonal 3bar m +iholohedry=6 hexagonal 6/mmm +iholohedry=7 cubic m3bar m + +- For bravais(2): The centering is defined as follows: +center=0 no centering +center=-1 body-centered +center=-3 face-centered +center=1 A-face centered +center=2 B-face centered +center=3 C-face centered + +""", +), + +Variable( + abivarname="bzlength@atdep", + varset="atdep", + vartype="integer+real", + topics=['aTDEP_expert'], + dimensions="'[[atdep:bzlength]](1)'+1", + defaultval="0", + mnemonics="Brillouin Zone LENGTH", + added_in_version="before_v9", + text=r""" +OPTIONAL: Defines the length of the Brillouin Zone for the phonon spectrum calculation. The first value defines the number of segments used in the path. The other values define the size of each segment. +""", +), + +Variable( + abivarname="bzpath@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_expert'], + dimensions="1", + defaultval="0", + mnemonics="Brillouin Zone PATH", + added_in_version="before_v9", + text=r""" +OPTIONAL: Defines the number of special points used in the path in the Brillouin Zone for the phonon spectrum calculation. +""", +), + +Variable( + abivarname="special_qpt@atdep", + varset="atdep", + vartype="letter", + topics=['aTDEP_expert'], + dimensions="'[[atdep:bzpath]](1)'", + defaultval="0", + mnemonics="SPECIAL Q-PoinTs", + added_in_version="10.4", + text=r""" +OPTIONAL: Defines the path in the Brillouin Zone for the phonon spectrum calculation. +The values define the special points of the BZ (only the letters fixed by convention for the present lattice are allowed: L, X, M... and G for $\Gamma$). +""", +), + +Variable( + abivarname="dielec_constant@atdep", + varset="atdep", + vartype="real", + topics=['aTDEP_expert'], + dimensions="scalar", + defaultval="0", + mnemonics="DIELECtric CONSTANT", + added_in_version="before_v9", + text=""" +OPTIONAL: Defines the dielectric constant used to compute the dipole-dipole interaction. +""", +), + +Variable( + abivarname="dosdeltae@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_expert'], + dimensions="scalar", + defaultval="0.2 cm$^{-1}$", + mnemonics="DOS delta Energy", + added_in_version="before_v9", + text=""" +OPTIONAL: Defines the smearing used for the phonon Density Of State calculation. + +Prior to v9.10, the default was 4.5d-6. +""", +), + +Variable( + abivarname="enunit@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_expert'], + dimensions="scalar", + defaultval="0", + mnemonics="ENergy UNIT", + added_in_version="before_v9", + text=""" +OPTIONAL: Defines the energy unit used for the phonon spectrum (0 for meV, 1 for cm-1, 2 for Ha and 3 for THz). +""", +), + +Variable( + abivarname="multiplicity@atdep", + varset="atdep", + vartype="real", + topics=['aTDEP_basic'], + dimensions=[3,3], + defaultval="9*0.d0", + mnemonics="MULTIPLICITY", + added_in_version="before_v9", + text=r""" +Defines the multiplicity of the SUPERCELL with respect to the primitive UNICELL. See the ABINIT variables [[rprimd]], [[acell]] and [[rprim]] for more details. The multiplicity [[atdep:multiplicity]] and the SUPERCELL lattice parameters [[atdep:rprimd]] are used to find the UNITCELL lattice parameters acell_unitcell such as: + +$$ \text{rprimd}_{i,j}=\sum_{k=1}^3 \text{acell_unitcell}_i * \text{multiplicity}_{i,k}*\text{rprim_tmp}_{k,j} $$ + +For example: + +- for a fcc lattice: rprim = ( 0 1/2 1/2 ; 1/2 0 1/2 ; 1/2 1/2 0) and acell = (a a a). If the SUPERCELL is rprimd = (3a 0 0 ; 0 3a 0 ; 0 0 3a), the multiplicity = ( -3 3 3 ; 3 -3 3 ; 3 3 -3) +- for a bcc lattice: rprim = ( -1/2 1/2 1/2 ; 1/2 -1/2 1/2 ; 1/2 1/2 -1/2) and acell = (a a a). If the SUPERCELL is rprimd = (3a 0 0 ; 0 3a 0 ; 0 0 3a), the multiplicity = ( 0 3 3 ; 3 0 3 ; 3 3 0) +""", +), + +Variable( + abivarname="natom@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_basic'], + dimensions="scalar", + defaultval="0", + mnemonics="NATOM", + added_in_version="before_v9", + text=""" +Defines the number of atoms in the SUPERCELL. See the ABINIT variable [[natom]] for more details. (Only required when the NetCDF file is absent). +""", +), + +Variable( + abivarname="natom_unitcell@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_basic'], + dimensions="scalar", + defaultval="0", + mnemonics="NATOM in the UNITCELL", + added_in_version="before_v9", + text=""" +Defines the number of atoms in the UNITCELL. +""", +), + +Variable( + abivarname="ngqpt1@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_expert'], + dimensions=[3], + defaultval=[8, 8, 8], + mnemonics="Number of Grid points for Q PoinTs generation (coarse)", + added_in_version="before_v9", + text=r""" +OPTIONAL: Defines the COARSE grid of q-points for the dynamical matrix output (in DDB). +""", +), + +Variable( + abivarname="ngqpt2@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_expert'], + dimensions=[3], + defaultval=[32, 32, 32], + mnemonics="Number of Grid points for Q PoinTs generation (fine)", + added_in_version="before_v9", + text=""" +OPTIONAL: Defines the FINE grid of q-points for the DOS and thermodynamic quantity calculations. +""", +), + +Variable( + abivarname="nstep_max@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_basic'], + dimensions="scalar", + defaultval="0", + mnemonics="NSTEP at MAX", + added_in_version="before_v9", + text=""" +Defines the upper limit in the range of configurations that one wants to use. This number has to be lower than the maximum number of configurations present in the NetCDF or ASCII file. +""", +), + +Variable( + abivarname="nstep_min@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_basic'], + dimensions="scalar", + defaultval="0", + mnemonics="NSTEP at MIN", + added_in_version="before_v9", + text=""" +Defines the lower limit in the range of configurations that one wants to use. This number has to be larger than the minimum number of configurations present in the NetCDF or ASCII file. +""", +), + +Variable( + abivarname="ntypat@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_basic'], + dimensions="scalar", + defaultval="0", + mnemonics="NTYPAT", + added_in_version="before_v9", + text=""" +Defines the number of atom types. See the ABINIT variable [[ntypat]] for more details. (Only required when the NetCDF file is absent). +""", +), + +Variable( + abivarname="order@atdep", + varset="atdep", + vartype="integer+real", + topics=['aTDEP_expert'], + dimensions="2", + defaultval="2", + mnemonics="ORDER for the IFC", + added_in_version="before_v9", + text=""" +OPTIONAL: Defines at which order the calculation of the IFCs is performed. If the first value [[atdep:order]](1)=3, that turns on a third order calculation and the second value [[atdep:order]](2) defines the cutoff radius. +""", +), + +Variable( + abivarname="rcut@atdep", + varset="atdep", + vartype="real", + topics=['aTDEP_basic'], + dimensions="scalar", + defaultval="0.d0", + mnemonics="Radius CUToff", + added_in_version="before_v9", + text=""" +Defines the cutoff radius used when the second order IFCs are computed. This ones has to be lower than half the smallest SUPERCELL lattice parameter. +""", +), + +Variable( + abivarname="readifc@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_expert'], + dimensions="scalar", + defaultval="0", + mnemonics="READ the Interatomic Force Constants", + added_in_version="before_v9", + text=""" +OPTIONAL: Defines the IO strategy used for the IFC. If : + +- [[atdep:readifc]] = 1 : Read the IFC coming from an input file. +- [[atdep:readifc]] = 2 : Write and read the IFC coming from the calculation (for tests). +""", +), + +Variable( + abivarname="rprimd@atdep", + varset="atdep", + vartype="real", + topics=['aTDEP_basic'], + dimensions=[3,3], + defaultval="9*0.d0", + mnemonics="RPRIMD", + added_in_version="before_v9", + text=""" +Defines the dimensional real space primitive vectors of the SUPERCELL. See [[rprimd]] for more details. (Only required when the NetCDF file is absent). +""", +), + +Variable( + abivarname="slice@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_expert'], + dimensions="1", + defaultval="1", + mnemonics="SLICE", + added_in_version="before_v9", + text=""" +OPTIONAL: Defines the slice used to include some configurations in the calculations. Only the ([[atdep:nstep_max]]-[[atdep:nstep_min]])/[[atdep:slice]] configurations will be considered in the calculations of the IFCs. +""", +), + + +Variable( + abivarname="temperature@atdep", + varset="atdep", + vartype="real", + topics=['aTDEP_basic'], + dimensions="scalar", + defaultval="0", + mnemonics="TEMPERATURE", + added_in_version="before_v9", + text=""" +Defines the temperature of the system. +""", +), + +Variable( + abivarname="together@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_expert'], + dimensions="scalar", + defaultval="1", + mnemonics="Are the different orders solved TOGETHER?", + added_in_version="9.5.1", + text=""" +OPTIONAL: Defines if the different [[atdep:order]] are solved together or not : + +- simultaneously : [[atdep:together]] = 1. +- successively : [[atdep:together]] = 0. +""", +), + +Variable( + abivarname="typat@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_basic'], + dimensions=['[[atdep:natom]]'], + defaultval="[[atdep:natom]]*0", + mnemonics="TYPAT", + added_in_version="before_v9", + text=""" +Defines the type of atoms in the SUPERCELL. See [[typat]] for more details. (Only required when the NetCDF file is absent). +""", +), + +Variable( + abivarname="typat_unitcell@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_basic'], + dimensions=['[[atdep:natom_unitcell]]'], + defaultval="[[atdep:natom_unitcell]]*0", + mnemonics="TYPAT in the UNITCELL", + added_in_version="before_v9", + text=""" +Defines the type of atoms in the UNITCELL. +""", +), + +Variable( + abivarname="use_ideal_positions@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_expert'], + dimensions="scalar", + defaultval="1", + mnemonics="USE IDEAL POSITIONS", + added_in_version="before_v9", + text=""" +OPTIONAL: Defines if the ideal ([[atdep:use_ideal_positions]]=1) or averaged ([[atdep:use_ideal_positions]]=0) positions are used during the calculations. It can affect strongly the phonon spectrum (and other quantities) if the system is close to an instability (soft mode,...). +""", +), + +Variable( + abivarname="use_weights@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_expert'], + dimensions="scalar", + defaultval="0", + mnemonics="USE the WEIGHTS", + added_in_version="9.5.1", + text=""" +OPTIONAL: Defines if a specific weight has to be used for each configuration ([[atdep:use_weights]]=1). +""", +), + +Variable( + abivarname="xred_unitcell@atdep", + varset="atdep", + vartype="real", + topics=['aTDEP_basic'], + dimensions=[3, '[[atdep:natom_unitcell]]'], + defaultval="(3*[[atdep:natom_unitcell]])*0.d0", + mnemonics="XRED in the UNITCELL", + added_in_version="before_v9", + text=""" +Defines the reduced coordinates of atoms in the UNITCELL. +""", +), + +Variable( + abivarname="znucl@atdep", + varset="atdep", + vartype="float", + topics=['aTDEP_basic'], + dimensions=['[[atdep:natom]]'], + defaultval="[[atdep:natom]]*0", + mnemonics="charge -Z- of the NUCLeus", + added_in_version="10.4", + text=""" +OPTIONAL: Gives nuclear charge for each type of atom, in order. +Within atep, this variable is only used when writing the DDB file. +""", +), + +Variable( + abivarname="debug_mode@atdep", + varset="atdep", + vartype="integer", + topics=['aTDEP_expert'], + dimensions="scalar", + defaultval="0", + mnemonics="DEBUG MODE", + added_in_version="10.4", + text=""" +OPTIONAL: A non-zero value activates debug mode for atdep. +""", +), + + +Variable( + abivarname="output_file@atdep", + varset="atdep", + vartype="string", + topics=['Control_useful'], + dimensions="scalar", + defaultval="", + mnemonics="OUTPUT FILE", + added_in_version="10.4", + text=r""" +This variable specifies the name of the output file when atdep is invoked with the new syntax: + + atdep run.in > run.log 2> run.err + +instead of the legacy mode based on the files file. Example: + + output_file = "run.out" +""", +), + +Variable( + abivarname="indata_prefix@atdep", + varset="atdep", + vartype="string", + topics=['Control_useful'], + dimensions="scalar", + defaultval="", + mnemonics="INput DATA PREFIX", + added_in_version="10.4", + text=r""" +Prefix for input files, in particular for the HIST.nc file. +This variable is used when atdep is executed with the new syntax: + + atdep run.abi > run.log 2> run.err & + +instead of the legacy mode based on the files file. Example: + + indata_prefix = "in" + +which tells atdep to look for a file called "in_HIST.nc". +""" +), + +Variable( + abivarname="outdata_prefix@atdep", + varset="atdep", + vartype="string", + topics=['Control_useful'], + dimensions="scalar", + defaultval="atdep", + mnemonics="OUTput DATA PREFIX", + added_in_version="10.4", + text=r""" +Prefix for output files. +This variable is used when atdep is executed with the new syntax: + + atdep run.abi > run.log 2> run.err & + +instead of the legacy mode based on the files file. Example: + + outdata_prefix = "run" + +which tells atdep to construct output file names like "run_DDB". +""" +), + + +] diff --git a/abipy/abio/abivars.py b/abipy/abio/abivars.py index cb3f7def1..80e01ecbf 100644 --- a/abipy/abio/abivars.py +++ b/abipy/abio/abivars.py @@ -17,6 +17,8 @@ __all__ = [ "is_abivar", + "is_anaddb_var", + "is_atdep_var", "is_abiunit", "AbinitInputFile", "AbinitInputParser", @@ -28,6 +30,9 @@ def is_anaddb_var(varname: str) -> bool: """True if varname is a valid Anaddb variable.""" return varname in get_codevars()["anaddb"] +def is_atdep_var(varname: str) -> bool: + """True if varname is a valid atdep variable.""" + return varname in get_codevars()["atdep"] def is_abivar(varname: str) -> bool: """True if s is an ABINIT variable.""" diff --git a/abipy/abio/abivars_db.py b/abipy/abio/abivars_db.py index 10e9256a0..a3507f6d2 100644 --- a/abipy/abio/abivars_db.py +++ b/abipy/abio/abivars_db.py @@ -22,6 +22,12 @@ def get_anaddb_variables(): return get_codevars()["anaddb"] +def get_atdep_variables(): + """Returns the database with the description of the ATDEP variables.""" + from abipy.abio.abivar_database.variables import get_codevars + return get_codevars()["atdep"] + + def docvar(varname, executable="abinit"): """Return the `Variable` object associated to this name.""" from abipy.abio.abivar_database.variables import get_codevars diff --git a/abipy/abio/inputs.py b/abipy/abio/inputs.py index a059c0afc..fb937810c 100644 --- a/abipy/abio/inputs.py +++ b/abipy/abio/inputs.py @@ -31,8 +31,8 @@ from abipy.core.kpoints import has_timrev_from_kptopt from abipy.tools.serialization import pmg_serialize from abipy.abio.variable import InputVariable -from abipy.abio.abivars import is_abivar, is_anaddb_var, format_string_abivars -from abipy.abio.abivars_db import get_abinit_variables, get_anaddb_variables +from abipy.abio.abivars import is_abivar, is_anaddb_var, is_atdep_var, format_string_abivars +from abipy.abio.abivars_db import get_abinit_variables, get_anaddb_variables, get_atdep_variables from abipy.tools import duck from abipy.flowtk import PseudoTable, Pseudo, AbinitTask, AnaddbTask, ParalHintsParser, NetcdfReader from abipy.flowtk.abiinspect import yaml_read_irred_perts @@ -4753,6 +4753,250 @@ def from_dict(cls, d: dict) -> Cut3DInput: options=d.get('options', None)) +class AtdepInputError(Exception): + """Error class raised by AtdepInput.""" + + +class AtdepInput(AbiAbstractInput, MSONable, Has_Structure): + """ + This object stores the anaddb variables. + + .. rubric:: Inheritance Diagram + .. inheritance-diagram:: AnaddbInput + """ + + Error = AtdepInputError + + @pmg_serialize + def as_dict(self) -> dict: + """ + JSON interface used in pymatgen for easier serialization. + """ + atdep_args = [] + for key, value in self.items(): + if isinstance(value, np.ndarray): value = value.tolist() + atdep_args.append((key, value)) + + return dict(structure=self.structure.as_dict(), + comment=self.comment, + atdep_args=atdep_args, + spell_check=self.spell_check, + ) + + @classmethod + def from_dict(cls, d: dict) -> AtdepInput: + """ + JSON interface used in pymatgen for easier serialization. + """ + return cls(d["structure"], + comment=d["comment"], + atdep_args=d["atdep_args"], + spell_check=d["spell_check"], + ) + + def __init__(self, + structure: Structure, + comment: str = "", + atdep_args=None, + atdep_kwargs=None, + spell_check: bool = False): + + """ + Args: + structure: |Structure| object + comment: Optional string with a comment that will be placed at the beginning of the file. + atdep_args: List of tuples (key, value) with atdep input variables (default: empty) + atdep_kwargs: Dictionary with atdep input variables (default: empty) + spell_check: False to disable spell checking for input variables. + """ + self.set_spell_check(spell_check) + self._structure = Structure.as_structure(structure) + self.comment = "" if comment is None else str(comment) + + atdep_args = [] if atdep_args is None else atdep_args + for key, value in atdep_args: + self._check_varname(key) + + atdep_kwargs = {} if atdep_kwargs is None else atdep_kwargs + for key in atdep_kwargs: + self._check_varname(key) + + args = list(atdep_args)[:] + args.extend(list(atdep_kwargs.items())) + + self._vars = OrderedDict(args) + + @property + def vars(self) -> dict: + return self._vars + + def set_spell_check(self, false_or_true: bool) -> None: + """Activate/Deactivate spell-checking""" + self._spell_check = bool(false_or_true) + + @property + def spell_check(self) -> bool: + """True if spell checking is activated.""" + try: + return self._spell_check + except AttributeError: # This is to maintain compatibility with pickle + return False + + def _check_varname(self, key: str) -> None: + if self.spell_check: + if not is_atdep_var(key): + raise self.Error(""" +Cannot find variable `%s` in the internal database. If you think this is not a typo, use: + + input.set_spell_check(False) + +to disable spell checking. Perhaps the internal database is not in synch +with the Abinit version you are using. Please contact the AbiPy developers.""" % key) + + @property + def structure(self) -> Structure: + """|Structure| object.""" + return self._structure + + @staticmethod + def get_atdep_brav(structure): + """ + Get the two integers defining the bravais lattice + according to the 'brav' variable from atdep. + """ + from pymatgen.symmetry.analyzer import SpacegroupAnalyzer + spa = SpacegroupAnalyzer(structure) + family = spa.get_crystal_system() + + symbol = spa.get_space_group_symbol() + n = spa.get_space_group_number() + + if 0 < n < 3: + # triclinic + iholohedry = 1 + if n < 16: + # monoclinic + iholohedry = 2 + #icentering = 0 + if n < 75: + # orthorhombic + iholohedry = 3 + if n < 143: + # tetragonal + iholohedry = 4 + if n < 168: + # trigonal + iholohedry = 5 + if n < 195: + # hexagonal + iholohedry = 6 + else: + # cubic + iholohedry = 7 + + if symbol.startswith('P'): + # No centering + icentering = 0 + elif symbol.startswith('I'): + # Body centered + icentering = -1 + elif symbol.startswith('F'): + # Face centered + icentering = -3 + elif symbol.startswith('A'): + # A-face centered + icentering = 1 + elif symbol.startswith('C'): + # B-face centered + icentering = 3 + else: + # Rhombrohedral + icentering = 0 + + return [iholohedry, icentering] + + _unitcell_keys = ['brav', 'natom_unitcell', + 'xred_unitcell', 'typat_unitcell'] + _supercell_keys = ['multiplicity'] + _computational_details_keys = ['nstep_max', 'nstep_min', + 'rcut', 'temperature'] + _mandatory_keys = ( + _unitcell_keys + _supercell_keys + _computational_details_keys) + + def has_mandatory_variables(self): + """True if all mandatory variables been specified.""" + for key in self._supercell_keys + self._computational_details_keys: + if key not in self.vars: + return False + return True + + def to_string(self, mode="text", verbose=0) -> str: + """ + String representation. + + Args: + sortmode: "a" for alphabetical order, None if no sorting is wanted + mode: Either `text` or `html` if HTML output with links is wanted. + """ + lines = [] + app = lines.append + + if mode == "html": + var_database = get_atdep_variables() + + def addvars(keys): + for vname in keys: + value = self[vname] + if mode == "html": + vname = var_database[vname].html_link(label=vname) + value = format_string_abivars(vname, value) + + try: + app(str(InputVariable(vname, value))) + except Exception as exc: + cprint(f"{vname=}, {value=}", color="red") + raise exc + + optional_keys = [] + for key in self.vars.keys(): + if key not in self._mandatory_keys: + optional_keys.append(key) + + structure_abivars = self.structure.to_abivars() + self['brav'] = self.get_atdep_brav(self.structure) + self['natom_unitcell'] = structure_abivars['natom'] + self['xred_unitcell'] = structure_abivars['xred'] + self['typat_unitcell'] = structure_abivars['typat'] + + app('#DEFINE_UNITCELL') + addvars(self._unitcell_keys) + app('') + app('#DEFINE_SUPERCELL') + addvars(self._supercell_keys) + app('') + app('#DEFINE_COMPUTATIONAL_DETAILS') + addvars(self._computational_details_keys) + app('') + app('#OPTIONAL_INPUT_VARIABLES') + addvars(optional_keys) + app('') + + if self.comment: + app("# " + self.comment.replace("\n", "\n#")) + + if mode == "text": + return "\n".join(lines) + else: + return "\n".join(lines).replace("\n", "
") + + def _repr_html_(self) -> str: + """Integration with jupyter_ notebooks.""" + return self.to_string(mode="html") + + def abivalidate(self, workdir=None, manager=None): + pass + + def product_dict(d: dict): """ This function receives a dictionary d where each key defines a list of items or a simple scalar. diff --git a/abipy/flowtk/flows.py b/abipy/flowtk/flows.py index 932948c07..05b366fb2 100644 --- a/abipy/flowtk/flows.py +++ b/abipy/flowtk/flows.py @@ -2021,13 +2021,13 @@ def pickle_dumps(self, protocol=None): protocol=self.pickle_protocol if protocol is None else protocol) return strio.getvalue() - def register_task(self, input: AbinitInput, + def register_task(self, input: AbinitInput | Task, deps=None, manager=None, task_class=None, append=False) -> Work: """ Utility function that generates a `Work` made of a single task Args: - input: |AbinitInput| + input: |AbinitInput| instance or |Task| object. deps: List of :class:`Dependency` objects specifying the dependency of this node. An empy list of deps implies that this node has no dependencies. manager: The |TaskManager| responsible for the submission of the task. diff --git a/abipy/flowtk/tasks.py b/abipy/flowtk/tasks.py index 117a4cb5a..bddc2aa47 100644 --- a/abipy/flowtk/tasks.py +++ b/abipy/flowtk/tasks.py @@ -67,6 +67,7 @@ "OpticTask", "AnaddbTask", "GwrTask", + "AtdepTask", "set_user_config_taskmanager", ] @@ -5005,3 +5006,80 @@ def make_input(self, with_header=False) -> str: # self.restart() # # return results + + +class AtdepTask(Task): + """ + Task for atdep runs: computation of + temperature-dependent effective potentials (TDEP) + for anharmonic phonons, using a HIST file from MD. + """ + + color_rgb = np.array((55, 70, 100)) / 255 + + # ========================== CODING LINE ================================ # + + def __init__(self, atdep_input, hist_node, workdir=None, manager=None): + """ + Create an instance of AtdepTask from a string containing the input. + + Args: + atdep_input: |AtdepInput| object. + hist_node: The node that will produce the HIST file. + Accept |Task|, |Work| or filepath. + workdir: Path to the working directory (optional). + manager: |TaskManager| object (optional). + """ + # Keep a reference to the nodes. + self.hist_node = Node.as_node(hist_node) + deps = {self.hist_node: "HIST"} + + super().__init__(input=atdep_input, workdir=workdir, + manager=manager, deps=deps) + + @property + def executable(self) -> str: + """Path to the executable required for running the |AtdepTask|.""" + try: + return self._executable + except AttributeError: + return "atdep" + + @property + def hist_filepath(self) -> str: + """Returns (at runtime) the absolute path of the input HIST file.""" + if isinstance(self.hist_node, FileNode): return self.hist_node.filepath + path = self.hist_node.outdir.has_abiext("HIST.nc") + return path if path else None + + def setup(self): + """Public method called before submitting the task.""" + pass + + def make_links(self): + self.inlink_file(self.hist_filepath) + + def outpath_from_ext(self, ext): + path = self.outdir.has_abiext(ext) + if not path: + raise RuntimeError("Atdep task `%s` didn't produce file with extension: `%s`" % (self, ext)) + return path + + def open_ddb(self): + """Open DDB file produced by atdep and returns |DdbFile| object.""" + from abipy.dfpt.ddb import DdbFile + ddb_path = self.outpath_from_ext("DDB") + return DdbFile(s_path) + + def make_input(self, with_header=False) -> str: + """return string the input file of the calculation.""" + inp = self.input.deepcopy() + + inp['output_file'] = str(self.output_file.path) + inp['indata_prefix'] = self.indir.path_in('in') + inp['outdata_prefix'] = self.outdir.path_in('out') + + s = str(inp) + if with_header: s = str(self) + "\n" + s + return s + diff --git a/abipy/flowtk/utils.py b/abipy/flowtk/utils.py index 55090f635..c6585df88 100644 --- a/abipy/flowtk/utils.py +++ b/abipy/flowtk/utils.py @@ -516,6 +516,7 @@ def find_1den_files(self): #"DKDE": {"getdkde": 1}, #"DELFD": {"getdelfd": 1}, "GSTORE": {"getgstore_filepath": '"indata/in_GSTORE.nc"'}, + "HIST": {}, }