-
Notifications
You must be signed in to change notification settings - Fork 47
feat: add ring planarity benchmark #681
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lwalew
wants to merge
1
commit into
ddmms:main
Choose a base branch
from
lwalew:feat/add-ring-planarity
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
200 changes: 200 additions & 0 deletions
200
ml_peg/analysis/molecular_dynamics/ring_planarity/analyse_ring_planarity.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,200 @@ | ||
| """Analyse the aromatic ring planarity benchmark.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from pathlib import Path | ||
|
|
||
| from ase.calculators.calculator import Calculator | ||
| from mlipaudit.io import load_model_output_from_disk | ||
| import numpy as np | ||
| import pytest | ||
|
|
||
| from ml_peg.analysis.utils.decorators import build_table, plot_hist | ||
| from ml_peg.analysis.utils.utils import ( | ||
| build_dispersion_name_map, | ||
| load_metrics_config, | ||
| ) | ||
| from ml_peg.app import APP_ROOT | ||
| from ml_peg.calcs import CALCS_ROOT | ||
| from ml_peg.calcs.utils.mlipaudit import MlPegRingPlanarityBenchmark | ||
| from ml_peg.calcs.utils.utils import download_s3_data | ||
| from ml_peg.models import current_models | ||
| from ml_peg.models.get_models import load_models | ||
|
|
||
| MODELS = load_models(current_models) | ||
| DISPERSION_NAME_MAP = build_dispersion_name_map(MODELS) | ||
|
|
||
| BENCHMARK = MlPegRingPlanarityBenchmark.name | ||
| DATASET_FILENAME = "ring_planarity_data.json" | ||
|
|
||
| CALC_PATH = CALCS_ROOT / "molecular_dynamics" / "ring_planarity" / "outputs" | ||
| OUT_PATH = APP_ROOT / "data" / "molecular_dynamics" / "ring_planarity" | ||
|
|
||
| METRICS_CONFIG_PATH = Path(__file__).with_name("metrics.yml") | ||
| DEFAULT_THRESHOLDS, DEFAULT_TOOLTIPS, DEFAULT_WEIGHTS = load_metrics_config( | ||
| METRICS_CONFIG_PATH | ||
| ) | ||
|
|
||
|
|
||
| def _data_input_dir() -> Path: | ||
| """ | ||
| Download and return the benchmark input data directory. | ||
|
|
||
| Returns | ||
| ------- | ||
| Path | ||
| Directory containing the extracted ring planarity input data. | ||
| """ | ||
| return download_s3_data( | ||
| key="inputs/molecular_dynamics/ring_planarity/ring_planarity.zip", | ||
| filename="ring_planarity.zip", | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def analyze_results() -> dict: | ||
| """ | ||
| Run the mlipaudit analysis for each model. | ||
|
|
||
| Returns | ||
| ------- | ||
| dict | ||
| Mapping of model name to its ``RingPlanarityResult``. | ||
| """ | ||
| data_input_dir = _data_input_dir() | ||
|
|
||
| results = {} | ||
| for model_name in MODELS: | ||
| output_dir = CALC_PATH / model_name / BENCHMARK | ||
| if not (output_dir / "model_output.zip").exists(): | ||
| continue | ||
| benchmark = MlPegRingPlanarityBenchmark( | ||
| force_field=Calculator(), | ||
| data_input_dir=data_input_dir, | ||
| run_mode="standard", | ||
| ) | ||
| benchmark.model_output = load_model_output_from_disk( | ||
| CALC_PATH / model_name, MlPegRingPlanarityBenchmark | ||
| ) | ||
| results[model_name] = benchmark.analyze() | ||
| return results | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def struct_info() -> None: | ||
| """Write the combined element set to ``info.json`` for filtering.""" | ||
| data_path = _data_input_dir() / BENCHMARK / DATASET_FILENAME | ||
| with open(data_path, encoding="utf-8") as f: | ||
| data = json.load(f) | ||
|
|
||
| elements = sorted( | ||
| {symbol for molecule in data.values() for symbol in molecule["atom_symbols"]} | ||
| ) | ||
|
|
||
| OUT_PATH.mkdir(parents=True, exist_ok=True) | ||
| with (OUT_PATH / "info.json").open("w", encoding="utf-8") as f: | ||
| json.dump({"elements": elements}, f, indent=1) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| @plot_hist( | ||
| filename=str(OUT_PATH / "figure_ring_planarity_hist.json"), | ||
| title="Ring planarity deviation distribution", | ||
| x_label="Planarity deviation / Å", | ||
| y_label="Probability density", | ||
| bins=50, | ||
| ) | ||
| def deviation_distributions(analyze_results) -> dict[str, np.ndarray]: | ||
| """ | ||
| Collect the planarity deviations sampled along each model's trajectories. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| analyze_results | ||
| Mapping of model name to its ``RingPlanarityResult``. | ||
|
|
||
| Returns | ||
| ------- | ||
| dict[str, np.ndarray] | ||
| Per-model flat array of ring planarity deviations across all molecules. | ||
| """ | ||
| results = {} | ||
| for model_name, result in analyze_results.items(): | ||
| if result.failed: | ||
| continue | ||
| deviations = [ | ||
| value | ||
| for molecule in result.molecules | ||
| if molecule.deviation_trajectory is not None | ||
| for value in molecule.deviation_trajectory | ||
| ] | ||
| if deviations: | ||
| results[model_name] = np.array(deviations) | ||
| return results | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def get_mae_deviation(analyze_results) -> dict[str, float]: | ||
| """ | ||
| Get the mean planarity deviation for each model. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| analyze_results | ||
| Mapping of model name to its ``RingPlanarityResult``. | ||
|
|
||
| Returns | ||
| ------- | ||
| dict[str, float] | ||
| Mean planarity deviation of the ring atoms over the trajectories, in Angstrom. | ||
| """ | ||
| return { | ||
| model_name: result.mae_deviation | ||
| for model_name, result in analyze_results.items() | ||
| } | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| @build_table( | ||
| filename=OUT_PATH / "ring_planarity_metrics_table.json", | ||
| metric_tooltips=DEFAULT_TOOLTIPS, | ||
| thresholds=DEFAULT_THRESHOLDS, | ||
| weights=DEFAULT_WEIGHTS, | ||
| mlip_name_map=DISPERSION_NAME_MAP, | ||
| ) | ||
| def metrics( | ||
| deviation_distributions, | ||
| get_mae_deviation: dict[str, float], | ||
| ) -> dict[str, dict]: | ||
| """ | ||
| Get all metrics. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| deviation_distributions | ||
| Per-model deviation arrays (triggers the histogram plot). | ||
| get_mae_deviation | ||
| Mean planarity deviations for all models. | ||
|
|
||
| Returns | ||
| ------- | ||
| dict[str, dict] | ||
| Metric names and values for all models. | ||
| """ | ||
| return { | ||
| "Planarity Deviation": get_mae_deviation, | ||
| } | ||
|
|
||
|
|
||
| def test_ring_planarity(metrics: dict[str, dict], struct_info: None) -> None: | ||
| """ | ||
| Run ring planarity analysis. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| metrics : dict[str, dict] | ||
| Ring planarity metric results provided by fixtures. | ||
| struct_info : None | ||
| Element info written to ``info.json`` for filtering. | ||
| """ |
8 changes: 8 additions & 0 deletions
8
ml_peg/analysis/molecular_dynamics/ring_planarity/metrics.yml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| metrics: | ||
| Planarity Deviation: | ||
| good: 0.0 | ||
| bad: 0.05 | ||
| unit: Å | ||
| weight: 1 | ||
| tooltip: Mean RMSD of the ring atoms from their best-fit plane, averaged over the MD trajectory and across all molecules. | ||
| level_of_theory: DFT |
66 changes: 66 additions & 0 deletions
66
ml_peg/app/molecular_dynamics/ring_planarity/app_ring_planarity.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| """Run ring planarity benchmark 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 | ||
| from ml_peg.app.utils.load import read_plot | ||
|
|
||
| BENCHMARK_NAME = "RingPlanarity" | ||
| DOCS_URL = "https://ddmms.github.io/ml-peg/user_guide/benchmarks/molecular_dynamics.html#ring-planarity" | ||
| DATA_PATH = APP_ROOT / "data" / "molecular_dynamics" / "ring_planarity" | ||
|
|
||
|
|
||
| class RingPlanarityApp(BaseApp): | ||
| """Ring planarity benchmark app layout and callbacks.""" | ||
|
|
||
| def register_callbacks(self) -> None: | ||
| """Register callbacks to app.""" | ||
| histogram = read_plot( | ||
| DATA_PATH / "figure_ring_planarity_hist.json", | ||
| id=f"{BENCHMARK_NAME}-figure", | ||
| ) | ||
|
|
||
| plot_from_table_column( | ||
| table_id=self.table_id, | ||
| plot_id=f"{BENCHMARK_NAME}-figure-placeholder", | ||
| column_to_plot={"Planarity Deviation": histogram}, | ||
| ) | ||
|
|
||
|
|
||
| def get_app() -> RingPlanarityApp: | ||
| """ | ||
| Get ring planarity benchmark app layout and callback registration. | ||
|
|
||
| Returns | ||
| ------- | ||
| RingPlanarityApp | ||
| Benchmark layout and callback registration. | ||
| """ | ||
| return RingPlanarityApp( | ||
| name="Ring Planarity", | ||
| framework_ids="mlip_audit", | ||
| description=( | ||
| "Performance in maintaining planar aromatic rings during molecular " | ||
| "dynamics of small organic molecules. Reference geometries are taken " | ||
| "from QM-optimised structures." | ||
| ), | ||
| docs_url=DOCS_URL, | ||
| table_path=DATA_PATH / "ring_planarity_metrics_table.json", | ||
| info_path=DATA_PATH / "info.json", | ||
| extra_components=[ | ||
| Div(id=f"{BENCHMARK_NAME}-figure-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=8070, debug=True) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
gpu estimate?