diff --git a/docs/source/user_guide/benchmarks/conformers.rst b/docs/source/user_guide/benchmarks/conformers.rst new file mode 100644 index 000000000..85119b357 --- /dev/null +++ b/docs/source/user_guide/benchmarks/conformers.rst @@ -0,0 +1,42 @@ +============== +Conformers +============== + +ACONFL +====== + +Summary +------- + +Performance in predicting relative conformer energies of 12 C12H26, +16 C16H34 and 20 C20H42 conformers. Reference data from PNO-LCCSD(T)-F12/ AVQZ calculations. + +Metrics +------- + +1. Conformer energy error + +For each complex, the the relative energy is calculated by taking the difference in energy +between the given conformer and the reference (zero-energy) conformer. This is +compared to the reference conformer energy, calculated in the same way. + +Computational cost +------------------ + +Low: tests are likely to take minutes to run on CPU. + +Data availability +----------------- + +Input structures: + +* Conformational Energy Benchmark for Longer n-Alkane Chains + Sebastian Ehlert, Stefan Grimme, and Andreas Hansen + The Journal of Physical Chemistry A 2022 126 (22), 3521-3535 + DOI: 10.1021/acs.jpca.2c02439 + +Reference data: + +* Same as input data +* :math:`PNO-LCCSD(T)-F12/ AVQZ` level of theory: a local, explicitly + correlated coupled cluster method. diff --git a/ml_peg/analysis/conformers/ACONFL/analyse_ACONFL.py b/ml_peg/analysis/conformers/ACONFL/analyse_ACONFL.py new file mode 100644 index 000000000..c3d450c40 --- /dev/null +++ b/ml_peg/analysis/conformers/ACONFL/analyse_ACONFL.py @@ -0,0 +1,149 @@ +""" +Analyse the ACONFL dataset for molecular conformer relative energies. + +Conformational Energy Benchmark for Longer n-Alkane Chains +Sebastian Ehlert, Stefan Grimme, and Andreas Hansen +The Journal of Physical Chemistry A 2022 126 (22), 3521-3535 +DOI: 10.1021/acs.jpca.2c02439 +""" + +from __future__ import annotations + +from pathlib import Path + +from ase import units +from ase.io import read, write +import pytest + +from ml_peg.analysis.utils.decorators import build_table, plot_parity +from ml_peg.analysis.utils.utils import build_d3_name_map, load_metrics_config, mae +from ml_peg.app import APP_ROOT +from ml_peg.calcs import CALCS_ROOT +from ml_peg.models.get_models import load_models +from ml_peg.models.models import current_models + +MODELS = load_models(current_models) +D3_MODEL_NAMES = build_d3_name_map(MODELS) + +EV_TO_KCAL = units.mol / units.kcal +CALC_PATH = CALCS_ROOT / "conformers" / "ACONFL" / "outputs" +OUT_PATH = APP_ROOT / "data" / "conformers" / "ACONFL" + +METRICS_CONFIG_PATH = Path(__file__).with_name("metrics.yml") +DEFAULT_THRESHOLDS, DEFAULT_TOOLTIPS, DEFAULT_WEIGHTS = load_metrics_config( + METRICS_CONFIG_PATH +) + + +def labels() -> list: + """ + Get list of system names. + + Returns + ------- + list + List of all system names. + """ + for model_name in MODELS: + labels_list = [path.stem for path in sorted((CALC_PATH / model_name).glob("*"))] + break + return labels_list + + +@pytest.fixture +@plot_parity( + filename=OUT_PATH / "figure_aconfl.json", + title="Energies", + x_label="Predicted energy / kcal/mol", + y_label="Reference energy / kcal/mol", + hoverdata={ + "Labels": labels(), + }, +) +def conformer_energies() -> dict[str, list]: + """ + Get conformer energies for all systems. + + Returns + ------- + dict[str, list] + Dictionary of all reference and predicted conformer energies. + """ + results = {"ref": []} | {mlip: [] for mlip in MODELS} + ref_stored = False + + for model_name in MODELS: + for label in labels(): + atoms = read(CALC_PATH / model_name / f"{label}.xyz") + + results[model_name].append(atoms.info["model_rel_energy"] * EV_TO_KCAL) + if not ref_stored: + results["ref"].append(atoms.info["ref_rel_energy"] * EV_TO_KCAL) + + # Write structures for app + structs_dir = OUT_PATH / model_name + structs_dir.mkdir(parents=True, exist_ok=True) + write(structs_dir / f"{label}.xyz", atoms) + ref_stored = True + return results + + +@pytest.fixture +def get_mae(conformer_energies) -> dict[str, float]: + """ + Get mean absolute error for conformer energies. + + Parameters + ---------- + conformer_energies + Dictionary of reference and predicted conformer energies. + + Returns + ------- + dict[str, float] + Dictionary of predicted conformer energies errors for all models. + """ + results = {} + for model_name in MODELS: + results[model_name] = mae( + conformer_energies["ref"], conformer_energies[model_name] + ) + return results + + +@pytest.fixture +@build_table( + filename=OUT_PATH / "aconfl_metrics_table.json", + metric_tooltips=DEFAULT_TOOLTIPS, + thresholds=DEFAULT_THRESHOLDS, + mlip_name_map=D3_MODEL_NAMES, +) +def metrics(get_mae: dict[str, float]) -> dict[str, dict]: + """ + Get all metrics. + + Parameters + ---------- + get_mae + Mean absolute errors for all models. + + Returns + ------- + dict[str, dict] + Metric names and values for all models. + """ + return { + "MAE": get_mae, + } + + +def test_aconfl(metrics: dict[str, dict]) -> None: + """ + Run ACONFL test. + + Parameters + ---------- + metrics + All new benchmark metric names and dictionary of values for each model. + """ + return diff --git a/ml_peg/analysis/conformers/ACONFL/metrics.yml b/ml_peg/analysis/conformers/ACONFL/metrics.yml new file mode 100644 index 000000000..40d89a17d --- /dev/null +++ b/ml_peg/analysis/conformers/ACONFL/metrics.yml @@ -0,0 +1,7 @@ +metrics: + MAE: + good: 0.0 + bad: 2.0 + unit: kcal/mol + tooltip: Mean Absolute Error for all systems + level_of_theory: PNO-LCCSD(T)-F12/ AVQZ diff --git a/ml_peg/app/conformers/ACONFL/app_ACONFL.py b/ml_peg/app/conformers/ACONFL/app_ACONFL.py new file mode 100644 index 000000000..838c894e2 --- /dev/null +++ b/ml_peg/app/conformers/ACONFL/app_ACONFL.py @@ -0,0 +1,87 @@ +"""Run ACONFL app.""" + +from __future__ import annotations + +from dash import Dash +from dash.html import Div + +from ml_peg.app import APP_ROOT +from ml_peg.app.base_app import BaseApp +from ml_peg.app.utils.build_callbacks import ( + plot_from_table_column, + struct_from_scatter, +) +from ml_peg.app.utils.load import read_plot +from ml_peg.models.get_models import get_model_names +from ml_peg.models.models import current_models + +MODELS = get_model_names(current_models) +BENCHMARK_NAME = "ACONFL" +DOCS_URL = "https://ddmms.github.io/ml-peg/user_guide/benchmarks/conformers.html#ACONFL" +DATA_PATH = APP_ROOT / "data" / "conformers" / "ACONFL" + + +class ACONFLApp(BaseApp): + """ACONFL benchmark app layout and callbacks.""" + + def register_callbacks(self) -> None: + """Register callbacks to app.""" + scatter = read_plot( + DATA_PATH / "figure_aconfl.json", + id=f"{BENCHMARK_NAME}-figure", + ) + + model_dir = DATA_PATH / MODELS[0] + if model_dir.exists(): + labels = sorted([f.stem for f in model_dir.glob("*.xyz")]) + structs = [ + f"assets/conformers/ACONFL/{MODELS[0]}/{label}.xyz" for label in labels + ] + else: + structs = [] + + plot_from_table_column( + table_id=self.table_id, + plot_id=f"{BENCHMARK_NAME}-figure-placeholder", + column_to_plot={"MAE": scatter}, + ) + + struct_from_scatter( + scatter_id=f"{BENCHMARK_NAME}-figure", + struct_id=f"{BENCHMARK_NAME}-struct-placeholder", + structs=structs, + mode="struct", + ) + + +def get_app() -> ACONFLApp: + """ + Get ACONFL benchmark app layout and callback registration. + + Returns + ------- + ACONFLApp + Benchmark layout and callback registration. + """ + return ACONFLApp( + name=BENCHMARK_NAME, + description=( + "Performance in predicting relative conformer energies " + "of 12 C12H26, 16 C16H34 and 20 C20H42 conformers. " + "Reference data from PNO-LCCSD(T)-F12/ AVQZ calculations." + ), + docs_url=DOCS_URL, + table_path=DATA_PATH / "aconfl_metrics_table.json", + extra_components=[ + Div(id=f"{BENCHMARK_NAME}-figure-placeholder"), + Div(id=f"{BENCHMARK_NAME}-struct-placeholder"), + ], + ) + + +if __name__ == "__main__": + full_app = Dash(__name__, assets_folder=DATA_PATH.parent.parent) + benchmark_app = get_app() + full_app.layout = benchmark_app.layout + benchmark_app.register_callbacks() + full_app.run(port=8062, debug=True) diff --git a/ml_peg/calcs/conformers/ACONFL/calc_ACONFL.py b/ml_peg/calcs/conformers/ACONFL/calc_ACONFL.py new file mode 100644 index 000000000..47201ddf5 --- /dev/null +++ b/ml_peg/calcs/conformers/ACONFL/calc_ACONFL.py @@ -0,0 +1,76 @@ +""" +Compute the ACONFL dataset for molecular conformer relative energies. + +Conformational Energy Benchmark for Longer n-Alkane Chains +Sebastian Ehlert, Stefan Grimme, and Andreas Hansen +The Journal of Physical Chemistry A 2022 126 (22), 3521-3535 +DOI: 10.1021/acs.jpca.2c02439 +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from ase import units +from ase.io import read, write +import pytest + +from ml_peg.calcs.utils.utils import download_s3_data +from ml_peg.models.get_models import load_models +from ml_peg.models.models import current_models + +MODELS = load_models(current_models) + +KCAL_TO_EV = units.kcal / units.mol + +OUT_PATH = Path(__file__).parent / "outputs" + + +@pytest.mark.parametrize("mlip", MODELS.items()) +def test_aconfl_conformer_energies(mlip: tuple[str, Any]) -> None: + """ + Benchmark the ACONFL dataset. + + Parameters + ---------- + mlip + Name of model use and model to get calculator. + """ + model_name, model = mlip + calc = model.get_calculator() + + data_path = ( + download_s3_data( + filename="ACONFL.zip", + key="inputs/conformers/ACONFL/ACONFL.zip", + ) + / "ACONFL" + ) + + calc = model.get_calculator() + # Add D3 calculator for this test + calc = model.add_d3_calculator(calc) + + with open(data_path / ".res") as lines: + for line in lines: + if "$tmer" in line: + items = line.strip().split() + zero_atoms_label = items[1].replace("/$f", "") + atoms_label = items[2].replace("/$f", "") + ref_rel_energy = float(items[7]) * KCAL_TO_EV + atoms = read(data_path / atoms_label / "struc.xyz") + atoms.calc = calc + atoms.info.update({"charge": 0, "spin": 1}) + zero_atoms = read(data_path / zero_atoms_label / "struc.xyz") + zero_atoms.calc = calc + zero_atoms.info.update({"charge": 0, "spin": 1}) + atoms.info["model_rel_energy"] = ( + atoms.get_potential_energy() - zero_atoms.get_potential_energy() + ) + atoms.info["ref_rel_energy"] = ref_rel_energy + + write_dir = OUT_PATH / model_name + write_dir.mkdir(parents=True, exist_ok=True) + + write(write_dir / f"{atoms_label}.xyz", atoms)