abio Package

abio Package

This sub-package provides objects and methods to generate Input files.

abivars Module

This module contains lookup table with the name of the ABINIT variables.

abipy.abio.abivars.is_abivar(varname)[source]

True if s is an ABINIT variable.

abipy.abio.abivars.is_abiunit(s)[source]

True if string is one of the units supported by the ABINIT parser

class abipy.abio.abivars.AbinitInputFile(filepath)[source]

Bases: abipy.core.mixins.TextFile, abipy.core.mixins.Has_Structure, abipy.core.mixins.NotebookWriter

This object parses the Abinit input file, stores the variables in dict-like objects (Datasets) and build Structure objects from the input variables. Mainly used for inspecting the structure declared in the Abinit input file.

classmethod from_string(string)[source]

Build the object from string.

to_string(verbose=0)[source]

String representation.

has_multi_structures[source]

True if input defines multiple structures.

close()[source]

NOP, required by ABC.

structure[source]

The structure defined in the input file.

If the input file contains multiple datasets AND the datasets have different structures, this property returns None. In this case, one has to access the structure of the individual datasets. For example:

input.datasets[0].structure

gives the structure of the first dataset.

yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user.

write_notebook(nbpath=None)[source]

Write an ipython notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook.

class abipy.abio.abivars.AbinitInputParser[source]

Bases: object

verbose = 0
parse(s)[source]

This function receives a string s with the Abinit input and return a list of Dataset objects.

static eval_abinit_operators(tokens)[source]

Receive a list of strings, find the occurences of operators supported in the input file (e.g. sqrt), evalute the expression and return new list of strings.

static varname_dtindex(tok)[source]
>>> p = AbinitInputParser()
>>> assert p.varname_dtindex("acell1") == ("acell", 1)
>>> assert p.varname_dtindex("fa1k2") == ("fa1k", 2)

abivars_db Module

Database with the names of the input variables used in Abinit and in other main programs.

abipy.abio.abivars_db.get_abinit_variables()[source]

Returns the database with the description of the ABINIT variables.

abipy.abio.abivars_db.get_anaddb_variables()[source]

Returns the database with the description of the ANADDB variables.

abipy.abio.abivars_db.docvar(varname, executable='abinit')[source]

Return the Variable object associated to this name.

