ml Package

ml Package

ml Package

aseml Package

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.to_ase_atoms(structure: Structure, calc=None) Atoms[source]

Convert pymatgen structure to ASE atoms. Optionally, attach a calculator.

abipy.ml.aseml.get_atoms(obj: Any) Atoms[source]

Return ASE Atoms from object.

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

Call abisanitize, return new Atoms instance.

abipy.ml.aseml.fix_atoms(atoms: Atoms, fix_inds: list[int] | None = None, fix_symbols: list[str] | None = None) None[source]

Fix atoms by indices and/or by symbols.

Parameters:
  • atoms – ASE atoms

  • fix_inds – List of site indices to fix. None to ignore constraint.

  • fix_symbols – List of chemical elements to fix. None to ignore the constraint.

abipy.ml.aseml.write_atoms(atoms: Atoms, workdir, verbose: int, formats=None, prefix=None, postfix=None) list[tuple[Path, str]][source]

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

Parameters:
  • atoms – ASE atoms

  • workdir – Working directory.

  • verbose – Verbosity level.

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

  • prefix – String to be prepended to filenames.

  • prefix – String to be appended to filenames.

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

Print atoms object to stream.

Parameters:
  • atoms – ASE atoms.

  • title – Optional string with the title.

  • cart_forces – np.array with cart_forces to print.

  • stream – Output stream

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: Trajectory)[source]

Bases: object

Plot an ASE trajectory with matplotlib.

classmethod from_file(filepath: str | PathLike) AseTrajectoryPlotter[source]

Initialize an instance from file filepath

to_string(verbose=0) str[source]

String representation with verbosity level verbose.

plot(fontsize=8, xlims=None, **kwargs) Any[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.

plot_lattice(ax_list=None, fontsize=8, xlims=None, **kwargs) Any[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.

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: ndarray) dict[source]

Return dictionary with statistics on the Cartesian forces.

class abipy.ml.aseml.AseResults(atoms: Atoms, ene: float, stress: ndarray, forces: ndarray, magmoms: ndarray)[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: Trajectory, *inds) AseResults[source]

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

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

Build the object from an atoms instance with a calculator.

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: int = 0) str[source]

String representation with verbosity level verbose.

get_fstats() dict[source]

Return dictionary with statistics on forces.

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

Dictionary with results used to build pandas dataframe.

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: list[str], results_list: list[list[AseResults]])[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: str | PathLike) None[source]

Write pickle file for object persistence and python script.

get_key_pairs() list[tuple][source]

Return list with (key_ref, key) tuple.

inds_of_keys(key1: str, key2: str) tuple[int, int][source]

Tuple with the indices of key1, key2

idir_from_direction(direction: str) int[source]

Index from direction string.

ivoigt_from_comp(voigt_comp: str) int[source]
get_aligned_energies_traj(istep=-1) ndarray[source]

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

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

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

xy_forces_for_keys(key1, key2, direction, symbol=None, site_inds=None) tuple[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.

traj_forces_for_keys(key1, key2) tuple[source]

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

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

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

get_forces_dataframe() DataFrame[source]

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

get_stress_dataframe() DataFrame[source]

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

plot_energies(fontsize=8, **kwargs) Any[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.

plot_forces(symbol=None, site_inds=None, fontsize=8, **kwargs) Any[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.

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) Any[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.

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

Plot energies along the trajectory.

Parameters:

delta_mode – True to plot differences instead of absolute values.

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) Any[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

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) Any[source]

Plot stresses along the trajectory.

Parameters:

delta_mode – True to plot differences instead of absolute values.

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: int = 0) str[source]

String representation with verbosity level verbose

summarize(tags=None, mode='smart', stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]
abipy.ml.aseml.dataframe_from_results_list(index: list, results_list: list[AseResults], mode='smart') DataFrame[source]
abipy.ml.aseml.ase_optimizer_cls(s: str | Optimizer) Type | list[str][source]

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

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

Relax atoms using an ASE calculator and ASE algorithms.

Parameters:
  • atoms – ASE atoms.

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

  • optimizer – name of the ASE optimizer to use.

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

  • pressure – Target pressure.

  • verbose – whether to print stdout.

  • steps – max number of steps for relaxation.

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

  • traj_path

  • calculator

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

Silence every unnecessary warning from tensorflow.

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: str)[source]

