-
Notifications
You must be signed in to change notification settings - Fork 7
Make torchsim able to use the latest metatomic features #181
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
Merged
Merged
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
7a42ce8
feat(torchsim): add variants, non-conservative, uncertainty, addition…
HaoZeke 188b84e
fix(torchsim): address code review findings
HaoZeke 22e2596
fix(torchsim): address round 2 review findings
HaoZeke 195bea2
feat(torchsim): complete deferred review items with full test coverage
HaoZeke 42bd026
fix(torchsim): fix CI failures
HaoZeke 9bc9a2d
fix(tests): use pytest.warns for uncertainty warning test
HaoZeke ce0fc7a
fix(tests): use tiny threshold to guarantee uncertainty warning fires
HaoZeke fc01389
fix(tests): add filterwarnings marker so pytest.warns captures the wa…
HaoZeke 78c8048
fix(tests): use pytest.raises for warning test (filterwarnings=error)
HaoZeke 626f0f4
fix(torchsim): handle bool pbc from torch-sim, fix warning test regex
HaoZeke da6b961
fix(torchsim): address PR #181 review comments
HaoZeke 160cc23
fix(torchsim): final review cleanup
HaoZeke 7e53f7e
fix(torchsim): address all remaining review items
HaoZeke 66ca9f9
fix(torchsim): address new review comments from 2026-03-24
HaoZeke 5d5f4cb
fix(tests): add uncertainty_threshold=None to test_energy_only_mode
HaoZeke f85bcae
docs(torchsim): re-add getting-started and batched as tutorials
HaoZeke 3c4e6f3
docs(torchsim): convert tutorials to sphinx-gallery .py files
HaoZeke 3664a09
fix(torchsim): ......
HaoZeke fac08a0
fix(docs): make torchsim tutorials runnable in sphinx-gallery
HaoZeke c80d5d1
fix(docs): remove velocities assignment, SimState uses momenta
HaoZeke ef449e7
fix(docs): use nve_init/nve_step functional API for NVE tutorial
HaoZeke d757810
fix(docs): sort imports to satisfy ruff I001
HaoZeke bbaa7e4
Small doc tweaks
Luthaf 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
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,192 @@ | ||
| """ | ||
| .. _torchsim-getting-started: | ||
|
|
||
| Getting started with TorchSim | ||
| ============================= | ||
|
|
||
| This tutorial walks through running a short NVE molecular dynamics | ||
| simulation with a metatomic model and `TorchSim | ||
| <https://torchsim.github.io/torch-sim/>`_. | ||
| """ | ||
|
|
||
| # %% | ||
| # | ||
| # Prerequisites | ||
| # ------------- | ||
| # | ||
| # Install the integration package and its dependencies: | ||
| # | ||
| # .. code-block:: bash | ||
| # | ||
| # pip install metatomic-torchsim | ||
| # | ||
| # We start by importing the modules we need: | ||
|
|
||
| from typing import Dict, List, Optional | ||
|
|
||
| import ase.build | ||
| import torch | ||
| from metatensor.torch import Labels, TensorBlock, TensorMap | ||
|
|
||
| import metatomic.torch as mta | ||
| from metatomic_torchsim import MetatomicModel | ||
|
|
||
|
|
||
| # %% | ||
| # | ||
| # Export a simple model | ||
| # --------------------- | ||
| # | ||
| # For this tutorial we create and export a minimal model that predicts | ||
| # energy as a (trivial) function of atomic positions. The energy must | ||
| # depend on positions so that forces can be computed via autograd. | ||
| # In practice you would use a pre-trained model loaded from a file. | ||
|
|
||
|
|
||
| class HarmonicEnergy(torch.nn.Module): | ||
| """A minimal model: harmonic restraint around initial positions.""" | ||
|
|
||
| def __init__(self, k: float = 0.1): | ||
| super().__init__() | ||
| self.k = k | ||
|
|
||
| def forward( | ||
| self, | ||
| systems: List[mta.System], | ||
| outputs: Dict[str, mta.ModelOutput], | ||
| selected_atoms: Optional[Labels] = None, | ||
| ) -> Dict[str, TensorMap]: | ||
| energies: List[torch.Tensor] = [] | ||
| for system in systems: | ||
| # energy = k * sum(positions^2) -- differentiable w.r.t. positions | ||
| e = self.k * torch.sum(system.positions**2) | ||
| energies.append(e.reshape(1, 1)) | ||
|
|
||
| energy = torch.cat(energies, dim=0) | ||
|
|
||
| block = TensorBlock( | ||
| values=energy, | ||
| samples=Labels("system", torch.arange(len(systems)).reshape(-1, 1)), | ||
| components=[], | ||
| properties=Labels("energy", torch.tensor([[0]])), | ||
| ) | ||
| return { | ||
| "energy": TensorMap(keys=Labels("_", torch.tensor([[0]])), blocks=[block]) | ||
| } | ||
|
|
||
|
|
||
| # %% | ||
| # | ||
| # Build an ``AtomisticModel`` wrapping the raw module: | ||
|
|
||
| raw_model = HarmonicEnergy(k=0.1) | ||
| capabilities = mta.ModelCapabilities( | ||
| length_unit="Angstrom", | ||
| atomic_types=[14], # Silicon | ||
| interaction_range=0.0, | ||
| outputs={"energy": mta.ModelOutput(quantity="energy", unit="eV")}, | ||
| supported_devices=["cpu"], | ||
| dtype="float64", | ||
| ) | ||
|
|
||
| atomistic_model = mta.AtomisticModel( | ||
| raw_model.eval(), mta.ModelMetadata(), capabilities | ||
| ) | ||
|
|
||
| # %% | ||
| # | ||
| # Load the model | ||
| # -------------- | ||
| # | ||
| # Wrap the model with :py:class:`~metatomic_torchsim.MetatomicModel`. | ||
| # You can pass an ``AtomisticModel`` directly, or a path to a saved | ||
| # ``.pt`` file: | ||
|
|
||
| model = MetatomicModel(atomistic_model, device="cpu") | ||
|
|
||
| # %% | ||
| # | ||
| # The wrapper detects the model's dtype and supported devices | ||
| # automatically. Pass ``device="cuda"`` to run on GPU when available. | ||
|
|
||
| print("dtype:", model.dtype) | ||
| print("device:", model.device) | ||
|
|
||
| # %% | ||
| # | ||
| # Build a simulation state | ||
| # ------------------------ | ||
| # | ||
| # TorchSim works with ``SimState`` objects. Convert ASE ``Atoms`` using | ||
| # ``torch_sim.initialize_state``: | ||
|
|
||
| import torch_sim as ts # noqa: E402 | ||
|
|
||
|
|
||
| atoms = ase.build.bulk("Si", "diamond", a=5.43, cubic=True) | ||
| sim_state = ts.initialize_state(atoms, device=model.device, dtype=model.dtype) | ||
|
|
||
| print("Number of atoms:", sim_state.n_atoms) | ||
|
|
||
| # %% | ||
| # | ||
| # Evaluate the model | ||
| # ------------------ | ||
| # | ||
| # Call the model on the simulation state to get energies, forces, and | ||
| # stresses: | ||
|
|
||
| results = model(sim_state) | ||
|
|
||
| print("Energy:", results["energy"]) # shape [1] | ||
| print("Forces shape:", results["forces"].shape) # shape [n_atoms, 3] | ||
| print("Stress shape:", results["stress"].shape) # shape [1, 3, 3] | ||
|
|
||
| # %% | ||
| # | ||
| # Run NVE dynamics | ||
| # ---------------- | ||
| # | ||
| # Use TorchSim's NVE (Velocity Verlet) integrator to run a short trajectory. | ||
| # ``nve_init`` samples momenta from a Maxwell-Boltzmann distribution at the | ||
| # given temperature, and ``nve_step`` advances by one timestep: | ||
|
|
||
| import matplotlib.pyplot as plt # noqa: E402 | ||
| from torch_sim.integrators import nve_init, nve_step # noqa: E402 | ||
| from torch_sim.units import MetalUnits # noqa: E402 | ||
|
|
||
|
|
||
| sim_state = ts.initialize_state(atoms, device=model.device, dtype=model.dtype) | ||
|
|
||
| # Initialize NVE state with momenta at 300 K (in eV units) | ||
| kT = 300.0 * MetalUnits.temperature # kelvin -> eV | ||
| md_state = nve_init(sim_state, model, kT=kT) | ||
|
|
||
| energies = [] | ||
| steps = [] | ||
| dt = 1.0 # femtoseconds | ||
|
|
||
| for step in range(50): | ||
| md_state = nve_step(md_state, model, dt=dt) | ||
| energies.append(md_state.energy.sum().item()) | ||
| steps.append(step) | ||
|
|
||
| plt.plot(steps, energies) | ||
| plt.xlabel("Step") | ||
| plt.ylabel("Potential energy (eV)") | ||
| plt.title("NVE dynamics -- potential energy vs step") | ||
| plt.tight_layout() | ||
| plt.show() | ||
|
|
||
|
|
||
| # %% | ||
| # | ||
| # .. note:: | ||
| # | ||
| # With a real interatomic potential the total energy would stay approximately | ||
| # constant in an NVE simulation, which serves as a basic sanity check. | ||
| # | ||
| # Next steps | ||
| # ---------- | ||
| # | ||
| # - :ref:`torchsim-batched` explains running multiple systems at once |
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.
Uh oh!
There was an error while loading. Please reload this page.