abipy.abio.abivars_db.abinit_help(varname, info=True, stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Print the abinit documentation on the ABINIT input variable varname

abipy.abio.abivars_db.repr_html_from_abinit_string(text)[source]

Given a string text with an Abinit input file, replace all variables with HTML links pointing to the official documentation. Return new string.

decorators Module

Decorators for AbinitInput or MultiDataset objects.

exception abipy.abio.decorators.InputDecoratorError[source]

Bases: Exception

Error class raised by AbinitInputDecorator.

class abipy.abio.decorators.AbinitInputDecorator[source]

Bases: monty.json.MSONable

An AbinitInputDecorator adds new options to an existing AbinitInput or an existing MultiDataset without altering its structure. This is an abstract Base class.

Example

decorator = MyDecorator(arguments)

new_abinit_input = decorator(abinit_input) new_multidataset = decorator(multidataset)

Note that a decorator does not modify the object on which it acts.

Warning

Please avoid introducing decorators acting on the structure (in particular the lattice) since the initial input may use the initial structure to compute important variables. For instance, the list of k-points for band structure calculation depend on the bravais lattice and a decorator that changes it should recompute the path. This should not represent a serious limitation because it’s always possible to change the structure with its methods and then call the factory function without having to decorate an already existing object.

Error

alias of InputDecoratorError

class abipy.abio.decorators.SpinDecorator(spinmode, kptopt_ifspinor=4)[source]

Bases: abipy.abio.decorators.AbinitInputDecorator

This decorator changes the spin polarization.

as_dict()[source]

A JSON serializable dict representation of an object.

classmethod from_dict(d)[source]
Parameters

d – Dict representation.

Returns

MSONable class.

class abipy.abio.decorators.SmearingDecorator(smearing)[source]

Bases: abipy.abio.decorators.AbinitInputDecorator

This decorator changes the electronic smearing.

as_dict()[source]

A JSON serializable dict representation of an object.

classmethod from_dict(d)[source]
Parameters

d – Dict representation.

Returns

MSONable class.

class abipy.abio.decorators.XcDecorator(ixc)[source]

Bases: abipy.abio.decorators.AbinitInputDecorator

Change the exchange-correlation functional.

as_dict()[source]

A JSON serializable dict representation of an object.

classmethod from_dict(d)[source]
Parameters

d – Dict representation.

Returns

MSONable class.

class abipy.abio.decorators.LdaUDecorator(symbols_luj, usepawu=1, unit='eV')[source]

Bases: abipy.abio.decorators.AbinitInputDecorator

This decorator adds LDA+U parameters to an AbinitInput object.

as_dict()[source]

A JSON serializable dict representation of an object.

classmethod from_dict(d)[source]
Parameters

d – Dict representation.

Returns

MSONable class.

class abipy.abio.decorators.LexxDecorator(symbols_lexx, exchmix=None)[source]

Bases: abipy.abio.decorators.AbinitInputDecorator

This decorator add local exact exchange to an AbinitInput object.

classmethod from_dict(d)[source]
Parameters

d – Dict representation.

Returns

MSONable class.

as_dict()[source]

A JSON serializable dict representation of an object.

factories Module

Factory functions for Abinit input files

abipy.abio.factories.gs_input(structure, pseudos, kppa=None, ecut=None, pawecutdg=None, scf_nband=None, accuracy='normal', spin_mode='polarized', smearing='fermi_dirac:0.1 eV', charge=0.0, scf_algorithm=None)[source]

Returns a abipy.abio.inputs.AbinitInput for ground-state calculation.

Parameters
  • structureabipy.core.structure.Structure object.

  • pseudos – List of filenames or list of pymatgen.io.abinit.pseudos.Pseudo objects or pymatgen.io.abinit.pseudos.PseudoTable object.

  • kppa – Defines the sampling used for the SCF run. Defaults to 1000 if not given.

  • ecut – cutoff energy in Ha (if None, ecut is initialized from the pseudos according to accuracy)

  • pawecutdg – cutoff energy in Ha for PAW double-grid (if None, pawecutdg is initialized from the pseudos according to accuracy)

  • scf_nband – Number of bands for SCF run. If scf_nband is None, nband is automatically initialized from the list of pseudos, the structure and the smearing option.

  • accuracy – Accuracy of the calculation.

  • spin_mode – Spin polarization.

  • smearing – Smearing technique.

  • charge – Electronic charge added to the unit cell.

  • scf_algorithm – Algorithm used for solving of the SCF cycle.

abipy.abio.factories.ebands_input(structure, pseudos, kppa=None, nscf_nband=None, ndivsm=15, ecut=None, pawecutdg=None, scf_nband=None, accuracy='normal', spin_mode='polarized', smearing='fermi_dirac:0.1 eV', charge=0.0, scf_algorithm=None, dos_kppa=None)[source]

Returns a abipy.abio.inputs.MultiDataset object for band structure calculations.

Parameters
  • structureabipy.core.structure.Structure object.

  • pseudos – List of filenames or list of pymatgen.io.abinit.pseudos.Pseudo objects or pymatgen.io.abinit.pseudos.PseudoTable object.

  • kppa – Defines the sampling used for the SCF run. Defaults to 1000 if not given.

  • nscf_nband – Number of bands included in the NSCF run. Set to scf_nband + 10 if None.

  • ndivsm – Number of divisions used to sample the smallest segment of the k-path. if 0, only the GS input is returned in multi[0].

  • ecut – cutoff energy in Ha (if None, ecut is initialized from the pseudos according to accuracy)

  • pawecutdg – cutoff energy in Ha for PAW double-grid (if None, pawecutdg is initialized from the pseudos according to accuracy)

  • scf_nband – Number of bands for SCF run. If scf_nband is None, nband is automatically initialized from the list of pseudos, the structure and the smearing option.

  • accuracy – Accuracy of the calculation.

  • spin_mode – Spin polarization.

  • smearing – Smearing technique.

  • charge – Electronic charge added to the unit cell.

  • scf_algorithm – Algorithm used for solving of the SCF cycle.

  • dos_kppa – Scalar or List of integers with the number of k-points per atom to be used for the computation of the DOS (None if DOS is not wanted).

abipy.abio.factories.ion_ioncell_relax_input(structure, pseudos, kppa=None, nband=None, ecut=None, pawecutdg=None, accuracy='normal', spin_mode='polarized', smearing='fermi_dirac:0.1 eV', charge=0.0, scf_algorithm=None, shift_mode='Monkhorst-pack')[source]

Returns a abipy.abio.inputs.MultiDataset for a structural relaxation. The first dataset optmizes the atomic positions at fixed unit cell. The second datasets optimizes both ions and unit cell parameters.

Parameters
  • structureabipy.core.structure.Structure object.

  • pseudos – List of filenames or list of pymatgen.io.abinit.pseudos.Pseudo objects or pymatgen.io.abinit.pseudos.PseudoTable object.

  • kppa – Defines the sampling used for the Brillouin zone.

  • nband – Number of bands included in the SCF run.

  • accuracy – Accuracy of the calculation.

  • spin_mode – Spin polarization.

  • smearing – Smearing technique.

  • charge – Electronic charge added to the unit cell.

  • scf_algorithm – Algorithm used for the solution of the SCF cycle.

abipy.abio.factories.ion_ioncell_relax_and_ebands_input(structure, pseudos, kppa=None, nband=None, ecut=None, pawecutdg=None, accuracy='normal', spin_mode='polarized', smearing='fermi_dirac:0.1 eV', charge=0.0, scf_algorithm=None)[source]

Returns a abipy.abio.inputs.MultiDataset for a structural relaxation followed by a band structure run. The first dataset optimizes the atomic positions at fixed unit cell. The second datasets optimizes both ions and unit cell parameters. The other datasets perform a band structure calculation.

Warning

Client code is responsible for propagating the relaxed structure obtained with the second dataset to the inputs used for the band structure calculation.

Parameters
  • structureabipy.core.structure.Structure object.

  • pseudos – List of filenames or list of pymatgen.io.abinit.pseudos.Pseudo objects or pymatgen.io.abinit.pseudos.PseudoTable object.

  • kppa – Defines the sampling used for the Brillouin zone.

  • nband – Number of bands included in the SCF run.

  • accuracy – Accuracy of the calculation.

  • spin_mode – Spin polarization.

  • smearing – Smearing technique.

  • charge – Electronic charge added to the unit cell.

  • scf_algorithm – Algorithm used for solving of the SCF cycle.

Returns: abipy.abio.inputs.MultiDataset object

abipy.abio.factories.g0w0_with_ppmodel_inputs(structure, pseudos, kppa, nscf_nband, ecuteps, ecutsigx, ecut=None, pawecutdg=None, shifts=(0.0, 0.0, 0.0), accuracy='normal', spin_mode='polarized', smearing='fermi_dirac:0.1 eV', ppmodel='godby', charge=0.0, scf_algorithm=None, inclvkb=2, scr_nband=None, sigma_nband=None, gw_qprange=1)[source]

Returns a abipy.abio.inputs.MultiDataset object that performs G0W0 calculations with the plasmon pole approximation.

Parameters
  • structureabipy.core.structure.Structure object.

  • pseudos – List of filenames or list of pymatgen.io.abinit.pseudos.Pseudo objects or pymatgen.io.abinit.pseudos.PseudoTable object.

  • kppa – Defines the sampling used for the SCF run.

  • nscf_nband – Number of bands included in the NSCF run.

  • ecuteps – Cutoff energy [Ha] for the screening matrix.

  • ecutsigx – Cutoff energy [Ha] for the exchange part of the self-energy.

  • ecut – cutoff energy in Ha (if None, ecut is initialized from the pseudos according to accuracy)

  • pawecutdg – cutoff energy in Ha for PAW double-grid (if None, pawecutdg is initialized from the pseudos according to accuracy)

  • shifts – Shifts for k-mesh.

  • accuracy – Accuracy of the calculation.

  • spin_mode – Spin polarization.

  • smearing – Smearing technique.

  • ppmodel – Plasmonpole technique.

  • charge – Electronic charge added to the unit cell.

  • scf_algorithm – Algorithm used for solving of the SCF cycle.

  • inclvkb – Treatment of the dipole matrix elements (see abinit variable).

  • scr_nband – Number of bands used to compute the screening (default is nscf_nband)

  • sigma_nband – Number of bands used to compute the self-energy (default is nscf_nband)

  • gw_qprange – Option for the automatic selection of k-points and bands for GW corrections. See Abinit docs for more detail. The default value makes the code compute the QP energies for all the point in the IBZ and one band above and one band below the Fermi level.

abipy.abio.factories.g0w0_convergence_inputs(structure, pseudos, kppa, nscf_nband, ecuteps, ecutsigx, scf_nband, ecut, accuracy='normal', spin_mode='polarized', smearing='fermi_dirac:0.1 eV', response_models=None, charge=0.0, scf_algorithm=None, inclvkb=2, gw_qprange=1, gamma=True, nksmall=None, extra_abivars=None)[source]

Returns a abipy.abio.inputs.MultiDataset object to generate a G0W0 work for the given the material. See also [Setten2017].

Parameters
  • structureabipy.core.structure.Structure object

  • pseudos – List of pymatgen.io.abinit.pseudos.Pseudo objects.

  • kppa – k points per reciprocal atom.

  • scf_nband – number of scf bands

  • ecut – ecut for all calcs that that are not ecut convergence cals at scf level

  • Defines the sampling used for the SCF run. (scf) –

  • nscf_nband – a list of number of bands included in the screening and sigmaruns. The NSCF run will be done with the maximum.

  • ecuteps – list of Cutoff energy [Ha] for the screening matrix.

  • ecutsigx – Cutoff energy [Ha] for the exchange part of the self-energy.

  • accuracy – Accuracy of the calculation.

  • spin_mode – Spin polarization.

  • smearing – Smearing technique.

  • charge – Electronic charge added to the unit cell.

  • scf_algorithm – Algorithm used for solving of the SCF cycle.

  • inclvkb – Treatment of the dipole matrix elements (see abinit variable).

  • response_models – List of response models

  • gw_qprange – selectpr for the qpoint mesh

  • gamma – is true a gamma centered mesh is enforced

  • nksmall – Kpoint division for additional band and dos calculations

  • extra_abivars – Dictionary with extra variables passed to ABINIT for all tasks.

extra abivars that are provided with _s appended will be take as a list of values to be tested a scf level

abipy.abio.factories.bse_with_mdf_inputs(structure, pseudos, scf_kppa, nscf_nband, nscf_ngkpt, nscf_shiftk, ecuteps, bs_loband, bs_nband, mbpt_sciss, mdf_epsinf, ecut=None, pawecutdg=None, exc_type='TDA', bs_algo='haydock', accuracy='normal', spin_mode='polarized', smearing='fermi_dirac:0.1 eV', charge=0.0, scf_algorithm=None)[source]

Returns a abipy.abio.inputs.MultiDataset object that performs a GS + NSCF + Bethe-Salpeter calculation. The self-energy corrections are approximated with the scissors operator. The screening is modeled with the model dielectric function.

Parameters
  • structureabipy.core.structure.Structure object.

  • pseudos – List of filenames or list of pymatgen.io.abinit.pseudos.Pseudo objects or pymatgen.io.abinit.pseudos.PseudoTable object.

  • scf_kppa – Defines the sampling used for the SCF run.

  • nscf_nband – Number of bands included in the NSCF run.

  • nscf_ngkpt – Divisions of the k-mesh used for the NSCF and the BSE run.

  • nscf_shiftk – Shifts used for the NSCF and the BSE run.

  • ecuteps – Cutoff energy [Ha] for the screening matrix.

  • bs_loband – Index of the first occupied band included the e-h basis set (ABINIT convention i.e. first band starts at 1). Can be scalar or array of shape (nsppol,)

  • bs_nband – Highest band idex used for the construction of the e-h basis set.

  • mbpt_sciss – Scissor energy in Hartree.

  • mdf_epsinf – Value of the macroscopic dielectric function used in expression for the model dielectric function.

  • ecut – cutoff energy in Ha (if None, ecut is initialized from the pseudos according to accuracy)

  • pawecutdg – cutoff energy in Ha for PAW double-grid (if None, pawecutdg is initialized from the pseudos according to accuracy)

  • exc_type – Approximation used for the BSE Hamiltonian (Tamm-Dancoff or coupling).

  • bs_algo – Algorith for the computatio of the macroscopic dielectric function.

  • accuracy – Accuracy of the calculation.

  • spin_mode – Spin polarization.

  • smearing – Smearing technique.

  • charge – Electronic charge added to the unit cell.

  • scf_algorithm – Algorithm used for solving the SCF cycle.

abipy.abio.factories.scf_phonons_inputs(structure, pseudos, kppa, ecut=None, pawecutdg=None, scf_nband=None, accuracy='normal', spin_mode='polarized', smearing='fermi_dirac:0.1 eV', charge=0.0, scf_algorithm=None)[source]

Returns a list of input files for performing phonon calculations. GS input + the input files for the phonon calculation.

Parameters
  • structureabipy.core.structure.Structure object.

  • pseudos – List of filenames or list of pymatgen.io.abinit.pseudos.Pseudo objects or pymatgen.io.abinit.pseudos.PseudoTable object.

  • kppa – Defines the sampling used for the SCF run.

  • ecut – cutoff energy in Ha (if None, ecut is initialized from the pseudos according to accuracy)

  • pawecutdg – cutoff energy in Ha for PAW double-grid (if None, pawecutdg is initialized from the pseudos according to accuracy)

  • scf_nband – Number of bands for SCF run. If scf_nband is None, nband is automatically initialized from the list of pseudos, the structure and the smearing option.

  • accuracy – Accuracy of the calculation.

  • spin_mode – Spin polarization.

  • smearing – Smearing technique.

  • charge – Electronic charge added to the unit cell.

  • scf_algorithm – Algorithm used for solving of the SCF cycle.

abipy.abio.factories.phonons_from_gsinput(gs_inp, ph_ngqpt=None, qpoints=None, with_ddk=True, with_dde=True, with_bec=False, ph_tol=None, ddk_tol=None, dde_tol=None, wfq_tol=None, qpoints_to_skip=None, manager=None)[source]

Returns a list of inputs in the form of a MultiDataset to perform phonon calculations, based on a ground state abipy.abio.inputs.AbinitInput. It will determine if WFQ files should be calculated for some q points and add the NSCF AbinitInputs to the set. The inputs have the following tags, according to their function: “ddk”, “dde”, “nscf”, “ph_q_pert”. All of them have the tag “phonon”.

Parameters
  • gs_inp – an abipy.abio.inputs.AbinitInput representing a ground state calculation, likely the SCF performed to get the WFK.

  • ph_ngqpt – a list of three integers representing the gamma centered q-point grid used for the calculation. If None and qpoint==None the ngkpt value present in the gs_input will be used. Incompatible with qpoints.

  • qpoints – a list of coordinates of q points in reduced coordinates for which the phonon perturbations will be calculated. Incompatible with ph_ngqpt.

  • with_ddk – If True, if Gamma is included in the list of qpoints it will add inputs for the calculations of the DDK.

  • with_dde – If True, if Gamma is included in the list of qpoints it will add inputs for the calculations of the DDE. Automatically sets with_ddk=True.

  • with_bec – If Truem if Gamma is included in the list of qpoints the DDE will be calculated in the same input as the phonons. This will allow to determine the BECs. Automatically sets with_ddk=True and with_dde=False.

  • ph_tol – a dictionary with a single key defining the type of tolerance used for the phonon calculations and its value. Default: {“tolvrs”: 1.0e-10}.

  • ddk_tol – a dictionary with a single key defining the type of tolerance used for the DDK calculations and its value. Default: {“tolwfr”: 1.0e-22}.

  • dde_tol – a dictionary with a single key defining the type of tolerance used for the DDE calculations and its value. Default: {“tolvrs”: 1.0e-10}.

  • wfq_tol – a dictionary with a single key defining the type of tolerance used for the NSCF calculations of the WFQ and its value. Default {“tolwfr”: 1.0e-22}.

  • qpoints_to_skip – a list of coordinates of q points in reduced coordinates that will be skipped. Useful when calculating multiple grids for the same system to avoid duplicate calculations. If a DDB needs to be extended with more q points use e.g. ddb.qpoints.to_array().

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

abipy.abio.factories.piezo_elastic_inputs_from_gsinput(gs_inp, ddk_tol=None, rf_tol=None, ddk_split=False, rf_split=False, manager=None)[source]

Returns a abipy.abio.inputs.MultiDataset for performing elastic and piezoelectric constants calculations. GS input + the input files for the elastic and piezoelectric constants calculation.

Parameters
  • gs_inp – Ground State input to build piezo elastic inputs from.

  • ddk_tol – Tolerance for the DDK calculation (i.e. {“tolwfr”: 1.0e-20}).

  • rf_tol – Tolerance for the Strain RF calculations (i.e. {“tolvrs”: 1.0e-12}).

  • ddk_split – Whether to split the DDK calculations.

  • rf_split – whether to split the RF calculations.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

abipy.abio.factories.scf_piezo_elastic_inputs(structure, pseudos, kppa, ecut=None, pawecutdg=None, scf_nband=None, accuracy='normal', spin_mode='polarized', smearing='fermi_dirac:0.1 eV', charge=0.0, scf_algorithm=None, ddk_tol=None, rf_tol=None, ddk_split=False, rf_split=False)[source]

Returns a abipy.abio.inputs.MultiDataset for performing elastic and piezoelectric constants calculations. GS input + the input files for the elastic and piezoelectric constants calculation.

Parameters
  • structureabipy.core.structure.Structure object.

  • pseudos – List of filenames or list of pymatgen.io.abinit.pseudos.Pseudo objects or pymatgen.io.abinit.pseudos.PseudoTable object.

  • kppa – Defines the sampling used for the SCF run.

  • ecut – cutoff energy in Ha (if None, ecut is initialized from the pseudos according to accuracy)

  • pawecutdg – cutoff energy in Ha for PAW double-grid (if None, pawecutdg is initialized from the pseudos according to accuracy)

  • scf_nband – Number of bands for SCF run. If scf_nband is None, nband is automatically initialized from the list of pseudos, the structure and the smearing option.

  • accuracy – Accuracy of the calculation.

  • spin_mode – Spin polarization.

  • smearing – Smearing technique.

  • charge – Electronic charge added to the unit cell.

  • scf_algorithm – Algorithm used for solving of the SCF cycle.

  • ddk_tol – Tolerance for the Ddk calculation (i.e. {“tolwfr”: 1.0e-20}).

  • rf_tol – Tolerance for the Strain RF calculations (i.e. {“tolvrs”: 1.0e-12}).

  • ddk_split – Whether to split the ddk calculations.

  • rf_split – whether to split the RF calculations.

abipy.abio.factories.scf_for_phonons(structure, pseudos, kppa=None, ecut=None, pawecutdg=None, nband=None, accuracy='normal', spin_mode='polarized', smearing='fermi_dirac:0.1 eV', charge=0.0, scf_algorithm=None, shift_mode='Symmetric')[source]
abipy.abio.factories.dte_from_gsinput(gs_inp, use_phonons=True, ph_tol=None, ddk_tol=None, dde_tol=None, skip_dte_permutations=False, manager=None)[source]

Returns a list of inputs in the form of a abipy.abio.inputs.MultiDataset to perform calculations of non-linear properties, based on a ground state AbinitInput.

The inputs have the following tags, according to their function: “ddk”, “dde”, “ph_q_pert” and “dte”. All of them have the tag “dfpt”.

Parameters
  • gs_inp – an abipy.abio.inputs.AbinitInput representing a ground state calculation, likely the SCF performed to get the WFK.

  • use_phonons – determine wether the phonon perturbations at gamma should be included or not

  • ph_tol – a dictionary with a single key defining the type of tolerance used for the phonon calculations and its value. Default: {“tolvrs”: 1.0e-22}.

  • ddk_tol – a dictionary with a single key defining the type of tolerance used for the DDK calculations and its value. Default: {“tolwfr”: 1.0e-22}.

  • dde_tol – a dictionary with a single key defining the type of tolerance used for the DDE calculations and its value. Default: {“tolvrs”: 1.0e-22}.

  • skip_dte_permutations – Since the current version of abinit always performs all the permutations of the perturbations, even if only one is asked, if True avoids the creation of inputs that will produce duplicated outputs.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

abipy.abio.factories.dfpt_from_gsinput(gs_inp, ph_ngqpt=None, qpoints=None, do_ddk=True, do_dde=True, do_strain=True, do_dte=False, ph_tol=None, ddk_tol=None, dde_tol=None, wfq_tol=None, strain_tol=None, skip_dte_permutations=False, manager=None)[source]

Returns a list of inputs in the form of a MultiDataset to perform a set of calculations based on DFPT including phonons, elastic and non-linear properties. Requires a ground state abipy.abio.inputs.AbinitInput as a starting point.

It will determine if WFQ files should be calculated for some q points and add the NSCF AbinitInputs to the set. The original input is included and the inputs have the following tags, according to their function: “scf”, “ddk”, “dde”, “nscf”, “ph_q_pert”, “strain”, “dte”, “dfpt”.

N.B. Currently (version 8.8.3) anaddb does not support a DDB containing both 2nd order derivatives with qpoints different from gamma AND 3rd oreder derivatives. The calculations could be run, but the global DDB will not be directly usable as is.

Parameters
  • gs_inp – an abipy.abio.inputs.AbinitInput representing a ground state calculation, likely the SCF performed to get the WFK.

  • ph_ngqpt – a list of three integers representing the gamma centered q-point grid used for the calculation. If None and qpoint==None the ngkpt value present in the gs_input will be used. Incompatible with qpoints.

  • qpoints – a list of coordinates of q points in reduced coordinates for which the phonon perturbations will be calculated. Incompatible with ph_ngqpt.

  • do_ddk – If True, if Gamma is included in the list of qpoints it will add inputs for the calculations of the DDK.

  • do_dde – If True, if Gamma is included in the list of qpoints it will add inputs for the calculations of the DDE. Automatically sets with_ddk=True.

  • do_strain – If True inputs for the strain perturbations will be included.

  • do_dte – If True inputs for the non-linear perturbations will be included. The phonon non-linear perturbations will be included only if a phonon calculation at gamma is present. The caller is responsible for adding it. Automatically sets with_dde=True.

  • ph_tol – a dictionary with a single key defining the type of tolerance used for the phonon calculations and its value. Default: {“tolvrs”: 1.0e-10}.

  • ddk_tol – a dictionary with a single key defining the type of tolerance used for the DDK calculations and its value. Default: {“tolwfr”: 1.0e-22}.

  • dde_tol – a dictionary with a single key defining the type of tolerance used for the DDE calculations and its value. Default: {“tolvrs”: 1.0e-10}.

  • wfq_tol – a dictionary with a single key defining the type of tolerance used for the NSCF calculations of the WFQ and its value. Default {“tolwfr”: 1.0e-22}.

  • strain_tol – dictionary with a single key defining the type of tolerance used for the strain calculations of and its value. Default {“tolvrs”: 1.0e-12}.

  • skip_dte_permutations – Since the current version of abinit always performs all the permutations of the perturbations, even if only one is asked, if True avoids the creation of inputs that will produce duplicated outputs.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

input_tags Module

This module contains a list of default tags for the AbinitInput object

inputs Module

This module defines objects to facilitate the creation of ABINIT input files. The syntax is similar to the one used in ABINIT with small differences.

class abipy.abio.inputs.AbstractInput[source]

Bases: collections.abc.MutableMapping

Abstract class defining the methods that must be implemented by Input objects.

write(filepath='run.abi')[source]

Write the input file to file to filepath.

deepcopy()[source]

Deep copy of the input.

set_vars(*args, **kwargs)[source]

Set the value of the variables. Return dict with the variables added to the input.

Example

input.set_vars(ecut=10, ionmov=3)

set_vars_ifnotin(*args, **kwargs)[source]

Set the value of the variables but only if the variable is not already present. Return dict with the variables added to the input.

Example

input.set_vars(ecut=10, ionmov=3)

pop_vars(keys)[source]

Remove the variables listed in keys. Return dictionary with the variables that have been removed. Unlike remove_vars, no exception is raised if the variables are not in the input.

Parameters

keys – string or list of strings with variable names.

Example

inp.pop_vars([“ionmov”, “optcell”, “ntime”, “dilatmx”])

remove_vars(keys, strict=True)[source]

Remove the variables listed in keys. Return dictionary with the variables that have been removed.

Parameters
  • keys – string or list of strings with variable names.

  • strict – If True, KeyError is raised if at least one variable is not present.

abstract property vars

Dictionary with the input variables. Used to implement dict-like interface.

abstract to_string()[source]

Returns a string with the input.

generate(**kwargs)[source]

This function generates new inputs by replacing the variables specified in kwargs.

Parameters

kwargs – keyword arguments with the values used for each variable.

gs_inp = call_function_to_generate_initial_template()

# To generate two input files with different values of ecut:
for inp_ecut in gs_inp.generate(ecut=[10, 20]):
    print("do something with inp_ecut %s" % inp_ecut)

# To generate four input files with all the possible combinations of ecut and nsppol:
for inp_ecut in gs_inpt.generate(ecut=[10, 20], nsppol=[1, 2]):
    print("do something with inp_ecut %s" % inp_ecut)
class abipy.abio.inputs.AbiAbstractInput[source]

Bases: abipy.abio.inputs.AbstractInput

Abstract class defining the methods that must be implemented by Input objects. associated to Abinit executables.

add_abiobjects(*abi_objects)[source]

This function receive a list of AbiVarable objects and add the corresponding variables to the input.

abstract abivalidate(workdir=None, manager=None)[source]

This method should invoke the executable associated to the input object. to test whether the input variables are correct and consistent. The executable is supposed to implemente some sort of –dry-run option that invokes the parser to validate the input and exits.

Parameters
  • workdir – Working directory of the fake task used to compute the ibz. Use None for temporary dir.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

Returns

retcode: Return code. 0 if OK. output_file: output file of the run. log_file: log file of the Abinit run, use log_file.read() to access its content. stderr_file: stderr file of the Abinit run. use stderr_file.read() to access its content. task: Task object

Return type

namedtuple with the following attributes

exception abipy.abio.inputs.AbinitInputError[source]

Bases: Exception

Base error class for exceptions raised by AbinitInput.

class abipy.abio.inputs.AbinitInput(structure, pseudos, pseudo_dir=None, comment=None, decorators=None, abi_args=None, abi_kwargs=None, tags=None)[source]

Bases: abipy.abio.inputs.AbiAbstractInput, monty.json.MSONable, abipy.core.mixins.Has_Structure

This object stores the ABINIT variables for a single dataset.

Inheritance Diagram

Inheritance diagram of AbinitInput
Error

alias of AbinitInputError

variable_checksum()[source]

Return string with sha1 value in hexadecimal format. This method is mainly used in unit tests to check the invariance of the input objects. Note, indeed, that AbintInput is mutable and therefore should not be used as keyword in dictionaries.

as_dict()[source]

JSON interface used in pymatgen for easier serialization.

property vars

Dictionary with the input variables. Used to implement dict-like interface.

classmethod from_dict(d)[source]

JSON interface used in pymatgen for easier serialization.

property runlevel

A set of strings defining the type of run of the current input.

property decorators
register_decorator(decorator)[source]

Register a AbinitInputDecorator.

set_mnemonics(boolean)[source]

True if mnemonics should be printed

property mnemonics

Return True if mnemonics should be printed

property uses_ktimereversal

True if time-reversal symmetry is used to generate k-points in the IBZ.

set_spell_check(false_or_true)[source]

Activate/Deactivate spell-checking

property spell_check

True if spell checking is activated.

to_string(sortmode='section', post=None, with_mnemonics=False, mode='text', with_structure=True, with_pseudos=True, exclude=None, verbose=0)[source]

String representation.

Parameters
  • sortmode – “section” if variables should be grouped by sections. “a” for alphabetical order, None if no sorting is wanted.

  • with_mnemonics – True if mnemonics should be added.

  • mode – Either text or html if HTML output with links is wanted.

  • post – String that will be appended to the name of the variables Note that post is usually autodetected when we have multiple datatasets It is mainly used when we have an input file with a single dataset so that we can prevent the code from adding “1” to the name of the variables (In this case, indeed, Abinit complains if ndtset=1 is not specified and we don’t want ndtset=1 simply because the code will start to add _DS1_ to all the input and output files.

  • with_structure – False if section with structure variables should not be printed.

  • with_pseudos – False if JSON section with pseudo data should not be added.

  • exclude – List of variable names that should be ignored.

property comment

Optional string with comment. None if comment is not set.

set_comment(comment)[source]

Set a comment to be included at the top of the file.

property structure

The abipy.core.structure.Structure object associated to this input.

set_structure(structure)[source]

Set structure.

set_kmesh(ngkpt, shiftk, kptopt=1)[source]

Set the variables for the sampling of the BZ.

Parameters
  • ngkpt – Monkhorst-Pack divisions

  • shiftk – List of shifts.

  • kptopt – Option for the generation of the mesh.

set_gamma_sampling()[source]

Gamma-only sampling of the BZ.

set_autokmesh(nksmall, kptopt=1)[source]

Set the variables (ngkpt, shift, kptopt) for the sampling of the BZ.

Parameters
  • nksmall – Number of k-points used to sample the smallest lattice vector.

  • kptopt – Option for the generation of the mesh.

get_ngkpt_shiftk()[source]

Return info on the k-point sampling from the input file, more specifically a tuple with nkgpt and shift. ngkpt is set to None if the BZ sampling cannot be described in terms of three divisions + one shift.

set_phdos_qmesh(nqsmall, method='tetra', ph_qshift=(0, 0, 0))[source]

Set the variables (ngkpt, shift, kptopt) for the computation of the Phonon DOS in Abinit. Remember that the Phdos is computed via Fourier interpolation so there’s no constraint of the q-mesh.

Parameters
  • nqsmall – Number of k-points used to sample the smallest lattice vector.

  • method – gaussian or tetra.

  • ph_qshift – Shift for the mesh.

set_kpath(ndivsm, kptbounds=None, iscf=-2)[source]

Set the variables for the computation of the electronic band structure.

Parameters
  • ndivsm – Number of divisions for the smallest segment.

  • kptbounds – k-points defining the path in k-space. If None, we use the default high-symmetry k-path defined in the pymatgen database.

set_qpath(ndivsm, qptbounds=None)[source]

Set the variables for the computation of the phonon band structure and phonon linewidths.

Parameters
  • ndivsm – Number of divisions for the smallest segment.

  • qptbounds – q-points defining the path in q-space. If None, we use the default high-symmetry q-path defined in the pymatgen database.

set_kptgw(kptgw, bdgw)[source]

Set the variables (k-points, bands) for the computation of GW corrections.

Parameters
  • kptgw – List of k-points in reduced coordinates.

  • bdgw – Specifies the range of bands for the GW corrections. Accepts iterable that be reshaped to (nkptgw, 2) or a tuple of two integers if the extrema are the same for each k-point.

set_spin_mode(spin_mode)[source]

Set the variables used to the treat the spin degree of freedom. Return dictionary with the variables that have been removed.

Parameters
  • spin_modeSpinMode object or string. Possible values for string are:

  • polarized (-) –

  • unpolarized (-) –

  • afm (-) –

  • spinor (-) –

  • spinor_nomag (-) –

set_autospinat(default=0.6)[source]

Set the variable spinat for collinear calculation in the format (0, 0, m) with the value of m determined with the following order of preference:

  1. If the site of the structure has a magmom setting, that is used.

  2. If the species on the site has a spin setting, that is used.

  3. If the species itself has a particular setting in the config file, that is used, e.g., Mn3+ may have a different magmom than Mn4+.

  4. The element symbol itself is checked in the config file.

  5. If there are no settings, the default value is used.

property pseudos

List of pymatgen.io.abinit.pseudos.Pseudo objects.

property ispaw

True if PAW calculation.

property isnc

True if norm-conserving calculation.

property num_valence_electrons

Number of valence electrons computed from the pseudos and the structure.

property valence_electrons_per_atom

Number of valence electrons for each atom in the structure.

linspace(varname, start, stop, num=50, endpoint=True)[source]

Returns num evenly spaced samples, calculated over the interval [start, stop].

The endpoint of the interval can optionally be excluded.

Parameters
  • start – The starting value of the sequence.

  • stop – The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of ndtset + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False.

  • num (int) – Number of samples to generate. Default is 50.

  • endpoint (bool) – optional. If True, stop is the last sample. Otherwise, it is not included. Default is True.

arange(varname, start, stop, step)[source]

Return evenly spaced values within a given interval.

Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop).

When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use linspace for these cases.

Parameters
  • start – Start of interval. The interval includes this value. The default start value is 0.

  • stop – End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point

  • step – Spacing between values. For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. The default step size is 1. If step is specified, start must also be given.

product(*items)[source]

Cartesian product of input iterables. Equivalent to nested for-loops.

inp.product("ngkpt", "tsmear", [[2,2,2], [4,4,4]], [0.1, 0.2, 0.3])
new_with_vars(*args, **kwargs)[source]

Return a new input with the given variables.

Example

new = input.new_with_vars(ecut=20)

new_with_structure(new_structure, scdims=None, verbose=1)[source]

Return a new abipy.abio.inputs.AbinitInput with different structure. See notes below for the constraints that must be fulfilled by the new structure

Parameters
  • new_structure – Parameters defining the crystalline structure. Accepts abipy.core.structure.Structure object file with structure (CIF, netcdf file, …) or dictionary with ABINIT geo variables.

  • scdims – 3 integer giving with the number of cells in the supercell along the three reduced directions. Must be used when new_structure represents a supercell of the initial structure defined in the input file.

  • verbose – Verbosity level.

Warning

If scdims is None (i.e. no supercell), the two structures must have the same value of natom and typat, they can only differ at the level of the lattice and of the atomic positions. When structure represents a supercell, scdims must be coherent with the new_structure passed as argument.

new_with_decorators(decorators)[source]

This function receives a list of AbinitInputDecorator objects or just a single object, applies the decorators to the input and returns a new abipy.abio.inputs.AbinitInput object. self is not changed.

pop_tolerances()[source]

Remove all the tolerance variables present in self. Return dictionary with the variables that have been removed.

pop_irdvars()[source]

Remove all the ird* variables present in self. Return dictionary with the variables that have been removed.

property scf_tolvar

Returns the tolerance variable and value relative to the SCF convergence. If more than one is present raise an error

make_ebands_input(ndivsm=15, tolwfr=1e-20, nscf_nband=None)[source]

Generate an input file for band structure calculation from a GS-SCF input.

Parameters
  • ndivsm – Number of divisions used to sample the smallest segment of the k-path.

  • tolwfr – Tolerance on residuals for NSCF calculation

  • nscf_nband – Number of bands for NSCF calculation. +10 if None.

make_edos_input(ngkpt, shiftk=(0, 0, 0), tolwfr=1e-20, nscf_nband=None)[source]

Generate an input file for electron DOS calculation from a GS-SCF input.

Parameters
  • ngkpt – Number of divisions for the k-mesh.

  • shiftk – List of shifts.

  • tolwfr – Tolerance on residuals for NSCF calculation

  • nscf_nband – Number of bands for NSCF calculation. +10 if None.

make_nscf_kptopt0_input(kpts, tolwfr=1e-20, iscf=-2)[source]

Build an input for NSCF calculation from a GS-SCF one. Uses explicit list of k-points and kptopt 0.

Parameters
  • kpts – List of k-points in reduced coordinates.

  • tolwfr – Tolerance on residuals.

make_dfpt_effmass_input(kpts, effmass_bands_f90, tolwfr=1e-20, iscf=-2)[source]
Return abipy.abio.inputs.MultiDataset with 2 inputs for the calculation of effective masses with DFPT

The first input in a standard NSCF run, the second input computes the effective masses.

Parameters
  • kpts – List of k-points in reduced coordinates where effective masses are wanted.

  • efmas_bands_f90 – (nkpt, 2) array with band range for effmas computation. WARNING: Assumes Fortran convention with indices starting from 1.

  • tolwfr – Tolerance on residuals.

make_ph_inputs_qpoint(qpt, tolerance=None, prtwf=-1, prepgkk=0, manager=None)[source]

Builds and returns a abipy.abio.inputs.MultiDataset list of input files for the calculation of phonons at the given q-point qpt. It should be called with an input the represents a GS run.

Parameters
  • qpt – q-point in reduced coordinates.

  • tolerance – dict {varname: value} with the tolerance to be used in the DFPT run. Defaults to {“tolvrs”: 1.0e-10}.

  • prtwf – 1WFs are only needed for restarting or non-linear response. Since these files are huge, we use prtwf -1 so that the 1WF file is produced only if the calculation is not converged so that AbiPy can restart it.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

Warning

The routine assumes the q-point is such that k + q belongs to the initial GS mesh. so that the DFPT run can be started from the WFK file directly without having to generate WFQ files.

make_ddk_inputs(tolerance=None, kptopt=2, only_vk=False, manager=None)[source]

Return inputs for performing DDK calculations. This functions should be called with an input the represents a GS run.

Parameters
  • tolerance – dict {varname: value} with the tolerance to be used in the DFPT run. Defaults to {“tolwfr”: 1.0e-22}.

  • kptopt – 2 to take into account time-reversal symmetry. Note that kptopt 1 is not available.

  • only_vk – If only matrix elements of the velocity operator are needed. First-order wavefunctions won’t be converged –> not usable for other DFPT calculations.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

Returns

List of abipy.abio.inputs.AbinitInput objects for DFPT runs.

make_dde_inputs(tolerance=None, use_symmetries=True, manager=None)[source]

Return abipy.abio.inputs.MultiDataset inputs for the calculation of the electric field perturbations. This functions should be called with an input the represents a gs run.

Parameters
  • tolerance – dict {varname: value} with the tolerance to be used in the DFPT run. Defaults to {“tolvrs”: 1.0e-22}.

  • use_symmetries – boolean that computes the irreducible components of the perturbation. Default to True. Should be set to False for nonlinear coefficients calculation.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

make_dte_inputs(phonon_pert=False, skip_permutations=False, ixc=None, manager=None)[source]

Return abipy.abio.inputs.MultiDataset inputs for DTE calculation. This functions should be called with an input that represents a GS run.

Parameters
  • phonon_pert – is True also the phonon perturbations will be considered. Default False.

  • skip_permutations – Since the current version of abinit always performs all the permutations of the perturbations, even if only one is asked, if True avoids the creation of inputs that will produce duplicated outputs.

  • ixc – Value of ixc variable. Used to overwrite the default value read from pseudos.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

make_bec_inputs(tolerance=None, manager=None)[source]

Return abipy.abio.inputs.MultiDataset inputs for the calculation of the Born effective charges. This functions should be called with an input that represents a GS run.

make_strain_perts_inputs(tolerance=None, phonon_pert=True, kptopt=2, manager=None)[source]

Return abipy.abio.inputs.MultiDataset inputs for strain perturbation calculation. This functions should be called with an input that represents a GS run.

Parameters
  • tolerance – dict {varname: value} with the tolerance to be used in the DFPT run. Defaults to {“tolvrs”: 1.0e-12}.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

  • phonon_pert – is True also the phonon perturbations will be considered. Default False.

  • kptopt – 2 to take into account time-reversal symmetry.

abivalidate(workdir=None, manager=None)[source]

Run ABINIT in dry-run mode to validate the input file.

Parameters
  • workdir – Working directory of the fake task used to compute the ibz. Use None for temporary dir.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

Returns

retcode: Return code. 0 if OK. output_file: output file of the run. log_file: log file of the Abinit run, use log_file.read() to access its content. stderr_file: stderr file of the Abinit run. use stderr_file.read() to access its content. task: Task object

Return type

namedtuple with the following attributes

abiget_spacegroup(tolsym=None, retdict=False, workdir=None, manager=None, verbose=0)[source]

This function invokes Abinit to get the space group (as detected by Abinit, not by spglib) It should be called with an input file that contains all the mandatory variables required by ABINIT.

Parameters
  • tolsym – Abinit tolsym input variable. None correspondes to the default value.

  • retdict – True to return dictionary with space group information instead of Structure.

  • workdir – Working directory of the fake task used to compute the ibz. Use None for temporary dir.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

  • verbose – Verbosity level.

Returns

abipy.core.structure.Structure object with AbinitSpaceGroup obtained from the main output file if retdict is False else dict with e.g. {‘bravais’: ‘Bravais cF (face-center cubic)’, ‘spg_number’: 227, ‘spg_symbol’: ‘Fd-3m’}.

abiget_ibz(ngkpt=None, shiftk=None, kptopt=None, workdir=None, manager=None, verbose=0)[source]

This function computes the list of points in the IBZ and the corresponding weights. It should be called with an input file that contains all the mandatory variables required by ABINIT.

Parameters
  • ngkpt – Number of divisions for the k-mesh (default None i.e. use ngkpt from self)

  • shiftk – List of shifts (default None i.e. use shiftk from self)

  • kptopt – Option for k-point generation. If None, the value in self is used.

  • workdir – Working directory of the fake task used to compute the ibz. Use None for temporary dir.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

  • verbose – verbosity level.

Returns

points: numpy.ndarray with points in the IBZ in reduced coordinates. weights: numpy.ndarray with weights of the points.

Return type

namedtuple with attributes

abiget_irred_phperts(qpt=None, ngkpt=None, shiftk=None, kptopt=None, prepgkk=0, workdir=None, manager=None)[source]

This function, computes the list of irreducible perturbations for DFPT. It should be called with an input file that contains all the mandatory variables required by ABINIT.

Parameters
  • qpt – qpoint of the phonon in reduced coordinates. Used to shift the k-mesh if qpt is not passed, self must already contain “qpt” otherwise an exception is raised.

  • ngkpt – Number of divisions for the k-mesh (default None i.e. use ngkpt from self)

  • shiftk – Shiftks (default None i.e. use shiftk from self)

  • kptopt – Option for k-point generation. If None, the value in self is used.

  • prepgkk – 1 to activate computation of all 3*natom perts (debugging option).

  • workdir – Working directory of the fake task used to compute the ibz. Use None for temporary dir.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

Returns

List of dictionaries with the Abinit variables defining the irreducible perturbation

Example

[{‘idir’: 1, ‘ipert’: 1, ‘qpt’: [0.25, 0.0, 0.0]},

{‘idir’: 2, ‘ipert’: 1, ‘qpt’: [0.25, 0.0, 0.0]}]

abiget_irred_ddeperts(ngkpt=None, shiftk=None, kptopt=None, workdir=None, manager=None)[source]

This function, computes the list of irreducible perturbations for DFPT. It should be called with an input file that contains all the mandatory variables required by ABINIT.

Parameters
  • ngkpt – Number of divisions for the k-mesh (default None i.e. use ngkpt from self)

  • shiftk – Shiftks (default None i.e. use shiftk from self)

  • kptopt – Option for k-point generation. If None, the value in self is used.

  • workdir – Working directory of the fake task used to compute the ibz. Use None for temporary dir.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

Returns

List of dictionaries with the Abinit variables defining the irreducible perturbation

Example

[{‘idir’: 1, ‘ipert’: 4, ‘qpt’: [0.0, 0.0, 0.0]},

{‘idir’: 2, ‘ipert’: 4, ‘qpt’: [0.0, 0.0, 0.0]}]

abiget_irred_dteperts(ngkpt=None, shiftk=None, kptopt=None, ixc=None, workdir=None, manager=None, phonon_pert=False)[source]

This function, computes the list of irreducible perturbations for DFPT. It should be called with an input file that contains all the mandatory variables required by ABINIT.

Parameters
  • ngkpt – Number of divisions for the k-mesh (default None i.e. use ngkpt from self)

  • shiftk – Shiftks (default None i.e. use shiftk from self)

  • kptopt – Option for k-point generation. If None, the value in self is used.

  • workdir – Working directory of the fake task used to compute the ibz. Use None for temporary dir.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

  • phonon_pert – if True also the phonon perturbations will be considered. Default False.

Returns

List of dictionaries with the Abinit variables defining the irreducible perturbation

Example

[{‘idir’: 1, ‘ipert’: 4, ‘qpt’: [0.0, 0.0, 0.0]},

{‘idir’: 2, ‘ipert’: 4, ‘qpt’: [0.0, 0.0, 0.0]}]

abiget_irred_strainperts(ngkpt=None, shiftk=None, kptopt=None, workdir=None, manager=None, phonon_pert=True)[source]

This function, computes the list of irreducible perturbations for strain perturbations in DFPT. It should be called with an input file that contains all the mandatory variables required by ABINIT.

Parameters
  • ngkpt – Number of divisions for the k-mesh (default None i.e. use ngkpt from self)

  • shiftk – Shiftks (default None i.e. use shiftk from self)

  • kptopt – Option for k-point generation. If None, the value in self is used.

  • workdir – Working directory of the fake task used to compute the ibz. Use None for temporary dir.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

  • phonon_pert – if True the phonon perturbation at gamma will be included.

Returns

List of dictionaries with the Abinit variables defining the irreducible perturbation

Example

[{‘idir’: 1, ‘ipert’: 4, ‘qpt’: [0.0, 0.0, 0.0]},

{‘idir’: 2, ‘ipert’: 4, ‘qpt’: [0.0, 0.0, 0.0]}]

pop_par_vars(all=False)[source]

Remove all the variables associated to parallelism from the input file. Useful in case of a restart when we need to remove the parallel variables before rerunning autoparal

abiget_autoparal_pconfs(max_ncpus, autoparal=1, workdir=None, manager=None, verbose=0)[source]

Get all the possible configurations up to max_ncpus. Return list of parallel configurations.

add_tags(tags)[source]

Add tags to the input

Parameters

tags – A single tag or list/tuple/set of tags

remove_tags(tags)[source]

Remove tags from the input

Parameters

tags – A single tag or list/tuple/set of tags

class abipy.abio.inputs.MultiDataset(structure, pseudos, pseudo_dir='', ndtset=1)[source]

Bases: object

This object is essentially a list of abipy.abio.inputs.AbinitInput objects. that provides an easy-to-use interface to apply global changes to the the inputs stored in the objects.

Let’s assume for example that multi contains two AbinitInput objects and we want to set ecut to 1 in both dictionaries. The direct approach would be:

for inp in multi:

inp.set_vars(ecut=1)

or alternatively:

for i in range(multi.ndtset):

multi[i].set_vars(ecut=1)

MultiDataset provides its own implementaion of __getattr__ so that one can simply use:

multi.set_vars(ecut=1)

multi.get(“ecut”) returns a list of values. It’s equivalent to:

[inp[“ecut”] for inp in multi]

Note that if “ecut” is not present in one of the input of multi, the corresponding entry is set to None. A default value can be specified with:

multi.get(“paral_kgb”, 0)

Warning

MultiDataset does not support calculations done with different sets of pseudopotentials. The inputs can have different crystalline structures (as long as the atom types are equal) but each input in MultiDataset must have the same set of pseudopotentials.

Error

alias of AbinitInputError

classmethod from_inputs(inputs)[source]

Build object from a list of abipy.abio.inputs.AbinitInput objects.

classmethod replicate_input(input, ndtset)[source]

Construct a multidataset with ndtset from the abipy.abio.inputs.AbinitInput input.

property ndtset

Number of inputs in self.

property pseudos

Pseudopotential objects.

property ispaw

True if PAW calculation.

property isnc

True if norm-conserving calculation.

append(abinit_input)[source]

Add a abipy.abio.inputs.AbinitInput to the list.

extend(abinit_inputs)[source]

Extends self with a list of abipy.abio.inputs.AbinitInput objects.

addnew_from(dtindex)[source]

Add a new entry in the multidataset by copying the input with index dtindex.

split_datasets()[source]

Return list of abipy.abio.inputs.AbinitInput objects..

deepcopy()[source]

Deep copy of the MultiDataset.

property has_same_structures

True if all inputs in MultiDataset are equal.

to_string(mode='text', verbose=0, with_pseudos=True)[source]

String representation i.e. the input file read by Abinit.

Parameters
  • mode – Either text or html if HTML output with links is wanted.

  • with_pseudos – False if JSON section with pseudo data should not be added.

get_vars_dataframe(*varnames)[source]

Return pandas DataFrame with the value of the variables specified in varnames.

filter_by_tags(tags=None, exclude_tags=None)[source]

Filters the input according to the tags

Parameters
  • tags – A single tag or list/tuple/set of tags

  • exclude_tags – A single tag or list/tuple/set of tags that should be excluded

Returns

A abipy.abio.inputs.MultiDataset containing the inputs containing all the requested tags.

add_tags(tags, dtindeces=None)[source]

Add tags to the selected inputs

Parameters
  • tags – A single tag or list/tuple/set of tags

  • dtindeces – a list of indices to which the tags will be added. None=all the inputs.

remove_tags(tags, dtindeces=None)[source]

Remove tags from the selected inputs

Parameters
  • tags – A single tag or list/tuple/set of tags

  • dtindeces – a list of indices from which the tags will be removed. None=all the inputs.

filter_by_runlevel(runlevel)[source]

Return new abipy.abio.inputs.MultiDataset object in which only the inputs with the given runlevel are selected.

write(filepath='run.abi')[source]

Write ndset input files to disk. The name of the file is constructed from the dataset index e.g. run0.abi

exception abipy.abio.inputs.AnaddbInputError[source]

Bases: Exception

Base error class for exceptions raised by AnaddbInput

class abipy.abio.inputs.AnaddbInput(structure, comment='', anaddb_args=None, anaddb_kwargs=None, spell_check=True)[source]

Bases: abipy.abio.inputs.AbiAbstractInput, abipy.core.mixins.Has_Structure

This object stores the anaddb variables.

Inheritance Diagram

Inheritance diagram of AnaddbInput
Error

alias of AnaddbInputError

property vars

Dictionary with the input variables. Used to implement dict-like interface.

set_spell_check(false_or_true)[source]

Activate/Deactivate spell-checking

property spell_check

True if spell checking is activated.

classmethod modes_at_qpoint(structure, qpoint, asr=2, chneut=1, dipdip=1, ifcflag=0, lo_to_splitting=False, directions=None, anaddb_args=None, anaddb_kwargs=None, spell_check=False)[source]

Build an abipy.abio.inputs.AnaddbInput for the calculation of the phonon frequencies at a given q-point.

Parameters
  • structureabipy.core.structure.Structure object

  • qpoint – Reduced coordinates of the q-point where phonon frequencies and modes are wanted

  • chneut, dipdp, ifcflag (asr,) – Anaddb input variable. See official documentation.

  • lo_to_splitting – if True calculation of the LO-TO splitting will be included if qpoint==Gamma

  • directions – list of 3D directions along which the LO-TO splitting will be calculated. If None the three cartesian direction will be used

  • anaddb_args – List of tuples (key, value) with Anaddb input variables (default: empty)

  • anaddb_kwargs – Dictionary with Anaddb input variables (default: empty)

  • spell_check – False to disable spell checking for input variables.

classmethod piezo_elastic(structure, relaxed_ion=True, stress_correction=False, asr=2, chneut=1, dipdip=1, anaddb_args=None, anaddb_kwargs=None)[source]

Build an abipy.abio.inputs.AnaddbInput for the calculation of piezoelectric and elastic tensor calculations.

Parameters

chneut, dipdp (asr,) – Anaddb input variable. See official documentation.

classmethod phbands_and_dos(structure, ngqpt, nqsmall, qppa=None, ndivsm=20, line_density=None, q1shft=(0, 0, 0), qptbounds=None, asr=2, chneut=0, dipdip=1, dos_method='tetra', lo_to_splitting=False, anaddb_args=None, anaddb_kwargs=None, spell_check=False, comment=None)[source]

Build an abipy.abio.inputs.AnaddbInput for the computation of phonon bands and phonon DOS.

Parameters
  • structureabipy.core.structure.Structure object

  • ngqpt – Monkhorst-Pack divisions for the phonon Q-mesh (coarse one)

  • nqsmall – Used to generate the (dense) mesh for the DOS. It defines the number of q-points used to sample the smallest lattice vector.

  • qppa – Defines the homogeneous q-mesh used for the DOS in units of q-points per reciproval atom. Overrides nqsmall.

  • line_density – Defines the a density of k-points per reciprocal atom to plot the phonon dispersion. Overrides ndivsm.

  • ndivsm – Used to generate a normalized path for the phonon bands. If gives the number of divisions for the smallest segment of the path.

  • q1shft – Shifts used for the coarse Q-mesh

  • Boundaries of the path. If None, the path is generated from an internal database (qptbounds) – depending on the input structure.

  • chneut, dipdp (asr,) – Anaddb input variable. See official documentation.

  • dos_method – Possible choices: “tetra”, “gaussian” or “gaussian:0.001 eV”. In the later case, the value 0.001 eV is used as gaussian broadening

  • lo_to_splitting – if True calculation of the LO-TO splitting will be included

  • anaddb_args – List of tuples (key, value) with Anaddb input variables (default: empty)

  • anaddb_kwargs – Dictionary with Anaddb input variables (default: empty)

  • spell_check – False to disable spell checking for input variables.

  • comment – Optional string with a comment that will be placed at the beginning of the file.

classmethod modes(structure, enunit=2, asr=2, chneut=1, anaddb_args=None, anaddb_kwargs=None)[source]

Build an abipy.abio.inputs.AnaddbInput for the computation of phonon modes.

Parameters
  • Structureabipy.core.structure.Structure object

  • ngqpt – Monkhorst-Pack divisions for the phonon Q-mesh (coarse one)

  • nqsmall – Used to generate the (dense) mesh for the DOS. It defines the number of q-points used to sample the smallest lattice vector.

  • q1shft – Shifts used for the coarse Q-mesh

  • Boundaries of the path. If None, the path is generated from an internal database (qptbounds) – depending on the input structure.

  • chneut, dipdp (asr,) – Anaddb input variable. See official documentation.

  • anaddb_args – List of tuples (key, value) with Anaddb input variables (default: empty)

  • anaddb_kwargs – Dictionary with Anaddb input variables (default: empty)

classmethod ifc(structure, ngqpt, ifcout=None, q1shft=(0, 0, 0), asr=2, chneut=1, dipdip=1, anaddb_args=None, anaddb_kwargs=None)[source]

Build an abipy.abio.inputs.AnaddbInput for the computation of interatomic force constants.

Parameters
  • structureabipy.core.structure.Structure object

  • ngqpt – Monkhorst-Pack divisions for the phonon Q-mesh (coarse one)

  • ifcout – Number of neighbouring atoms for which the ifc’s will be output. If None all the atoms in the big box.

  • q1shft – Shifts used for the coarse Q-mesh

  • chneut, dipdip (asr,) – Anaddb input variable. See official documentation.

  • anaddb_args – List of tuples (key, value) with Anaddb input variables (default: empty)

  • anaddb_kwargs – Dictionary with Anaddb input variables (default: empty)

classmethod dfpt(structure, ngqpt=None, relaxed_ion=False, piezo=False, dde=False, strain=False, dte=False, raman=False, stress_correction=False, nqsmall=None, qppa=None, ndivsm=20, line_density=None, q1shft=(0, 0, 0), qptbounds=None, asr=2, chneut=1, dipdip=1, ramansr=1, alphon=1, dos_method='tetra', directions=None, anaddb_args=None, anaddb_kwargs=None, comment=None)[source]

Builds an abipy.abio.inputs.AnaddbInput to post-process a generic DFPT calculation.

Parameters
  • structureabipy.core.structure.Structure object.

  • ngqpt – Monkhorst-Pack divisions for the phonon Q-mesh (coarse one)

  • stress_correction – True to activate computation of stress correction in elastic tensor. Requires DDB with stress entries.

  • relaxed_ion – True to activate computation of relaxed-ion elastic and piezoelectric tensors. (assume the DDB has atomic perturbations at Gamma)

  • piezo – if True the piezoelectric tensor are calculated (requires piezoelectric perturbations)

  • dde – if True dielectric tensors will be calculated. If phonon band structure is calculated will also enable the calculation of the lo_to splitting (requires the DDE perturbations)

  • strain – if True the elastic tensors will be calculated (requires the strain perturbations)

  • dte – if True properties related to the nonlinear tensors will be calculated (requires third orders perturbations)

  • raman – if True the Raman tensor will be calculated (sets dte to True).

  • nqsmall – Used to generate the (dense) mesh for the DOS. It defines the number of q-points used to sample the smallest lattice vector.

  • qppa – Defines the homogeneous q-mesh used for the DOS in units of q-points per reciproval atom. Overrides nqsmall.

  • line_density – Defines the a density of k-points per reciprocal atom to plot the phonon dispersion. Overrides ndivsm.

  • ndivsm – Used to generate a normalized path for the phonon bands. If gives the number of divisions for the smallest segment of the path.

  • q1shft – Shifts used for the coarse Q-mesh

  • qptbounds – Boundaries of the path. If None, the path is generated from an internal database depending on the input structure.

  • chneut, dipdp, ramansr, alphon (asr,) – Anaddb input variable. See official documentation.

  • dos_method – Possible choices: “tetra”, “gaussian” or “gaussian:0.001 eV”. In the later case, the value 0.001 eV is used as gaussian broadening

  • directions – list of 3D directions along which the non analytical contribution will be calculated. If None the three cartesian direction will be used. Used only when dte=True.

  • anaddb_args – List of tuples (key, value) with Anaddb input variables (default: empty)

  • anaddb_kwargs – Dictionary with Anaddb input variables (default: empty)

  • comment – Optional string with a comment that will be placed at the beginning of the file.

property structure

abipy.core.structure.Structure object.

to_string(sortmode=None, mode='text', verbose=0)[source]

String representation.

Parameters
  • sortmode – “a” for alphabetical order, None if no sorting is wanted

  • mode – Either text or html if HTML output with links is wanted.

set_qpath(ndivsm, qptbounds=None)[source]

Set the variables for the computation of the phonon band structure.

Parameters
  • ndivsm – Number of divisions for the smallest segment.

  • qptbounds – q-points defining the path in k-space. If None, we use the default high-symmetry k-path defined in the pymatgen database.

set_autoqmesh(nqsmall)[source]

Set the variable nqpt for the sampling of the BZ.

Parameters

nqsmall – Number of divisions used to sample the smallest lattice vector.

abivalidate(workdir=None, manager=None)[source]

Run ANADDB in dry-run mode to validate the input file.

Parameters
  • workdir – Working directory of the fake task used to compute the ibz. Use None for temporary dir.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

Returns

retcode: Return code. 0 if OK. output_file: output file of the run. log_file: log file of the Abinit run, use log_file.read() to access its content. stderr_file: stderr file of the Abinit run. use stderr_file.read() to access its content. task: Task object

Return type

namedtuple with the following attributes

class abipy.abio.inputs.OpticVar[source]

Bases: abipy.abio.inputs.OpticVar

property url

The url associated to the variable.

String with the URL of the web page.

exception abipy.abio.inputs.OpticError[source]

Bases: Exception

Error class raised by OpticInput.

class abipy.abio.inputs.OpticInput(**kwargs)[source]

Bases: abipy.abio.inputs.AbiAbstractInput, monty.json.MSONable

Input file for optic executable

Error

alias of OpticError

property vars

Dictionary with the input variables. Used to implement dict-like interface.

get_default(key)[source]

Return the default value of variable key.

classmethod from_dict(d)[source]

JSON interface used in pymatgen for easier serialization.

as_dict()[source]

JSON interface used in pymatgen for easier serialization.

to_string(verbose=0)[source]

String representation.

only_independent_chi_components(structure, assume_symmetric_tensor=False, symprec=0.001, angle_tolerance=5)[source]

Use the crystal system returned by spglib to find the independent components of the linear susceptibility tensor and set the appropriate variables.

Parameters
  • structure – Crystalline structure

  • assume_symmetric_tensor – True if tensor can be assumed symmetric. Note that the tensor is symmetric only for a lossless and non-optically active material.

  • angle_tolerance (symprec,) – Parameters passed to spglib.

Returns

Set internal variables and return list of components to compute.

abivalidate(workdir=None, manager=None)[source]

Run OPTIC in dry-run mode to validate the input file. Note: This method is a stub, it always return retcode 0

Parameters
  • workdir – Working directory of the fake task used to compute the ibz. Use None for temporary dir.

  • managerabipy.flowtk.tasks.TaskManager of the task. If None, the manager is initialized from the config file.

Returns

retcode: Return code. 0 if OK. output_file: output file of the run. log_file: log file of the Abinit run, use log_file.read() to access its content. stderr_file: stderr file of the Abinit run. use stderr_file.read() to access its content. task: Task object

Return type

namedtuple with the following attributes

class abipy.abio.inputs.Cut3DInput(infile_path=None, output_filepath=None, options=None)[source]

Bases: monty.json.MSONable, object

This object stores the options to run a single cut3d analysis.

Warning

Converters with nspden > 1 won’t work since cut3d asks for the ispden index.

to_string(verbose=0)[source]

Returns a string with the input.

write(filepath)[source]

Writes the input to a file.

classmethod den_to_3d_formatted(density_filepath, output_filepath)[source]

Generates a cut3d input for the conversion to a 3D formatted format.

Parameters
  • density_filepath – absolute or relative path to the input density produced by abinit. Can be None to be defined at a later time.

  • output_filepath – path to the file that should be produced by cut3D, if required. At this stage it would be safer to use just the file name, as using an absolute or relative path may fail depending on the compiler.

classmethod den_to_3d_indexed(density_filepath, output_filepath)[source]

Generates a cut3d input for the conversion to a 3D indexed format.

Parameters
  • density_filepath – absolute or relative path to the input density produced by abinit. Can be None to be defined at a later time.

  • output_filepath – path to the file that should be produced by cut3D, if required. At this stage it would be safer to use just the file name, as using an absolute or relative path may fail depending on the compiler.

classmethod den_to_molekel(density_filepath, output_filepath)[source]

Generates a cut3d input for the conversion to a Molekel format.

Parameters
  • density_filepath – absolute or relative path to the input density produced by abinit. Can be None to be defined at a later time.

  • output_filepath – path to the file that should be produced by cut3D, if required. At this stage it would be safer to use just the file name, as using an absolute or relative path may fail depending on the compiler.

classmethod den_to_tecplot(density_filepath, output_filepath)[source]

Generates a cut3d input for the conversion to a Tecplot format.

Parameters
  • density_filepath – absolute or relative path to the input density produced by abinit. Can be None to be defined at a later time.

  • output_filepath – path to the file that should be produced by cut3D, if required. At this stage it would be safer to use just the file name, as using an absolute or relative path may fail depending on the compiler.

classmethod den_to_xsf(density_filepath, output_filepath, shift=None)[source]

Generates a cut3d input for the conversion to an xsf format.

Parameters
  • density_filepath – absolute or relative path to the input density produced by abinit. Can be None to be defined at a later time.

  • output_filepath – path to the file that should be produced by cut3D, if required. At this stage it would be safer to use just the file name, as using an absolute or relative path may fail depending on the compiler.

  • shift – a list of three integers defining the shift along the x, y, z axis. None if no shift is required.

classmethod den_to_cube(density_filepath, output_filepath)[source]

Generates a cut3d input for the conversion to a cube format.

Parameters
  • density_filepath – absolute or relative path to the input density produced by abinit. Can be None to be defined at a later time.

  • output_filepath – path to the file that should be produced by cut3D, if required. At this stage it would be safer to use just the file name, as using an absolute or relative path may fail depending on the compiler.

classmethod hirshfeld(density_filepath, all_el_dens_paths)[source]

Generates a cut3d input for the calculation of the Hirshfeld charges from the density.

Parameters
  • density_filepath – absolute or relative path to the input density produced by abinit. Can be None to be defined at a later time.

  • all_el_dens_paths – a list of paths to the all-electron density files corresponding to the elements defined in the abinit input. See https://www.abinit.org/downloads/all_core_electron for files.

classmethod hirshfeld_from_fhi_path(density_filepath, structure, fhi_all_el_path)[source]

Generates a cut3d input for the calculation of the Hirshfeld charges from the density. Automatically selects the all-electron density files from a folder containing the fhi all-electron density files: https://www.abinit.org/downloads/all_core_electron

This will work only if the input has been generated with AbinitInput and the Structure object is the same provided to AbinitInput.

Parameters
  • density_filepath – absolute or relative path to the input density produced by abinit. Can be None to be defined at a later time.

  • structure – the structure used for the ground state calculation. Used to determine the elements

  • fhi_all_el_path – path to the folder containing the fhi all-electron density files

as_dict()[source]

JSON interface used in pymatgen for easier serialization.

classmethod from_dict(d)[source]

JSON interface used in pymatgen for easier serialization.

abipy.abio.inputs.product_dict(d)[source]

This function receives a dictionary d where each key defines a list of items or a simple scalar. It constructs the Cartesian product of the values (equivalent to nested for-loops), and returns a list of dictionaries with the values that would be used inside the loop.

>>> d = OrderedDict([("foo", [2, 4]), ("bar", 1)])
>>> product_dict(d) == [OrderedDict([('foo', 2), ('bar', 1)]), OrderedDict([('foo', 4), ('bar', 1)])]
True
>>> d = OrderedDict([("bar", [1,2]), ('foo', [3,4])])
>>> product_dict(d) == [{'bar': 1, 'foo': 3},
... {'bar': 1, 'foo': 4},
... {'bar': 2, 'foo': 3},
... {'bar': 2, 'foo': 4}]
True

outputs Module

Objects used to extract and plot results from output files in text format.

class abipy.abio.outputs.AbinitTextFile(filepath)[source]

Bases: abipy.core.mixins.TextFile

Base class for the ABINIT main output files and log files.

property events

List of ABINIT events reported in the file.

get_timer()[source]

Timer data.

class abipy.abio.outputs.AbinitLogFile(filepath)[source]

Bases: abipy.abio.outputs.AbinitTextFile, abipy.core.mixins.NotebookWriter

Class representing the Abinit log file.

Inheritance Diagram

Inheritance diagram of AbinitLogFile
to_string(verbose=0)[source]
plot(**kwargs)[source]

Empty placeholder.

yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user.

write_notebook(nbpath=None)[source]

Write a jupyter notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook.

class abipy.abio.outputs.AbinitOutputFile(filepath)[source]

Bases: abipy.abio.outputs.AbinitTextFile, abipy.core.mixins.NotebookWriter

Class representing the main Abinit output file.

Inheritance Diagram

Inheritance diagram of AbinitOutputFile
initial_structures[source]

List of initial abipy.core.structure.Structure.

property has_same_initial_structures

True if all initial structures are equal.

final_structures[source]

List of final abipy.core.structure.Structure.

initial_structure[source]

The abipy.core.structure.Structure defined in the output file.

If the input file contains multiple datasets AND the datasets have different structures, this property returns None. In this case, one has to access the structure of the individual datasets. For example:

self.initial_structures[0]

gives the structure of the first dataset.

property has_same_final_structures

True if all initial structures are equal.

final_structure[source]

The abipy.core.structure.Structure defined in the output file.

If the input file contains multiple datasets AND the datasets have different structures, this property returns None. In this case, one has to access the structure of the individual datasets. For example:

self.final_structures[0]

gives the structure of the first dataset.

diff_datasets(dt_list1, dt_list2, with_params=True, differ='html', dryrun=False)[source]

Compare datasets

to_string(verbose=0)[source]

String representation.

get_dims_spginfo_dataframe(verbose=0)[source]

Parse the section with the dimensions of the calculation. Return Dataframe.

get_dims_spginfo_dataset(verbose=0)[source]

Parse the section with the dimensions of the calculation. Return dictionaries

Parameters

verbose – Verbosity level.

Return: (dims_dataset, spginfo_dataset)

where dims_dataset[i] is an OrderedDict with the dimensions of dataset i spginfo_dataset[i] is a dictionary with space group information.

next_gs_scf_cycle()[source]

Return the next GroundStateScfCycle in the file. None if not found.

get_all_gs_scf_cycles()[source]

Return list of GroundStateScfCycle objects. Empty list if no entry is found.

next_d2de_scf_cycle()[source]

Return D2DEScfCycle with information on the DFPT iterations. None if not found.

get_all_d2de_scf_cycles()[source]

Return list of D2DEScfCycle objects. Empty list if no entry is found.

plot(tight_layout=True, with_timer=False, show=True)[source]

Plot GS/DFPT SCF cycles and timer data found in the output file.

Parameters

with_timer – True if timer section should be plotted

yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user.

compare_gs_scf_cycles(others, show=True)[source]

Produce and returns a list of matplotlib figure comparing the GS self-consistent cycle in self with the ones in others.

Parameters
  • others – list of AbinitOutputFile objects or strings with paths to output files.

  • show – True to diplay plots.

compare_d2de_scf_cycles(others, show=True)[source]

Produce and returns a matplotlib figure comparing the DFPT self-consistent cycle in self with the ones in others.

Parameters
  • others – list of AbinitOutputFile objects or strings with paths to output files.

  • show – True to diplay plots.

get_panel()[source]

Build panel with widgets to interact with the Abinit output file either in a notebook or in panel app.

write_notebook(nbpath=None)[source]

Write a jupyter notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook.

abipy.abio.outputs.validate_output_parser(abitests_dir=None, output_files=None)[source]

Validate/test Abinit output parser.

Parameters
  • dirpath – Abinit tests directory.

  • output_files – List of Abinit output files.

Return: Exit code.

class abipy.abio.outputs.AboRobot(*args)[source]

Bases: abipy.abio.robots.Robot

This robot analyzes the results contained in multiple Abinit output files. Can compare dimensions, SCF cycles, analyze timers.

Inheritance Diagram

Inheritance diagram of AboRobot
EXT = 'abo'
get_dims_dataframe(with_time=True, index=None)[source]

Build and return pandas.DataFrame with the dimensions of the calculation.

Parameters
  • with_time – True if walltime and cputime should be added

  • index – Index of the dataframe. Use relative paths of files if None.

get_dataframe(with_geo=True, with_dims=True, abspath=False, funcs=None)[source]

Return a pandas.DataFrame with the most important results and the filenames as index.

Parameters
  • with_geo – True if structure info should be added to the dataframe

  • with_dims – True if dimensions should be added

  • abspath – True if paths in index should be absolute. Default: Relative to getcwd().

  • funcs – Function or list of functions to execute to add more data to the DataFrame. Each function receives a abipy.electrons.gsr.GsrFile object and returns a tuple (key, value) where key is a string with the name of column and value is the value to be inserted.

get_time_dataframe()[source]

Return a pandas.DataFrame with the wall-time, cpu time in seconds and the filenames as index.

yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user.

write_notebook(nbpath=None)[source]

Write a jupyter notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook.

class abipy.abio.outputs.OutNcFile(filepath)[source]

Bases: abipy.core.mixins.AbinitNcFile

Class representing the _OUT.nc file containing the dataset results produced at the end of the run. The netcdf variables can be accessed via instance attribute e.g. outfile.ecut. Provides integration with ipython.

params[source]

OrderedDict with parameters that might be subject to convergence studies.

close()[source]

Close the file.

get_allvars()[source]

Read all netcdf variables present in the file. Return dictionary varname –> value

robots Module

This module defines the Robot BaseClass. Robots operates on multiple files and provide helper functions to plot the data e.g. convergence studies and to build pandas dataframes from the output files.

class abipy.abio.robots.Robot(*args)[source]

Bases: abipy.core.mixins.NotebookWriter

This is the base class from which all Robot subclasses should derive. A Robot supports the with context manager:

Usage example:

with Robot([("label1", "file1"), (label2, "file2")]) as robot:
    # Do something with robot. files are automatically closed when we exit.
    for label, abifile in self.items():
        print(label)
start = None
classmethod get_supported_extensions()[source]

List of strings with extensions supported by Robot subclasses.

classmethod class_for_ext(ext)[source]

Return the Robot subclass associated to the given extension.

classmethod from_dir(top, walk=True, abspath=False)[source]

This class method builds a robot by scanning all files located within directory top. This method should be invoked with a concrete robot class, for example:

robot = GsrRobot.from_dir(“.”)

Parameters
  • top (str) – Root directory

  • walk – if True, directories inside top are included as well.

  • abspath – True if paths in index should be absolute. Default: Relative to top.

classmethod from_dirs(dirpaths, walk=True, abspath=False)[source]

Similar to from_dir but accepts a list of directories instead of a single directory.

Parameters
  • walk – if True, directories inside top are included as well.

  • abspath – True if paths in index should be absolute. Default: Relative to top.

classmethod from_dir_glob(pattern, walk=True, abspath=False)[source]

This class method builds a robot by scanning all files located within the directories matching pattern as implemented by glob.glob This method should be invoked with a concrete robot class, for example:

robot = GsrRobot.from_dir_glob(“flow_dir/w*/outdata/”)

Parameters
  • pattern – Pattern string

  • walk – if True, directories inside top are included as well.

  • abspath – True if paths in index should be absolute. Default: Relative to getcwd().

classmethod class_handles_filename(filename)[source]

True if robot class handles filename.

classmethod from_files(filenames, labels=None, abspath=False)[source]

Build a Robot from a list of filenames. if labels is None, labels are automatically generated from absolute paths.

Parameters

abspath – True if paths in index should be absolute. Default: Relative to top.

classmethod from_flow(flow, outdirs='all', nids=None, ext=None, task_class=None)[source]

Build a robot from a abipy.flowtk.flows.Flow object.

Parameters
  • flowabipy.flowtk.flows.Flow object

  • outdirs – String used to select/ignore the files in the output directory of flow, works and tasks outdirs=”work” selects only the outdir of the Works, outdirs=”flow+task” selects the outdir of the Flow and the outdirs of the tasks outdirs=”-work” excludes the outdir of the Works. Cannot use + and - flags in the same string. Default: all that is equivalent to “flow+work+task”

  • nids – List of node identifiers used to select particular nodes. Not used if None

  • ext – File extension associated to the robot. Mainly used if method is invoked with the BaseClass

  • task_class – Task class or string with the class name used to select the tasks in the flow. None implies no filtering.

Usage example:

with abilab.GsrRobot.from_flow(flow) as robot:
    print(robot)

# That is equivalent to:
with Robot.from_flow(flow, ext="GSR") as robot:
    print(robot)
Returns

Robot subclass.

add_extfile_of_node(node, nids=None, task_class=None)[source]

Add the file produced by this node to the robot.

Parameters
  • nodeabipy.flowtk.flows.Flow or abipy.flowtk.works.Work or abipy.flowtk.tasks.Task object.

  • nids – List of node identifiers used to select particular nodes. Not used if None

  • task_class – Task class or string with class name used to select the tasks in the flow. None implies no filtering.

scan_dir(top, walk=True)[source]

Scan directory tree starting from top. Add files to the robot instance.

Parameters
  • top (str) – Root directory

  • walk – if True, directories inside top are included as well.

Returns

Number of files found.

add_file(label, abifile, filter_abifile=None)[source]

Add a file to the robot with the given label.

Parameters
  • label – String used to identify the file (must be unique, ax exceptions is raised if label is already present.

  • abifile – Specify the file to be added. Accepts strings (filepath) or abipy file-like objects.

  • filter_abifile – Function that receives an abifile object and returns True if the file should be added to the plotter.

iter_lineopt()[source]

Generates matplotlib linestyles.

static ordered_intersection(list_1, list_2)[source]

Return ordered intersection of two lists. Items must be hashable.

pop_label(label)[source]

Remove file with the given label and close it.

change_labels(new_labels, dryrun=False)[source]

Change labels of the files.

Parameters
  • new_labels – List of strings (same length as self.abifiles)

  • dryrun – True to activate dryrun mode.

Returns

mapping new_label –> old_label.

remap_labels(function, dryrun=False)[source]

Change labels of the files by executing function

Parameters
  • function – Callable object e.g. lambda function. The output of function(abifile) is used as new label. Note that the function shall not return duplicated labels when applied to self.abifiles.

  • dryrun – True to activate dryrun mode.

Returns

mapping new_label –> old_label.

trim_paths(start=None)[source]

Replace absolute filepaths in the robot with relative paths wrt to start directory. If start is None, os.getcwd() is used. Set self.start attribute, return self.start.

property exceptions

List of exceptions.

keys()[source]
items()[source]
property labels
get_label_files_str()[source]

Return string with [label, filepath].

show_files(stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Show label –> file path

to_string(verbose=0)[source]

String representation.

property abifiles

List of netcdf files.

has_different_structures(rtol=1e-05, atol=1e-08)[source]

Check if structures are equivalent, return string with info about differences (if any).

is_sortable(aname, raise_exc=False)[source]

Return True if aname is an attribute of the netcdf file If raise_exc is True, AttributeError with an explicit message is raised.

sortby(func_or_string, reverse=False, unpack=False)[source]

Sort files in the robot by func_or_string.

Parameters
  • func_or_string – Either None, string, callable defining the quantity to be used for sorting. If string, it’s assumed that the abifile has an attribute with the same name and getattr is invoked. If callable, the output of func_or_string(abifile) is used. If None, no sorting is performed.

  • reverse – If set to True, then the list elements are sorted as if each comparison were reversed.

  • unpack – Return (labels, abifiles, params) if True

Return: list of (label, abifile, param) tuples where param is obtained via func_or_string.

or labels, abifiles, params if unpack

group_and_sortby(hue, func_or_string)[source]

Group files by hue and, inside each group` sort items by func_or_string.

Parameters
  • hue – Variable that define subsets of the data, which will be drawn on separate lines. Accepts callable or string If string, it’s assumed that the abifile has an attribute with the same name and getattr is invoked. Dot notation is also supported e.g. hue=”structure.formula” –> abifile.structure.formula If callable, the output of hue(abifile) is used.

  • func_or_string – Either None, string, callable defining the quantity to be used for sorting. If string, it’s assumed that the abifile has an attribute with the same name and getattr is invoked. If callable, the output of func_or_string(abifile) is used. If None, no sorting is performed.

Return: List of HueGroup instance.

close()[source]

Close all files that have been opened by the Robot.

static sortby_label(sortby, param)[source]

Return the label to be used when files are sorted with sortby.

get_structure_dataframes(abspath=False, filter_abifile=None, **kwargs)[source]

Wrap dataframes_from_structures function.

Parameters
  • abspath – True if paths in index should be absolute. Default: Relative to getcwd().

  • filter_abifile – Function that receives an abifile object and returns True if the file should be added to the plotter.

get_lattice_dataframe(**kwargs)[source]

Return pandas.DataFrame with lattice parameters.

get_coords_dataframe(**kwargs)[source]

Return pandas.DataFrame with atomic positions.

get_params_dataframe(abspath=False)[source]

Return pandas.DataFrame with the most important parameters. that are usually subject to convergence studies.

Parameters

abspath – True if paths in index should be absolute. Default: Relative to top.

static plot_xy_with_hue(data, x, y, hue, decimals=None, ax=None, xlims=None, ylims=None, fontsize=12, **kwargs)

Plot y = f(x) relation for different values of hue. Useful for convergence tests done wrt to two parameters.

Parameters
  • datapandas.DataFrame containing columns x, y, and hue.

  • x – Name of the column used as x-value

  • y – Name of the column(s) used as y-value

  • hue – Variable that define subsets of the data, which will be drawn on separate lines

  • decimals – Number of decimal places to round hue columns. Ignore if None

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • ylims (xlims) – Set the data limits for the x(y)-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used

  • fontsize – Legend fontsize.

  • kwargs – Keywork arguments are passed to ax.plot method.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_convergence(item, sortby=None, hue=None, ax=None, fontsize=8, **kwargs)[source]

Plot the convergence of item wrt the sortby parameter. Values can optionally be grouped by hue.

Parameters
  • item – Define the quantity to plot. Accepts callable or string If string, it’s assumed that the abifile has an attribute with the same name and getattr is invoked. Dot notation is also supported e.g. hue=”structure.formula” –> abifile.structure.formula If callable, the output of item(abifile) is used.

  • sortby – Define the convergence parameter, sort files and produce plot labels. Can be None, string or function. If None, no sorting is performed. If string and not empty it’s assumed that the abifile has an attribute with the same name and getattr is invoked. If callable, the output of sortby(abifile) is used.

  • hue – Variable that define subsets of the data, which will be drawn on separate lines. Accepts callable or string If string, it’s assumed that the abifile has an attribute with the same name and getattr is invoked. If callable, the output of hue(abifile) is used.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • fontsize – legend and label fontsize.

  • kwargs – keyword arguments passed to matplotlib plot method.

Returns: matplotlib.figure.Figure

Example

robot.plot_convergence(“energy”)

robot.plot_convergence(“energy”, sortby=”nkpt”)

robot.plot_convergence(“pressure”, sortby=”nkpt”, hue=”tsmear”)

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_convergence_items(items, sortby=None, hue=None, fontsize=6, **kwargs)[source]

Plot the convergence of a list of items wrt to the sortby parameter. Values can optionally be grouped by hue.

Parameters
  • items – List of attributes (or callables) to be analyzed.

  • sortby – Define the convergence parameter, sort files and produce plot labels. Can be None, string or function. If None, no sorting is performed. If string and not empty it’s assumed that the abifile has an attribute with the same name and getattr is invoked. If callable, the output of sortby(abifile) is used.

  • hue – Variable that define subsets of the data, which will be drawn on separate lines. Accepts callable or string If string, it’s assumed that the abifile has an attribute with the same name and getattr is invoked. Dot notation is also supported e.g. hue=”structure.formula” –> abifile.structure.formula If callable, the output of hue(abifile) is used.

  • fontsize – legend and label fontsize.

  • kwargs – keyword arguments are passed to ax.plot

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_lattice_convergence(what_list=None, sortby=None, hue=None, fontsize=8, **kwargs)[source]

Plot the convergence of the lattice parameters (a, b, c, alpha, beta, gamma). wrt the``sortby`` parameter. Values can optionally be grouped by hue.

Parameters
  • what_list – List of strings with the quantities to plot e.g. [“a”, “alpha”, “beta”]. None means all.

  • item – Define the quantity to plot. Accepts callable or string If string, it’s assumed that the abifile has an attribute with the same name and getattr is invoked. If callable, the output of item(abifile) is used.

  • sortby – Define the convergence parameter, sort files and produce plot labels. Can be None, string or function. If None, no sorting is performed. If string and not empty it’s assumed that the abifile has an attribute with the same name and getattr is invoked. If callable, the output of sortby(abifile) is used.

  • hue – Variable that define subsets of the data, which will be drawn on separate lines. Accepts callable or string If string, it’s assumed that the abifile has an attribute with the same name and getattr is invoked. Dot notation is also supported e.g. hue=”structure.formula” –> abifile.structure.formula If callable, the output of hue(abifile) is used.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • fontsize – legend and label fontsize.

Returns: matplotlib.figure.Figure

Example

robot.plot_lattice_convergence()

robot.plot_lattice_convergence(sortby=”nkpt”)

robot.plot_lattice_convergence(sortby=”nkpt”, hue=”tsmear”)

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

get_baserobot_code_cells(title=None)[source]

Return list of jupyter cells with calls to methods provided by the base class.

class abipy.abio.robots.HueGroup(hvalue, xvalues, abifiles, labels)[source]

Bases: object

This small object is used by group_and_sortby to store information abouth the group.

timer Module

This module provides objects for extracting timing data from the ABINIT output files It also provides tools to analyze and to visualize the parallel efficiency.

class abipy.abio.timer.AbinitTimerParser[source]

Bases: pymatgen.io.abinit.abitimer.AbinitTimerParser, abipy.core.mixins.NotebookWriter

yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user.

write_notebook(nbpath=None)[source]

Write an ipython notebook to nbpath. If nbpath is None, a temporary file in the current working directory is created. Return path to the notebook.

variable Module

class abipy.abio.variable.InputVariable(name, value, units='', valperline=3)[source]

Bases: object

An Abinit input variable.

get_value()[source]

Return the value.

property name
property basename

Return the name trimmed of any dataset index.

property dataset

Return the dataset index in string form.

property units

Return the units.

format_scalar(val, floatdecimal=0)[source]

Format a single numerical value into a string with the appropriate number of decimal.

format_list2d(values, floatdecimal=0)[source]

Format a list of lists.

format_list(values, floatdecimal=0)[source]

Format a list of values into a string. The result might be spread among several lines.