abipy.ml package

Submodules

abipy.ml.aseml module

Objects to perform ASE calculations with machine-learned potentials.

class abipy.ml.aseml.RX_MODE(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: EnumMixin, StrEnum

Relaxation mode string flags.

no = 'no'
ions = 'ions'
cell = 'cell'
abipy.ml.aseml.get_atoms(obj)[source]

Return ASE Atoms from object.

Return type:

Atoms

abipy.ml.aseml.abisanitize_atoms(atoms, **kwargs)[source]

Call abisanitize, return new Atoms instance.

Return type:

Atoms

abipy.ml.aseml.fix_atoms(atoms, fix_inds=None, fix_symbols=None)[source]

Fix atoms by indices and/or by symbols.

Parameters:
  • atoms (Atoms) – ASE atoms

  • fix_inds (list[int] | None) – List of site indices to fix. None to ignore constraint.

  • fix_symbols (list[str] | None) – List of chemical elements to fix. None to ignore the constraint.

Return type:

None

abipy.ml.aseml.write_atoms(atoms, workdir, verbose, formats=None, prefix=None, postfix=None)[source]

Write atoms to file(s), return list with (Path, fmt) tuples.

Parameters:
  • atoms (Atoms) – ASE atoms

  • workdir – Working directory.

  • verbose (int) – Verbosity level.

  • formats – List of strings with file formats. If None all known formats are used.

  • prefix – String to be prepended to filenames.

Return type:

list[tuple[Path, str]]

abipy.ml.aseml.print_atoms(atoms, title=None, cart_forces=None, stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]

Print atoms object to stream.

Parameters:
  • atoms (Atoms) – ASE atoms.

  • title – Optional string with the title.

  • cart_forces – np.array with cart_forces to print.

  • stream – Output stream

Return type:

None

abipy.ml.aseml.diff_two_structures(label1, structure1, label2, structure2, fmt, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]

Diff two structures using format fmt`and print results to `file.

class abipy.ml.aseml.AseTrajectoryPlotter(traj)[source]

Bases: object

Plot an ASE trajectory with matplotlib.

classmethod from_file(filepath)[source]

Initialize an instance from file filepath

Return type:

AseTrajectoryPlotter

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

plot(fontsize=8, xlims=None, marker='o', **kwargs)[source]

Plot energies, force stats, and pressure as a function of the trajectory index.

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.

plotly

Try to convert mpl figure to plotly.

Return type:

Any

plot_lattice(ax_list=None, fontsize=8, marker='o', xlims=None, **kwargs)[source]

Plot lattice lengths/angles/volume as a function the of the trajectory index.

Parameters:
  • ax_list – List of axis or None if a new figure should be created.

  • fontsize – fontsize for legends and titles

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

Return type:

Any

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.

plotly

Try to convert mpl figure to plotly.

abipy.ml.aseml.get_fstats(cart_forces)[source]

Return dictionary with statistics on the Cartesian forces.

Return type:

dict

class abipy.ml.aseml.AseResults(atoms, ene, stress, forces, magmoms)[source]

Bases: HasPickleIO

Container with the results produced by an ASE calculator.

atoms: Atoms
ene: float
stress: ndarray
forces: ndarray
magmoms: ndarray
classmethod from_traj_inds(trajectory, *inds)[source]

Build list of AseResults from a trajectory and list of indices.

Return type:

list[AseResults]

classmethod from_atoms(atoms, calc=None, with_stress=True, with_magmoms=True)[source]

Build the object from an atoms instance with a calculator.

Return type:

AseResults

property pressure: float
get_voigt_stress()[source]

xx, yy, zz, yz, xz, xy

property volume: float

Volume of the unit cell in Ang^3.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

get_fstats()[source]

Return dictionary with statistics on forces.

Return type:

dict

get_dict4pandas(with_geo=True, with_fstats=True)[source]

Dictionary with results used to build pandas dataframe.

Return type:

dict

abipy.ml.aseml.zip_sort(xs, ys)[source]
abipy.ml.aseml.diff_stats(xs, ys)[source]
class abipy.ml.aseml.AseResultsComparator(structure, keys, ene_list, forces_list, stress_list)[source]

Bases: HasPickleIO

This object allows one to compare energies, forces and stresses computed for the same structure but with different methods e.g. results obtained with different ML potentials.

ALL_VOIGT_COMPS = ['xx', 'yy', 'zz', 'yz', 'xz', 'xy']
classmethod from_ase_results(keys, results_list)[source]

Build object from list of keys and list of AseResults.

nsteps()[source]

Number of steps in the trajectory.

natom()[source]

Number of atoms.

pickle_dump_and_write_script(workdir)[source]

Write pickle file for object persistence and python script.

Return type:

None

get_key_pairs()[source]

Return list with (key_ref, key) tuple.

Return type:

list[tuple]

inds_of_keys(key1, key2)[source]

Tuple with the indices of key1, key2

Return type:

tuple[int, int]

idir_from_direction(direction)[source]

Index from direction string.

Return type:

int

ivoigt_from_comp(voigt_comp)[source]
Return type:

int

get_aligned_energies_traj(istep=-1)[source]

Return energies in eV aligned with respect to self.iref key. Use the energy at the istep step index.

Return type:

ndarray

xy_energies_for_keys(key1, key2, sort=True)[source]

Return (xs, ys) sorted arrays with aligned energies for (key1, key2).

Return type:

tuple

xy_forces_for_keys(key1, key2, direction, symbol=None, site_inds=None)[source]

Return (xs, ys), sorted arrays with forces along the cart direction for (key1, key2).

Parameters:
  • symbol – If not None, select only forces for this atomic specie.

  • site_inds – List of site indices to consider. None if all sites should be included.

Return type:

tuple

traj_forces_for_keys(key1, key2)[source]

Return arrays with the cart direction of forces along the trajectory for (key1, key2).

Return type:

tuple

xy_stress_for_keys(key1, key2, voigt_comp, sort=True)[source]

Return xs, ys sorted arrays with the stress along the voigt component for (key1, key2).

Return type:

tuple

get_forces_dataframe()[source]

Return dataFrame with columns (fx, fy, fz, isite, istep, key)

Return type:

DataFrame

get_stress_dataframe()[source]

Return DataFrame with columns [sxx,syy,szz, … ,istep,key]

Return type:

DataFrame

plot_energies(fontsize=8, **kwargs)[source]

Compare energies aligned wrt to self.iref entry

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.

plotly

Try to convert mpl figure to plotly.

Return type:

Any

plot_forces(symbol=None, site_inds=None, fontsize=8, **kwargs)[source]

Parity plot for forces.

Parameters:
  • symbol – If not None, select only forces for this atomic specie.

  • site_inds – List of site indices to consider. None if all sites should be included.

Return type:

Any

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.

plotly

Try to convert mpl figure to plotly.

plot_stresses(fontsize=6, **kwargs)[source]

Compare stress components.

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.

plotly

Try to convert mpl figure to plotly.

Return type:

Any

plot_energies_traj(delta_mode=True, fontsize=6, markersize=2, **kwargs)[source]

Plot energies along the trajectory.

Parameters:

delta_mode – True to plot differences instead of absolute values.

Return type:

Any

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.

plotly

Try to convert mpl figure to plotly.

plot_forces_traj(delta_mode=True, symbol=None, fontsize=6, markersize=2, **kwargs)[source]

Plot forces along the trajectory.

Parameters:
  • delta_mode – True to plot differences instead of absolute values.

  • symbol – If not None, select only forces for this atomic species

Return type:

Any

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.

plotly

Try to convert mpl figure to plotly.

plot_stress_traj(delta_mode=True, markersize=2, fontsize=6, **kwargs)[source]

Plot stresses along the trajectory.

Parameters:

delta_mode – True to plot differences instead of absolute values.

Return type:

Any

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.

plotly

Try to convert mpl figure to plotly.

class abipy.ml.aseml.AseRelaxation(dyn, r0, r1, traj_path)[source]

Bases: object

Container with the results produced by the ASE calculator.

traj()[source]

ASE trajectory.

to_string(verbose=0)[source]

String representation with verbosity level verbose

Return type:

str

summarize(tags=None, mode='smart', stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]
abipy.ml.aseml.dataframe_from_results_list(index, results_list, mode='smart')[source]
Return type:

DataFrame

abipy.ml.aseml.ase_optimizer_cls(s)[source]

Return an ASE Optimizer subclass from string s. If s == “__all__”, return list with all Optimizer subclasses supported by ASE.

Return type:

Union[Type, list[str]]

abipy.ml.aseml.relax_atoms(atoms, relax_mode, optimizer, fmax, pressure, verbose, steps=500, opt_kwargs=None, traj_path=None, calculator=None)[source]

Relax atoms using an ASE calculator and ASE algorithms.

Parameters:
  • atoms (Atoms) – ASE atoms.

  • relax_mode (str) – “ions” to relax ions only, “cell” for ions + cell, “no” for no relaxation.

  • optimizer (str) – name of the ASE optimizer to use for relaxation.

  • fmax (float) – tolerance for relaxation convergence. Here fmax is a sum of force and stress forces.

  • pressure (float) – Target pressure in GPa.

  • verbose (int) – whether to print stdout.

  • steps (int) – max number of steps for relaxation.

  • opt_kwargs (dict) – kwargs for the ASE optimizer class.

  • traj_path

  • calculator

Return type:

AseRelaxation

abipy.ml.aseml.silence_tensorflow()[source]

Silence every unnecessary warning from tensorflow.

Return type:

None

class abipy.ml.aseml.CORRALGO(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntEnum

Enumerate the different algorithms used to correct the ML forces/stresses.

none = 0
delta = 1
one_point = 2
classmethod from_string(string)[source]

Build instance from string.

abipy.ml.aseml.as_calculator(obj)[source]

Build an ASE calculator.

Return type:

Calculator

abipy.ml.aseml.find_spec_nn()[source]
Return type:

list[str]

abipy.ml.aseml.get_installed_nn_names(verbose=0, printout=True)[source]

Return list of strings with the names of the nn potentials installed in the environment

Return type:

tuple[list[str], list[str]]

abipy.ml.aseml.install_nn_names(nn_names='all', update=False, verbose=0)[source]

Install NN potentials in the environment using pip.

Parameters:
  • nn_names – List of NN potentisl to install.

  • update – True if packages should be updated.

  • verbose – Verbosity level.

Return type:

None

class abipy.ml.aseml.CalcBuilder(name, dftd3_args=None, **kwargs)[source]

Bases: object

Factory class to build an ASE calculator with a ML potential as backend. Supports different backends defined by name string. Possible formats are:

  1. nn_type e.g. m3gnet. See ALL_NN_TYPES for available keys.

  2. nn_type:model_name

  3. nn_type@model_path e.g.: mace:FILEPATH

  4. nn_type@calc_kwargs.yaml e.g.: mace:calc_kwargs.yaml.

ALL_NN_TYPES = ['emt', 'm3gnet', 'matgl', 'chgnet', 'alignn', 'mace', 'mace_mp', 'pyace', 'nequip', 'metatensor', 'deepmd', 'orb', 'sevenn', 'mattersim']
reset()[source]
Return type:

None

get_calculator(with_delta=True, reset=False)[source]

Return an ASE calculator with ML potential.

Parameters:
  • with_delta (bool) – False if the calculator should not include delta corrections.

  • reset (bool) – True if the internal cache for the model should be reset.

Return type:

Calculator

class abipy.ml.aseml.MlBase(workdir, prefix=None, exist_ok=False, fig_ext='.pdf')[source]

Bases: HasPickleIO

Base class for all Ml subclasses providing helper methods to perform typical tasks such as writing files in the workdir and object persistence via pickle.

add_basename_info(basename, info)[source]

Register basename with info in the internal buffer used to generate the README.md file in _finalize. Print WARNING if basename is already registered.

Return type:

None

mkdir(basename, info)[source]

Create directory in workdir, return Path object.

Return type:

Path

rmtree()[source]

Remove workdir.

Return type:

None

get_path(basename, info)[source]

Return Path in workdir.

Return type:

Path

savefig(basename, fig, info)[source]

Save matplotlib figure in workdir.

Return type:

None

write_traj(basename, traj, info)[source]

Write ASE trajectory in workdir.

Return type:

None

write_json(basename, data, info, indent=4, stream=None, **kwargs)[source]

Write data in JSON format and mirror output to stream.

Return type:

None

write_df(df, basename, info, fmt='csv')[source]

Write dataframe to file.

Return type:

None

write_script(basename, text, info)[source]

Write text script to basename file.

Return type:

Path

class abipy.ml.aseml.MlRelaxer(atoms, relax_mode, fmax, pressure, steps, optimizer, nn_name, verbose, workdir, prefix=None)[source]

Bases: MlBase

Relax a structure with ASE and ML-potential.

classmethod from_abinit_yaml_file(filepath, workdir=None, prefix=None)[source]

Build object from a YAML file produced by ABINIT in hybrid relaxation mode.

Return type:

MlRelaxer

write_output_file_for_abinit()[source]

Write output file with results in a format that can be parsed by ABINIT. Return path to the output file.

Return type:

Path

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

run()[source]

Run structural relaxation.

abipy.ml.aseml.restart_md(traj_filepath, atoms, verbose)[source]

Try to restart a MD run from an existent trajectory file. Return: (restart_bool, len_traj)

Return type:

tuple[bool, int]

class abipy.ml.aseml.AseMdLog(filepath)[source]

Bases: TextFile

Postprocessing tool for the log file produced by ASE MD.

Inheritance Diagram

Inheritance diagram of AseMdLog
time_key = 'Time[ps]'
df()[source]

DataFrame with the results.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

plot(**kwargs)[source]

Plot all the keys in the dataframe.

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.

plotly

Try to convert mpl figure to plotly.

Return type:

Any

histplot(**kwargs)[source]

Histogram plot.

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.

plotly

Try to convert mpl figure to plotly.

Return type:

Any

yield_figs(**kwargs)[source]

Generate a predefined list of matplotlib figures with minimal input from the user.

class abipy.ml.aseml.MlMd(atoms, temperature, pressure, timestep, steps, loginterval, ensemble, nn_name, verbose, workdir, prefix=None)[source]

Bases: MlBase

Perform MD calculations with ASE and ML potential.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

run()[source]

Run MD

Return type:

None

class abipy.ml.aseml.MlRelaxerFromMdTraj(traj_filepath, relax_mode, fmax, pressure, steps, optimizer, nn_name, verbose, workdir, prefix=None)[source]

Bases: MlBase

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

run()[source]

Run structural relaxation for selected configurations.

class abipy.ml.aseml.MlGsList(atoms_list, nn_name, verbose, workdir, prefix=None)[source]

Bases: _MlNebBase

Perform ground-state calculations for a list of atoms with ASE and ML-potential. Inherits from _MlNebBase so that we can reuse postprocess_images and read_neb_data.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

run()[source]

Run list of GS calculations.

Return type:

None

class abipy.ml.aseml.MlNeb(initial_atoms, final_atoms, nimages, neb_method, climb, optimizer, relax_mode, fmax, pressure, nn_name, verbose, workdir, prefix=None)[source]

Bases: _MlNebBase

Perform NEB calculation with ASE and ML potential.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

run()[source]

Run NEB

Return type:

None

class abipy.ml.aseml.MultiMlNeb(atoms_list, nimages, neb_method, climb, optimizer, relax_mode, fmax, pressure, nn_name, verbose, workdir, prefix=None)[source]

Bases: _MlNebBase

Perform a multi-NEB calculation with ASE and ML potential.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

run()[source]

Run multi NEB calculations.

Return type:

None

abipy.ml.aseml.make_ase_neb(initial, final, nimages, calculators, neb_method, climb, method='linear', mic=False)[source]

Make a NEB band consisting of nimages. See https://databases.fysik.dtu.dk/ase/ase/neb.html

Parameters:
  • initial (Atoms) – First point.

  • final (Atoms) – Last point.

  • nimages (int) – Number of images.

  • calculators (list) – List of ASE calculators.

  • neb_method (str) – String defining NEB algorithm.

  • climb (bool) – True to use a climbing image.

  • method – str Method by which to interpolate: ‘linear’ or ‘idpp’. linear provides a standard straight-line interpolation, while idpp uses an image-dependent pair potential.

  • mic – Map movement into the unit cell by using the minimum image convention.

Return type:

NEB

class abipy.ml.aseml.MlOrderer(structure, max_ns, optimizer, relax_mode, fmax, pressure, steps, nn_name, verbose, workdir, prefix=None)[source]

Bases: MlBase

Order a disordered structure using pymatgen and ML potential.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

run()[source]

Run MlOrderer.

Return type:

None

class abipy.ml.aseml.MlValidateWithAbinitio(filepaths, nn_names, traj_range, verbose, workdir, prefix=None)[source]

Bases: _MlNebBase

Compare ab-initio energies, forces and stresses with ML results.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

get_abinitio_results()[source]
Return type:

list[AseResults]

run(nprocs, print_dataframes=True)[source]

Run calculation with nprocs processes.

Return type:

AseResultsComparator

class abipy.ml.aseml.MolecularDynamics(atoms, ensemble='nvt', temperature=300, timestep=1.0, pressure=6.324209121801212e-07, taut=None, taup=None, compressibility_au=None, trajectory=None, logfile=None, loginterval=1, append_trajectory=False)[source]

Bases: object

Molecular dynamics class Based on https://github.com/materialsvirtuallab/m3gnet/blob/main/m3gnet/models/_dynamics.py

run(steps)[source]

Thin wrapper of ase MD run.

Parameters:

steps (int) – number of MD steps

class abipy.ml.aseml.GsMl(atoms, nn_name, verbose, workdir, prefix=None)[source]

Bases: MlBase

Single point calculation of energy, forces and stress with ML potential.

run()[source]

Run the calculation.

class abipy.ml.aseml.MlEos(atoms, vol_scales, relax_mode, fmax, pressure, steps, optimizer, nn_name, verbose, workdir, prefix=None)[source]

Bases: MlBase

Compute the equation of state E(V) for a given structure with ASE and ML-potential.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

run()[source]

Run structural relaxation.

class abipy.ml.aseml.FrozenPhononMl(structure, qpoint, phdispl_cart, eta_list, nn_name, verbose, workdir, prefix=None)[source]

Bases: MlBase

Frozen-phonon calculation with ML potential.

classmethod from_ddb_file(ddb_filepath, qpoint, eta_list, nn_name, verbose, workdir, prefix=None, **anaddb_kwargs)[source]

Initialize an instance from a DDB file and a q-point.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

run(select_imodes=None)[source]

Run the calculation.

class abipy.ml.aseml.MlCompareNNs(atoms, nn_names, num_tests, rattle, stdev_rvol, verbose, workdir, prefix=None)[source]

Bases: MlBase

Compare energies, forces and stresses obtained with different ML potentials. Also profile the time required.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

run(print_dataframes=True)[source]

Run calculations.

Return type:

AseResultsComparator

class abipy.ml.aseml.MlCwfEos(elements, nn_names, verbose, workdir, prefix=None)[source]

Bases: MlBase

Compute EOS with different ML potentials.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

run()[source]
run_nn_name_set_name(nn_name, set_name)[source]
Return type:

dict

abipy.ml.extxyz_generator module

Tools to read data from output files generated by ab-initio codes and generate extended XYZ files.

class abipy.ml.extxyz_generator.ExtxyzIOWriter(filepaths)[source]

Bases: object

This object converts output files produced by ab-initio codes such as ABINIT or VASP to extended XYZ files that can be used to train ML models.

Example

# To find all the vasprun.xml files starting from a top-level directory, use:

xyz_writer = ExtxyzIOWriter.from_top(“.”, “vasprun.xml”) print(xyz_writer) xyz_writer.write(“foo.xyz”)

# A similar syntax can be used for Abinit GSR files:

ExtxyzIOWriter.from_top(“.”, “GSR.nc”).write(“foo.xyz”)

# To specify an explicit list of files, use:

xyz_writer = ExtxyzIOWriter([“dir1/vasprun.xml”, “dir2/vasprun.xml”]) xyz_writer.write(“foo.xyz”)

SUPPORTED_EXTS = ['vasprun.xml', 'GSR.nc', 'HIST.nc']
classmethod from_top_vasprun(top)[source]

Find all the vasprun.xml files starting from the top-level directory top.

classmethod from_top_hist(top)[source]

Find all the HIST.nc files starting from the top-level directory top.

classmethod from_top_gsr(top)[source]

Find all the GSR.nc files starting from the top-level directory top.

classmethod from_top(top, ext)[source]

Scan for files with extension ext starting from the top directory top.

to_string(verbose=0)[source]

String representation with verbosiy level verbose.

Return type:

str

write(xyz_filepath, traj_range=None, overwrite=False)[source]

Write data to xyz_filepath.

Parameters:
  • xyz_filepath (str | PathLike) – Filename

  • traj_range – Range object to select configurations. If None, only the last configuration is used.

  • overwrite (bool) – True to allow overwriting.

Return type:

None

yield_atoms_filepath(filepath, traj_range)[source]

Generate ASE atoms.

Parameters:
  • filepath – Filename

  • traj_range – Range object to select configurations. If None, only the last configuration is used.

abipy.ml.extxyz_generator.check_vasp_success(vasprun, outcar, verbose=1)[source]

Check if a VASP calculation completed successfully.

Returns: True if the calculation completed successfully, False otherwise.

Return type:

bool

abipy.ml.ml_phonopy module

Classes to compute vibrational properties with phonopy and ML potentials.

abipy.ml.ml_phonopy.cprint_traceback(color='red')[source]

Print traceback.

Return type:

None

abipy.ml.ml_phonopy.get_phonopy(structure, supercell_matrix, calculator, distance=0.01, primitive_matrix=None, remove_drift=True)[source]

Build and return a Phonopy instance.

Parameters:
  • structure (Structure) – Structure object.

  • supercell_matrix – Supercell matrix.

  • calculator (Calculator) – ASE calculator to be attached to the atoms.

  • distance – Distance of finite displacements in Angstrom.

  • primitive_matrix

  • remove_drift – True if the drift in the forces should be removed.

Return type:

Phonopy

Based on a similar implementation available at: https://github.com/modl-uclouvain/randomcarbon/blob/main/randomcarbon/run/phonon.py

class abipy.ml.ml_phonopy.MlPhonopyWithDDB(ddb_filepath, distance, asr, dipdip, line_density, qppa, relax_mode, fmax, pressure, steps, optimizer, nn_names, verbose, workdir, prefix=None, supercell=None)[source]

Bases: MlBase

Compute phonons with phonopy and a ML potential starting from a DDB file and compare the results.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

run()[source]

Run MlPhonopyWithDDB.

Return type:

None

class abipy.ml.ml_phonopy.MlPhonopy(structure, supercell, distance, line_density, qppa, relax_mode, fmax, pressure, steps, optimizer, nn_names, verbose, workdir, prefix=None)[source]

Bases: MlBase

Compute phonons with phonopy and a ML potential.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

run()[source]

Run calculation.

Return type:

None

class abipy.ml.ml_phonopy.MlVZSISAQHAPhonopy(structure, bo_vol_scales, supercell, distance, line_density, qppa, relax_mode, fmax, pressure, steps, optimizer, nn_name, verbose, workdir, prefix=None)[source]

Bases: MlBase

Perform a VZSISA QHA calculation with phonopy and a ML potential.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

run()[source]

Run calculation

Return type:

None

abipy.ml.ml_relax module

class abipy.ml.ml_relax.RelaxationProfiler(atoms, pseudos, corr_algo, algorithm, xc_name, kppa, relax_mode, fmax, mpi_nprocs, steps=500, verbose=0, optimizer='BFGS', nn_name='chgnet', mpi_runner='mpirun')[source]

Bases: object

ml_relax_opt(directory)[source]

Relax structure with ML potential only. Return ASE optimizer.

abi_relax_atoms(directory, atoms=None, header='Begin ABINIT relaxation')[source]

Relax structure with ABINIT. Return namedtuple with results.

abi_relax_atoms_with_ase(directory, header='Begin ABINIT+ASE relaxation')[source]

Relax structure with ABINIT. Return ASE Optimizer

abinit_run_gs_atoms(directory, atoms)[source]

Perform a GS calculation with ABINIT. Return namedtuple with results in ASE units.

run(workdir=None, prefix=None)[source]

Run the different steps of the benchmark.

abipy.ml.neb module

abipy.ml.relax_scanner module

Objects to perform ASE calculations with machine-learning potentials.

abipy.ml.relax_scanner.nprocs_for_ntasks(nprocs, ntasks, title=None)[source]

Return the number of procs to be used in a multiprocessing Pool. If negative or None, use all procs in the system.

Return type:

int

class abipy.ml.relax_scanner.Entry(isite, structure, energy, forces)[source]

Bases: object

Stores the relaxed structure with the associated energy and the Cartesian forces.

isite: int
structure: Structure
energy: float
forces: ndarray
classmethod from_atoms_and_calculator(isite, atoms, calculator)[source]

Build an Entry from an Atoms object by attaching a calculator to compute energy and forces at fixed geometry.

Return type:

Entry

classmethod from_traj(isite, traj)[source]

Build an Entry by taking the last Atoms object from an ASE trajectory.

Return type:

Entry

class abipy.ml.relax_scanner.Pair(index1, index2, ediff, dist, frac_coords1, frac_coords2)[source]

Bases: object

Stores info on a possible transition between two relaxed configurations.

index1: int
index2: int
ediff: float
dist: float
frac_coords1: ndarray
frac_coords2: ndarray
get_dict4pandas()[source]

Useful to construct pandas DataFrames

Return type:

dict

class abipy.ml.relax_scanner.RelaxScanner(structure, isite, mesh, nn_name, relax_mode='ions', fmax=0.001, steps=500, verbose=0, optimizer_name='BFGS', pressure=0.0, workdir=None, prefix=None)[source]

Bases: HasPickleIO

This object employs an ASE calculator to perform many structural relaxations in which the initial configurations are obtained by displacing or inserting an atom on a grid covering the unit cell. The relaxed configurations are then compared with each other and only the unique solutions (Entry objects) are kept and stored to disk in pickle format.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

Return type:

str

get_atoms_with_frac_coords(frac_coords, with_fixed_atoms=True)[source]

Return Atoms instance with frac_coords at site index isite. By default, Fixed Contraints are applied to all atoms except isite.

Return type:

Atoms

get_structure_with_two_frac_coords(frac_coords1, frac_coords2)[source]

Return Structure instance with frac_coords at site index isite.

Return type:

Structure

run_start_count(start, count)[source]

Invoke ASE to relax count structures starting from index start. Stores unique results in an internal list and save results to file in pickle format. Return Path to the directory with the results.

Parameters:
  • start (int) – Index of initial structure.

  • count (int) – Number of structures to relax. If < 0, all structures are considered.

Return type:

Path

run(nprocs)[source]

Main entry point for client code. Run relaxations using a multiprocessing Pool with nprocs processors. If nprocs is None or negative, the total number of CPUs in the system is used.

Return type:

None

class abipy.ml.relax_scanner.RelaxScannerAnalyzer(entries, scanner, verbose=0)[source]

Bases: object

Analyze the results produced by RelaxScanner. The object is usually constructed by calling from_topdir:

Example

from abipy.ml.relax_scanner import RelaxScannerAnalyzer rsa = RelaxScannerAnalyzer.from_topdir(“.”)

print_dataframe(rsa.df) rsa.histplot() rsa.pairs_enediff_dist(ediff_tol=1e-3, dist_tol=3.5, neb_method=None)

classmethod from_topdir(topdir)[source]

Merge all entries starting from directory topdir.

Return type:

RelaxScannerAnalyzer

has_vasp_inputs()[source]

Return True if all the input files required to run VASP exist.

Return type:

bool

property workdir
df()[source]

Dataframe with the total energy in eV and the relaxed coordinates of the atomic site that has been relaxed.

to_string(verbose=0)[source]
Return type:

str

lattice()[source]
pairs_enediff_dist(ediff_tol=0.001, dist_tol=3.5, neb_method=None, nprocs=-1)[source]

Find pairs (i.e. relaxed configurations) that differ in energy less than ediff_tol and with relaxed sites that are less than dist_tol Angstrom apart (minimum-image convention is applied).

Parameters:
  • ediff_tol – Energy difference in eV. Tuple for range, scalar for max value.

  • dist_tol – Tolerance on site distance in Ang. Tuple for range, scalar for max value.

  • neb_method – None to print pairs only, “static” to compute energy profile along static path or ASE neb method to perform NEB calculation.

  • nprocs – Number of processes for Multiprocessing parallelism.

Return type:

list[Pair]

Return: list of Pair objects.

run_pair(pair, neb_method='static', nimages=14, climb=False)[source]

Perform NEB calculation for the given pair. Return dictionary with results. NB: Contraints are enforced during the NEB.

Parameters:
  • pair (Pair) – Info on Pair.

  • neb_method – One of the NEB methods implemented by ASE e.g. “aseneb” or “static” to compute total energies along a static path.

  • nimages – Number of images

  • climb – True to use climbing images.

Return type:

dict

histplot(ax=None, **kwargs)[source]

Plot histogram to show energy distribution.

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.

plotly

Try to convert mpl figure to plotly.

abipy.ml.tools module

Low-level tools used in abipy.ml module

abipy.ml.tools.get_energy_step(step)[source]

Copied from final_energy property in vasp.outputs.

Addresses a bug in vasprun.xml. See https://www.vasp.at/forum/viewtopic.php?f=3&t=16942

Return type:

float

abipy.ml.tools.get_structures_labels_from_file(filepath)[source]

Read energies, forces, stresses and magmoms from an external file. Return list of structures and dict with results.

Return type:

tuple[list[Structure], dict]

abipy.ml.tools.get_structures_labels_from_files(filepaths)[source]

Read energies, forces, stresses and magmoms from an external file. Return list of structures and dict with results.

Return type:

tuple[list[Structure], dict]