-
Notifications
You must be signed in to change notification settings - Fork 4
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
Add ASE tutorial #43
Merged
Merged
Add ASE tutorial #43
Changes from 46 commits
Commits
Show all changes
66 commits
Select commit
Hold shift + click to select a range
3ea3e6a
Add gradient calculator
frostedoyster 79d161e
Fix linter
frostedoyster e65679d
Loss draft
frostedoyster 8591d7d
Add tests for losses
frostedoyster 8df7e41
Wrap forces and stresses
frostedoyster 0ffc0a9
Clarify cell convention
frostedoyster 9253931
Merge branch 'main' into forces-virials
frostedoyster 9b93eaa
Support multiple model outputs, use new loss
frostedoyster 83c94e6
Fix composition calculator
frostedoyster 4f1c569
Address review
frostedoyster 7c32d9e
Partial draft
frostedoyster 3081a0f
Finished trainer
frostedoyster ed8697f
Make linter happy
frostedoyster 589b586
Merge branch 'main' into finalize-training
frostedoyster 01a528b
Fix small merge issue
frostedoyster aa31433
Add new functions to the documentation
frostedoyster 9061f1c
Add tutorial how to override arch params
PicoCentauri 631d274
Adapt to most recent parser changes
frostedoyster dc523b7
Train with actual train/validation splits
frostedoyster fe0bd01
Fix some small issues
frostedoyster f579652
Merge branch 'arch_override_docs' into finalize-training
frostedoyster 2e82d22
Fix docs build?
frostedoyster 3f9c927
Attempt to export
frostedoyster 0142784
Address reviewer comments
frostedoyster bc60b87
Merge branch 'main' into finalize-training
frostedoyster 6590939
Merge branch 'finalize-training' into export
frostedoyster 236e5a3
Make SOAP-BPNN model saveable
frostedoyster addd65d
Hack better
frostedoyster a7811bc
Update `MANIFEST.in`
frostedoyster f8b2325
Update tests and docs
frostedoyster ecb8279
Add some comments on the hacks
frostedoyster 27e3bc9
Fix `usage.sh`?
frostedoyster 5fb18c1
Add ASE tutorial
frostedoyster 374b88b
Fix docs?
frostedoyster 3acf607
Fix docs??
frostedoyster e7397ac
Merge branch 'main' into export
frostedoyster c34f85c
Fix merge bug
frostedoyster 84a64b5
Try to put a notebook together
frostedoyster 2e004e5
Run correct NVE MD
frostedoyster 199f98a
Also fix units in `metatensor.torch.atomistic`
frostedoyster b88e586
Turn example into python script
frostedoyster ed62a5f
Sphinx gallery?
frostedoyster 82f1c22
Sphinx gallery??
frostedoyster 19f77cb
Fix conf.py
frostedoyster ef9e532
Make README.rst a title
frostedoyster bf891b4
Title?
frostedoyster 793488b
Added sphinx config
PicoCentauri 54fbe61
Some improvments to the tutorial
PicoCentauri e7d240b
Try to run gallery as a subprocess of conf.py
frostedoyster cf069fb
Merge branch 'main' into export
frostedoyster 1623ae1
Retrain model, add symlink
frostedoyster 9dc2a78
Add info about model
PicoCentauri b02a0eb
Use vanilla sphinx-gallery
PicoCentauri ecea35f
More details to the tutorial
PicoCentauri eb54ddf
fix some typos
PicoCentauri 04af489
Merge branch 'export' into ase-tutorial
frostedoyster 12d0c7a
fix wrong title
PicoCentauri 6e5df56
Merge branch 'ase-tutorial' of https://github.com/lab-cosmo/metatenso…
frostedoyster 9fe6305
Fix leftover issue from merge
frostedoyster 4699030
Linter betrayal AGAIN
frostedoyster cc939da
Run example on the fly
PicoCentauri 629f90d
reorder example files
PicoCentauri c8e4bb4
finish restructure
PicoCentauri 33214f2
remove output file
PicoCentauri 4a22182
Merge branch 'main' into ase-tutorial
frostedoyster c22ee68
fix docs
PicoCentauri 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 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 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 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 |
---|---|---|
@@ -1,4 +1,7 @@ | ||
furo | ||
sphinx >= 7 | ||
sphinx-gallery | ||
sphinx-toggleprompt | ||
tomli | ||
|
||
ase # for ASE tutorial |
This file contains 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 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,68 @@ | ||
import os | ||
import shutil | ||
import sys | ||
|
||
import sphinx_gallery.gen_gallery | ||
|
||
|
||
HERE = os.path.realpath(os.path.dirname(__file__)) | ||
|
||
|
||
class AttrDict(dict): | ||
def __init__(self): | ||
super().__init__() | ||
self.__dict__ = self | ||
|
||
|
||
class PseudoSphinxApp: | ||
""" | ||
Class pretending to be a sphinx App, used to configure and run sphinx-gallery | ||
from the command line, without having an actual sphinx project. | ||
""" | ||
|
||
def __init__(self, example): | ||
gallery_dir = os.path.join( | ||
HERE, "tutorials", "gallery", os.path.basename(example) | ||
) | ||
if os.path.exists(gallery_dir): | ||
shutil.rmtree(gallery_dir) | ||
|
||
# the options here are the minimal set of options to get sphinx-gallery to run | ||
# feel free to add more if sphinx-gallery uses more options in the future | ||
self.config = AttrDict() | ||
self.config.html_static_path = [] | ||
self.config.source_suffix = [".rst"] | ||
self.config.default_role = "" | ||
self.config.sphinx_gallery_conf = { | ||
"filename_pattern": ".*", | ||
"examples_dirs": os.path.join(HERE, "..", "..", example), | ||
"gallery_dirs": gallery_dir, | ||
"min_reported_time": 60, | ||
} | ||
|
||
self.builder = AttrDict() | ||
self.builder.srcdir = os.path.join(HERE) | ||
self.builder.outdir = "" | ||
self.builder.name = os.path.basename(example) | ||
|
||
self.extensions = [] | ||
|
||
self.builder.config = AttrDict() | ||
self.builder.config.plot_gallery = "True" | ||
self.builder.config.abort_on_example_error = True | ||
self.builder.config.highlight_language = None | ||
|
||
def add_css_file(self, path): | ||
pass | ||
|
||
|
||
if __name__ == "__main__": | ||
if len(sys.argv) < 2: | ||
print(f"usage: {sys.argv[0]} <example/dir>") | ||
sys.exit(1) | ||
|
||
app = PseudoSphinxApp(example=sys.argv[1]) | ||
|
||
sphinx_gallery.gen_gallery.fill_gallery_conf_defaults(app, app.config) | ||
sphinx_gallery.gen_gallery.update_gallery_conf_builder_inited(app) | ||
sphinx_gallery.gen_gallery.generate_gallery_rst(app) |
This file contains 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 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 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,10 @@ | ||
Tutorials | ||
========= | ||
|
||
This sections includes some more advanced tutorials on the usage of the | ||
``metatensor-models`` package. | ||
|
||
.. toctree:: | ||
:maxdepth: 1 | ||
|
||
gallery/ase/run_ase |
This file contains 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,3 @@ | ||
Running molecular dynamics with ASE | ||
=================================== | ||
|
Binary file not shown.
This file contains 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,91 @@ | ||
""" | ||
Running molecular dynamics with ASE | ||
=================================== | ||
|
||
This tutorial shows how to use an exported model to run an ASE simulation. | ||
""" | ||
|
||
# %% | ||
# | ||
# First, we import the necessary libraries: | ||
|
||
# NumPy | ||
import numpy as np | ||
|
||
# Tools to run the simulation | ||
import ase.md | ||
import ase.md.velocitydistribution | ||
import ase.units | ||
|
||
# Integration with ASE calculator for metatensor atomistic models | ||
from metatensor.torch.atomistic.ase_calculator import MetatensorCalculator | ||
|
||
# Plotting | ||
import matplotlib.pyplot as plt | ||
import ase.visualize.plot | ||
|
||
# The SOAP-BPNN model contains compiled extensions from rascaline.torch | ||
import rascaline.torch | ||
|
||
|
||
# %% | ||
# | ||
# Next, we initialize the simulation, including importing the model: | ||
|
||
# Initial positions (reading them from a file): | ||
atoms = ase.io.read("../../tests/resources/ethanol_reduced_100.xyz") | ||
|
||
# Initialize the velocities: | ||
ase.md.velocitydistribution.MaxwellBoltzmannDistribution(atoms, temperature_K=300) | ||
|
||
# Load the model and register it as the energy calculator for these ``atoms``: | ||
atoms.calc = MetatensorCalculator("exported-model.pt") | ||
|
||
# Define the integrator: | ||
integrator = ase.md.VelocityVerlet( | ||
atoms, | ||
timestep=1.0 * ase.units.fs | ||
) | ||
|
||
# Plot the initial configuration: | ||
ase.visualize.plot.plot_atoms(atoms) | ||
plt.show() | ||
|
||
# %% | ||
# | ||
# Run a short simulation: | ||
|
||
potential_energy = [] | ||
kinetic_energy = [] | ||
total_energy = [] | ||
trajectory = [] | ||
|
||
for step in range(100): | ||
# run a single simulation step | ||
integrator.run(1) | ||
|
||
# collect data about the simulation | ||
potential_energy.append(atoms.get_potential_energy()) | ||
kinetic_energy.append(atoms.get_kinetic_energy()) | ||
total_energy.append(atoms.get_total_energy()) | ||
trajectory.append(atoms.copy()) | ||
|
||
# Convert to numpy arrays | ||
potential_energy = np.array(potential_energy) | ||
kinetic_energy = np.array(kinetic_energy) | ||
total_energy = np.array(total_energy) | ||
|
||
# Plot the final configuration: | ||
ase.visualize.plot.plot_atoms(trajectory[99]) | ||
plt.show() | ||
|
||
# %% | ||
# | ||
# Plot the evolution of kinetic, potential, and total energy. | ||
# The total energy should approximately be conserved: | ||
|
||
plt.plot(range(100), potential_energy-potential_energy.mean(), label="potential energy") | ||
plt.plot(range(100), kinetic_energy-kinetic_energy.mean(), label="kinetic energy") | ||
plt.plot(range(100), total_energy-total_energy.mean(), label="total energy") | ||
plt.legend() | ||
plt.show() |
This file contains 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,21 @@ | ||
defaults: | ||
- architecture: soap_bpnn # architecture used to train the model | ||
- _self_ | ||
|
||
architecture: | ||
training: | ||
batch_size: 16 | ||
num_epochs: 1000 | ||
learning_rate: 0.003 | ||
|
||
# Section defining the parameters for structure and target data | ||
training_set: | ||
structures: | ||
read_from: "../../../tests/resources/ethanol_reduced_100.xyz" | ||
targets: | ||
energy: | ||
key: "energy" | ||
unit: "kcal/mol" # very important to run simulations | ||
|
||
validation_set: 0.1 | ||
test_set: 0.0 |
This file contains 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 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,48 @@ | ||
# Since torch.jit.save cannot handle Labels.single(), we need to replace it with | ||
# Labels(names=["_"], values=_dispatch.zeros_like(block.values, (1, 1))) | ||
# in metatensor-operations. This is a hacky way to do it. | ||
|
||
import os | ||
import metatensor.operations | ||
import metatensor.torch.atomistic | ||
|
||
file = os.path.join( | ||
os.path.dirname(metatensor.operations.__file__), | ||
"reduce_over_samples.py" | ||
) | ||
|
||
# Find the line that contains "Labels.single()" | ||
# and replace "Labels.single()" with | ||
# "Labels(names=["_"], values=_dispatch.zeros_like(block.values, (1, 1)))" | ||
with open(file, "r") as f: | ||
lines = f.readlines() | ||
for i, line in enumerate(lines): | ||
if "samples_label = Labels.single()" in line: | ||
lines[i] = line.replace( | ||
"samples_label = Labels.single()", | ||
"samples_label = Labels(names=[\"_\"], values=_dispatch.zeros_like(block.values, (1, 1)))" | ||
) | ||
break | ||
|
||
with open(file, "w") as f: | ||
f.writelines(lines) | ||
|
||
file = os.path.join( | ||
os.path.dirname(metatensor.torch.atomistic.__file__), | ||
"units.py" | ||
) | ||
|
||
# At the moment, unit handling is incorrect in metatensor.torch.atomistic | ||
# This will fix it: | ||
with open(file, "r") as f: | ||
lines = f.readlines() | ||
for i, line in enumerate(lines): | ||
if "return self._conversions[to_unit] / self._conversions[from_unit]" in line: | ||
lines[i] = line.replace( | ||
"return self._conversions[to_unit] / self._conversions[from_unit]", | ||
"return self._conversions[from_unit] / self._conversions[to_unit]" | ||
) | ||
break | ||
|
||
with open(file, "w") as f: | ||
f.writelines(lines) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Are we hacking metatensor while installing metatensor models? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No, the user has to run this, but it's documented (see export PR) |
This file contains 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.
I don't know if we really need the custom rewrite that we do in metatensor here as well. I think the standard config should be enough for us?
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.
I have no clue but I don't have the time to find out