Build instance from string.

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

Build an ASE calculator.

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

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

abipy.ml.aseml.install_nn_names(nn_names='all', update=False, verbose=0) None[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.

class abipy.ml.aseml.CalcBuilder(name: str, 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']
reset() None[source]
get_calculator(with_delta: bool = True, reset: bool = False) Calculator[source]

Return an ASE calculator with ML potential.

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

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

class abipy.ml.aseml.MlBase(workdir, fig_ext: str = '.pdf', prefix=None, exist_ok=False)[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: str, info: str) None[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.

mkdir(basename: str, info: str) Path[source]

Create directory in workdir, return Path object.

get_path(basename: str, info: str) Path[source]

Return Path in workdir.

savefig(basename: str, fig, info: str) None[source]

Save matplotlib figure in workdir.

write_traj(basename: str, traj, info: str) None[source]

Write ASE trajectory in workdir.

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

Write data in JSON format and mirror output to stream.

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

Write dataframe to file.

write_script(basename: str, text: str, info: str) Path[source]

Write text script to basename file.

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

Bases: MlBase

Relax structure with ASE and ML-potential.

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

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

write_output_file_for_abinit() Path[source]

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

to_string(verbose=0) str[source]

String representation with verbosity level verbose.

run()[source]

Run structural relaxation.

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

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

class abipy.ml.aseml.AseMdLog(filepath: str)[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: int = 0) str[source]

String representation with verbosity level verbose.

plot(**kwargs) Any[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.

histplot(**kwargs) Any[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.

yield_figs(**kwargs)[source]

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

class abipy.ml.aseml.MlMd(atoms: 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) str[source]

String representation with verbosity level verbose.

run() None[source]

Run MD

class abipy.ml.aseml.MlGsList(atoms_list: list[Atoms], 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) str[source]

String representation with verbosity level verbose.

run() None[source]

Run list of GS calculations.

class abipy.ml.aseml.MlNeb(initial_atoms: Atoms, final_atoms: 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) str[source]

String representation with verbosity level verbose.

run() None[source]

Run NEB

class abipy.ml.aseml.MultiMlNeb(atoms_list: list[Atoms], 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) str[source]

String representation with verbosity level verbose.

run() None[source]

Run multi NEB calculations.

abipy.ml.aseml.make_ase_neb(initial: Atoms, final: Atoms, nimages: int, calculators: list, neb_method: str, climb: bool, method='linear', mic=False) NEB[source]

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

Parameters:
  • initial – First point.

  • final – Last point.

  • nimages – Number of images.

  • calculators – List of ASE calculators.

  • neb_method – String defining NEB algorithm.

  • climb – 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.

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) str[source]

String representation with verbosity level verbose.

run() None[source]

Run MlOrderer.

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) str[source]

String representation with verbosity level verbose.

get_abinitio_results() list[AseResults][source]
run(nprocs, print_dataframes=True) AseResultsComparator[source]

Run calculation with nprocs processes.

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

Bases: object

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

run(steps: int)[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.FrozenPhononMl(structure, qpoint, phdispl_cart, eta_list, nn_name, verbose, workdir, prefix=None)[source]

Bases: MlBase

Frozen-phonon calculations with ML potential.

classmethod from_ddb_file(ddb_filepath, qpoint, eta_list, nn_name, verbose, workdir, prefix=None, **anaddb_kwargs)[source]
run()[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) str[source]

String representation with verbosity level verbose.

run(print_dataframes=True) AseResultsComparator[source]

Run calculations.

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) str[source]

String representation with verbosity level verbose.

run()[source]
run_nn_name_set_name(nn_name: str, set_name: str) dict[source]

extxyz_generator Package

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

class abipy.ml.extxyz_generator.ExtxyzIOWriter(filepaths: list[str | PathLike])[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']
classmethod from_top_vasprun(top: str | PathLike)[source]

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

classmethod from_top_gsr(top: str | PathLike)[source]

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

classmethod from_top(top: str | PathLike, ext: str)[source]

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

to_string(verbose: int = 0) str[source]

String representation with verbosiy level verbose.

write(xyz_filepath: str | PathLike, overwrite: bool = False)[source]

Write data to xyz_filepath.

Parameters:
  • xyz_filepath – Filename

  • overwrite – True to allow overwriting.

yield_atoms()[source]

Generate ASE atoms.

abipy.ml.extxyz_generator.check_vasp_success(vasprun: Vasprun, outcar: Outcar | None, verbose: int = 1) bool[source]

Check if a VASP calculation completed successfully.

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

class abipy.ml.extxyz_generator.SinglePointRunner(traj_path: str | ~os.PathLike, traj_range: range, topdir: str | ~os.PathLike = '.', code: str = 'vasp', vasp_set_cls=<class 'pymatgen.io.vasp.sets.MatPESStaticSet'>, verbose: int = 0)[source]

Bases: object

Usage example:

traj_range = range(0, -1, 100)
runner = SinglePointRunner("out.traj", "outdir", traj_range)
runner.sbatch()
runner.collect_xyz("foo.xyz")
slurm_script_name = 'run.sh'
custodian_script_name = 'run_custodian.py'
to_string(verbose: int = 0) str[source]

String representation with verbosiy level verbose.

sbatch(max_jobs: int = 100) list[int][source]

Submit max_jobs SinglePoint calculations with structures taken from the ASE trajectory file.

write_xyz(xyz_filepath: str | PathLike, dry_run=False) None[source]

ml_phonopy Package

Classes to compute vibrational properties with phonopy and ML potentials.

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

Print traceback.

abipy.ml.ml_phonopy.get_phonopy(structure: Structure, supercell_matrix, calculator: Calculator, distance=0.01, primitive_matrix=None, remove_drift=True) Phonopy[source]
Parameters:
  • structure – Structure object.

  • supercell_matrix – Supercell matrix.

  • 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.

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() None[source]

Run MlPhonopyWithDDB.

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 ML potential.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

run() None[source]

Run calculation.

relax_scanner Package

Objects to perform ASE calculations with machine-learning potentials.

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

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

class abipy.ml.relax_scanner.Entry(isite: int, structure: Structure, energy: float, forces: ndarray)[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) Entry[source]

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

classmethod from_traj(isite, traj) Entry[source]

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

class abipy.ml.relax_scanner.Pair(index1: int, index2: int, ediff: float, dist: float, frac_coords1: ndarray, frac_coords2: ndarray)[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() dict[source]

Useful to construct pandas DataFrames

class abipy.ml.relax_scanner.RelaxScanner(structure, isite, mesh, nn_name, relax_mode: str = 'ions', fmax: float = 0.001, steps=500, verbose: int = 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: int = 0) str[source]

String representation with verbosity level verbose.

get_atoms_with_frac_coords(frac_coords, with_fixed_atoms=True) Atoms[source]

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

get_structure_with_two_frac_coords(frac_coords1, frac_coords2) Structure[source]

Return Structure instance with frac_coords at site index isite.

run_start_count(start: int, count: int) Path[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 – Index of initial structure.

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

run(nprocs) None[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.

class abipy.ml.relax_scanner.RelaxScannerAnalyzer(entries: list[Entry], scanner: RelaxScanner, verbose: int = 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: Path) RelaxScannerAnalyzer[source]

Merge all entries starting from directory topdir.

has_vasp_inputs() bool[source]

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

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) str[source]
lattice()[source]
pairs_enediff_dist(ediff_tol=0.001, dist_tol=3.5, neb_method=None, nprocs=-1) list[Pair][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: list of Pair objects.

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

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

Parameters:
  • 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.

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.

tools Package

Low-level tools used in abipy.ml

abipy.ml.tools.get_energy_step(step: dict) float[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

abipy.ml.tools.get_structures_labels_from_file(filepath: str) tuple[list[Structure], dict][source]

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

abipy.ml.tools.get_structures_labels_from_files(filepaths) tuple[list[Structure], dict][source]

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