Skip to content

Commit

Permalink
Add tests for ml modules
Browse files Browse the repository at this point in the history
  • Loading branch information
gmatteo committed Jan 11, 2025
1 parent 505758d commit 234ef4c
Show file tree
Hide file tree
Showing 12 changed files with 1,687 additions and 91 deletions.
4 changes: 3 additions & 1 deletion abipy/data/refs/al_eph/_runflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,14 @@ def main(options):

rename_table = [
# src, dest
("_runflow/w1/outdata/out_DDB", "out_444q_DDB"),
("_runflow/w2/t0/outdata/out_A2F.nc", "al_888k_161616q_A2F.nc"),
("_runflow/w2/t1/outdata/out_A2F.nc", "al_888k_161616q_vinterp_A2F.nc"),
("_runflow/w2/t2/outdata/out_PHDOS.nc", "al_161616q_PHDOS.nc"),
("_runflow/w2/t2/outdata/out_PHDOS.nc", "al_161616q_PHDOS.nc"),
]
import shutil
for old, new in rename_table:
#print(old, new)
shutil.copyfile(old, new)
#shutil.rmtree("_runflow")
sys.exit(0)
Binary file added abipy/data/refs/al_eph/al_relax_HIST.nc
Binary file not shown.
1,428 changes: 1,428 additions & 0 deletions abipy/data/refs/al_eph/out_444q_DDB

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions abipy/dynamics/hist.py
Original file line number Diff line number Diff line change
Expand Up @@ -742,9 +742,9 @@ def get_dataframe(self, with_geo=True, index=None, abspath=False,
kwargs:
attrs:
List of additional attributes of the |GsrFile| to add to the |pandas-DataFrame|.
List of additional attributes of the |HistFile| to add to the |pandas-DataFrame|.
funcs: Function or list of functions to execute to add more data to the DataFrame.
Each function receives a |GsrFile| object and returns a tuple (key, value)
Each function receives a |HistFile| 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.
"""
# Add attributes specified by the users
Expand Down
61 changes: 61 additions & 0 deletions abipy/eph/tests/test_varpeq.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Tests for varpeq module."""
import abipy.data as abidata

from abipy.core.testing import AbipyTest
from abipy.eph.varpeq import VarpeqFile


#class VarpeqTest(AbipyTest):
#
# def test_varpeq_file(self):
# """Testing VarpeqFile."""
# with VarpeqFile(abidata.ref_file("abinitio_qpath_V1QAVG.nc")) as varpeq:
# repr(varpeq)
# str(varpeq)
# assert varpeq.to_string(verbose=2)
# assert not varpeq.params
# assert varpeq.structure.formula == "Ga1 P1" and len(varpeq.structure) == 2
#
# #print(varpeq.ebands.kpoints.ksampling)
# for polaron in varpeq.polaron_spin:
# #print(polaron)
# #polaron.plot_bz_sampling()
# #polaron.plot_bqnu_with_phbands(phbands)
# polaron.plot_ank_with_ebands(ebands)
#
# if self.has_matplotlib():
#
# # Test jupyter notebook creation
# if self.has_nbformat():
# varpeq.write_notebook(nbpath=self.get_tmpname(text=True))


#class VarpeqRobotTest(AbipyTest):
#
# def test_varpeq_robot(self):
# """Testing VarpeqRobot."""
# files = abidata.ref_files(
# "abinitio_qpath_V1QAVG.nc",
# "interpolated_qpath_V1QAVG.nc",
# )
#
# with VarpeqRobot.from_files(files[0]) as robot:
# robot.add_file("interpolated_v1qavg", files[1])
# assert len(robot) == 2
# repr(robot); str(robot)
# robot.to_string(verbose=2)
#
# interp_ncfile = robot.abifiles[1]
# assert interp_ncfile.interpolated
# assert interp_ncfile.has_maxw
#
# # Test matplotlib methods
# if self.has_matplotlib():
# assert robot.plot(ispden=0, vname="v1scf_avg", show=False)
# assert robot.plot_maxw(show=False) is None
# assert interp_ncfile.plot_maxw(show=False)
# assert interp_ncfile.plot_maxw_perts(scale="semilogy", sharey=False, fontsize=8, show=False)
#
# # Test jupyter notebook creation
# if self.has_nbformat():
# robot.write_notebook(nbpath=self.get_tmpname(text=True))
2 changes: 1 addition & 1 deletion abipy/flowtk/vzsisa.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ def on_all_ok(self):
ph_work = PhononWork.from_scf_input(scf_input, self.ngqpt, is_ngqpt=True, tolerance=None,
with_becs=self.with_becs, with_quad=self.with_quad,
ndivsm=0 if bo_scale != 1.0 else self.ndivsm)
ph_work.set_name(f"PH for {bo_scale=}"
ph_work.set_name(f"PH for {bo_scale=}")

# Reduce the number of files produced in the DFPT tasks to avoid possible disk quota issues.
for task in ph_work[1:]:
Expand Down
2 changes: 1 addition & 1 deletion abipy/flowtk/zsisa.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ def _on_ok(self):
structure=relaxed_structure,
cart_therm_stress=cart_therm_stress,
cart_bo_stress=gsr.cart_stress_tensor,
converged=converged.
converged=converged,
)

mjson_write(thermal_hist, json_path, indent=4)
Expand Down
61 changes: 36 additions & 25 deletions abipy/ml/aseml.py
Original file line number Diff line number Diff line change
Expand Up @@ -754,7 +754,10 @@ def plot_energies(self, fontsize=8, **kwargs) -> Figure:
ax.grid(True)
ax.set_xlabel(f"{key1} energy", fontsize=fontsize)
ax.set_ylabel(f"{key2} energy", fontsize=fontsize)
linear_fit_ax(ax, xs, ys, fontsize=fontsize, with_label=True)
try:
linear_fit_ax(ax, xs, ys, fontsize=fontsize, with_label=True)
except ValueError as exc:
print(exc)
ax.legend(loc="best", shadow=True, fontsize=fontsize)
if irow == 0:
ax.set_title(f"{key1}/{key2} MAE: {stats.MAE:.6f}", fontsize=fontsize)
Expand Down Expand Up @@ -787,7 +790,10 @@ def plot_forces(self, symbol=None, site_inds=None, fontsize=8, **kwargs) -> Figu
xs, ys = self.xy_forces_for_keys(key1, key2, direction, symbol=symbol, site_inds=site_inds)
stats = diff_stats(xs, ys)
ax.scatter(xs, ys, marker="o")
linear_fit_ax(ax, xs, ys, fontsize=fontsize, with_label=True)
try:
linear_fit_ax(ax, xs, ys, fontsize=fontsize, with_label=True)
except ValueError as exc:
print(exc)

ax.legend(loc="best", shadow=True, fontsize=fontsize)
f_tex = f"$F_{direction}$"
Expand Down Expand Up @@ -820,7 +826,11 @@ def plot_stresses(self, fontsize=6, **kwargs) -> Figure:
stats = diff_stats(xs, ys)
ax = ax_mat[irow, icol]
ax.scatter(xs, ys, marker="o")
linear_fit_ax(ax, xs, ys, fontsize=fontsize, with_label=True)
try:
linear_fit_ax(ax, xs, ys, fontsize=fontsize, with_label=True)
except ValueError as exc:
print(exc)

ax.legend(loc="best", shadow=True, fontsize=fontsize)
ax.grid(True)
s_tex = r"$\sigma_{%s}$" % voigt_comp
Expand Down Expand Up @@ -880,7 +890,7 @@ def plot_forces_traj(self, delta_mode=True, symbol=None, fontsize=6, markersize=
delta_mode: True to plot differences instead of absolute values.
symbol: If not None, select only forces for this atomic species
"""
# Fx,Fy,Fx along rows, pairs along columns.
# Fx, Fy, Fx along rows, pairs along columns.
key_pairs = self.get_key_pairs()
nrows, ncols = 3, len(key_pairs)
ax_mat, fig, plt = get_axarray_fig_plt(None, nrows=nrows, ncols=ncols,
Expand All @@ -892,7 +902,7 @@ def plot_forces_traj(self, delta_mode=True, symbol=None, fontsize=6, markersize=
atom2_cmap = plt.get_cmap("jet")
marker_idir = {0: ">", 1: "<", 2: "^"}

if symbol is None:
if symbol is not None:
inds = np.array(self.structure.indices_from_symbol(symbol))
if len(inds) == 0:
raise ValueError(f"Cannot find chemical {symbol=} in structure!")
Expand Down Expand Up @@ -1104,9 +1114,9 @@ def relax_atoms(atoms: Atoms,
Args:
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.
optimizer: name of the ASE optimizer to use for relaxation.
fmax: tolerance for relaxation convergence. Here fmax is a sum of force and stress forces.
pressure: Target pressure.
pressure: Target pressure in GPa.
verbose: whether to print stdout.
steps: max number of steps for relaxation.
opt_kwargs (dict): kwargs for the ASE optimizer class.
Expand Down Expand Up @@ -2101,7 +2111,7 @@ def __init__(self,
"""
Args:
atoms: ASE atoms to relax.
relax_mode: Relaxation mode.
relax_mode: "ions" to relax ions only, "cell" for ions + cell, "no" for no relaxation.
fmax: tolerance for relaxation convergence. Here fmax is a sum of force and stress forces.
pressure: Target pressure in GPa.
steps: max number of steps for relaxation.
Expand Down Expand Up @@ -2309,7 +2319,7 @@ def __init__(self,
Args:
atoms: ASE atoms.
temperature: Temperature in K
pressure:
pressure: Target pressure in GPa.
timestep:
steps: Number of steps.
loginterval:
Expand Down Expand Up @@ -2427,9 +2437,9 @@ def __init__(self, traj_filepath, relax_mode, fmax, pressure, steps, optimizer,
"""
Args:
traj_filepath:
relax_mode:
relax_mode: "ions" to relax ions only, "cell" for ions + cell, "no" for no relaxation.
fmax: tolerance for relaxation convergence. Here fmax is a sum of force and stress forces.
pressure: Target pressure.
pressure: Target pressure in GPa.
steps: max number of steps for relaxation.
optimizer: name of the ASE optimizer to use for relaxation.
nn_name: String defining the NN potential. See also CalcBuilder.
Expand Down Expand Up @@ -2612,7 +2622,7 @@ def __init__(self,
optimizer: name of the ASE optimizer to use for relaxation.
relax_mode: "ions" to relax ions only, "cell" for ions + cell, "no" for no relaxation.
fmax: tolerance for relaxation convergence. Here fmax is a sum of force and stress forces.
pressure: Target pressure
pressure: Target pressure in GPa.
nn_name: String defining the NN potential. See also CalcBuilder.
verbose: Verbosity level.
workdir: Working directory.
Expand Down Expand Up @@ -2768,10 +2778,10 @@ def __init__(self,
nimages: Number of NEB images.
neb_method:
climb:
optimizer:
optimizer: name of the ASE optimizer to use for relaxation.
relax_mode: "ions" to relax ions only, "cell" for ions + cell, "no" for no relaxation.
fmax: tolerance for relaxation convergence. Here fmax is a sum of force and stress forces.
pressure:
pressure: Target pressure in GPa.
nn_name: String defining the NN potential. See also CalcBuilder.
verbose: Verbosity level.
workdir: Working directory.
Expand Down Expand Up @@ -2903,7 +2913,8 @@ def __init__(self,
max_ns,
optimizer,
relax_mode,
fmax, pressure,
fmax,
pressure,
steps,
nn_name,
verbose,
Expand All @@ -2912,11 +2923,11 @@ def __init__(self,
"""
Args:
structure: Abipy Structure object or any object that can be converted to structure.
max_ns:
optimizer:
relax_mode:
fmax:
pressure:
max_ns: Maximum number of structures
optimizer: name of the ASE optimizer to use for relaxation.
relax_mode: "ions" to relax ions only, "cell" for ions + cell, "no" for no relaxation.
fmax: tolerance for relaxation convergence. Here fmax is a sum of force and stress forces.
pressure: Target pressure in GPa.
steps:
nn_name: String defining the NN potential. See also CalcBuilder.
verbose: Verbosity level.
Expand Down Expand Up @@ -2964,10 +2975,10 @@ def run(self) -> None:
Run MlOrderer.
"""
workdir = self.workdir
from pymatgen.core import Lattice
specie = {"Cu0+": 0.5, "Au0+": 0.5}
structure = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3.677), [specie], [[0, 0, 0]])
#structure = self.structure
#from pymatgen.core import Lattice
#specie = {"Cu0+": 0.5, "Au0+": 0.5}
#structure = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3.677), [specie], [[0, 0, 0]])
structure = self.structure
#print(structure)

# Each dict in d_list contains the following entries:
Expand Down Expand Up @@ -3464,7 +3475,7 @@ def __init__(self,
vol_scales: List of volumetric scaling factors.
relax_mode:
fmax: tolerance for relaxation convergence. Here fmax is a sum of force and stress forces.
pressure: Target pressure.
pressure: Target pressure in GPa.
steps: max number of steps for relaxation.
optimizer: name of the ASE optimizer to use for relaxation.
nn_name: String defining the NN potential. See also CalcBuilder.
Expand Down
Loading

0 comments on commit 234ef4c

Please sign in to comment.