### Import Libraries and Setup Directory Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_03_force_models.ipynb Imports necessary PyTorch and SchNetPack libraries and creates a directory for tutorial experiments. Ensure these libraries are installed before running. ```python import torch import torchmetrics import schnetpack as spk import schnetpack.transform as trn import pytorch_lightning as pl import os import matplotlib.pyplot as plt import numpy as np forcetut = "./forcetut" if not os.path.exists(forcetut): os.makedirs(forcetut) ``` -------------------------------- ### Install Tensorboard for Visualization Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/docs/getstarted.md Install Tensorboard to enable visualization of training logs and metrics. ```bash pip install tensorboard ``` -------------------------------- ### Install SchNetPack from Source Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/README.md Clone the SchNetPack repository and install it locally. This method allows you to use the most recent code directly from GitHub. ```bash git clone https://github.com/atomistic-machine-learning/schnetpack.git cd schnetpack pip install . ``` -------------------------------- ### Prepare and Setup QM9 Data Module Source: https://context7.com/atomistic-machine-learning/schnetpack/llms.txt Prepare the QM9 dataset by downloading data if it doesn't exist and creating train/validation/test splits. Then, set up the dataloaders for accessing the data. ```python # Setup downloads data if not exists and creates train/val/test splits qm9.prepare_data() qm9.setup() ``` -------------------------------- ### Install Test Dependencies from Source Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/tests/README.md If you have a local copy of the SchNetPack repository and installed from source, use this command to install test dependencies. ```bash pip install .[test] ``` -------------------------------- ### Initialize System Momenta Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Use an Initializer to set atomic momenta based on a target temperature. This example uses UniformInit to also remove center-of-mass motion and rotation. ```python from schnetpack.md import UniformInit system_temperature = 300 # Kelvin # Set up the initializer md_initializer = UniformInit( system_temperature, remove_center_of_mass=True, remove_translation=True, remove_rotation=True, ) # Initialize the system momenta md_initializer.initialize_system(md_system) ``` -------------------------------- ### Install SchNetPack Test Dependencies Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/tests/README.md Use this command to install SchNetPack with all necessary dependencies for running tests. This is typically done via pip. ```bash pip install schnetpack[test] ``` -------------------------------- ### Install SchNetPack with pip Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/README.md Use this command to install the latest stable version of SchNetPack from PyPI. This is the simplest installation method. ```bash pip install schnetpack ``` -------------------------------- ### Start QM9 Training Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/README.md Initiates training of a SchNet model with default settings for the QM9 dataset. The dataset will be downloaded automatically if it doesn't exist. ```bash spktrain experiment=qm9_atomwise ``` -------------------------------- ### Download Example Files for SchNetPack LAMMPS Deployment Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/howtos/lammps.rst Downloads the necessary input files (LAMMPS script, data file, and a trained model) for demonstrating the SchNetPack model deployment with LAMMPS. Use this if the schnetpack repository is not cloned locally. ```bash mkdir aspirin-example cd aspirin-example wget https://raw.githubusercontent.com/atomistic-machine-learning/schnetpack/master/interfaces/lammps/examples/aspirin/aspirin_md.in wget https://raw.githubusercontent.com/atomistic-machine-learning/schnetpack/master/interfaces/lammps/examples/aspirin/aspirin.data wget https://raw.githubusercontent.com/atomistic-machine-learning/schnetpack/master/interfaces/lammps/examples/aspirin/best_model ``` -------------------------------- ### SchNet Forward Pass Example Source: https://context7.com/atomistic-machine-learning/schnetpack/llms.txt Perform a forward pass with a SchNet model using dummy input data. This demonstrates how to provide inputs like atomic numbers, positions, and neighbor indices to obtain scalar representations. ```python # Example forward pass with dummy input inputs = { "_atomic_numbers": torch.tensor([6, 1, 1, 1, 1]), # CH4 "_positions": torch.randn(5, 3), "_idx_i": torch.tensor([0, 0, 0, 0, 1, 2, 3, 4]), "_idx_j": torch.tensor([1, 2, 3, 4, 0, 0, 0, 0]), "_Rij": torch.randn(8, 3), } outputs = schnet(inputs) print(f"Scalar representation shape: {outputs['scalar_representation'].shape}") # Output: Scalar representation shape: torch.Size([5, 128]) ``` -------------------------------- ### SchNetPack Molecular Dynamics Simulator Source: https://context7.com/atomistic-machine-learning/schnetpack/llms.txt GPU-accelerated molecular dynamics simulation setup including system initialization, integrators, and simulation hooks. ```python import torch from schnetpack.md import Simulator, System from schnetpack.md.calculators import SchNetPackCalculator from schnetpack.md.integrators import VelocityVerlet from schnetpack.md.initial_conditions import MaxwellBoltzmannInit from schnetpack.md.simulation_hooks import ( LangevinThermostat, FileLogger, MoleculeStream, ) from schnetpack.transform import MatScipyNeighborList from ase.io import read # Load structure atoms = read("structure.xyz") # Initialize MD system system = System() system.load_molecules( atoms, n_replicas=1, # For path-integral MD, set > 1 ) # Initialize velocities initializer = MaxwellBoltzmannInit( temperature=300, # Kelvin remove_translation=True, remove_rotation=True, ) initializer.initialize_system(system) # Create calculator calculator = SchNetPackCalculator( model_file="./best_model", neighbor_list=MatScipyNeighborList(cutoff=5.0), energy_key="energy", force_key="forces", energy_unit="kcal/mol", position_unit="Ang", ) # Setup integrator integrator = VelocityVerlet(time_step=0.5) # fs # Setup simulation hooks hooks = [ LangevinThermostat( temperature_bath=300, time_constant=100, # fs ), FileLogger( filename="simulation.hdf5", buffer_size=100, data_streams=[ MoleculeStream(store_velocities=True), ], ), ] # Create and run simulator simulator = Simulator( system=system, integrator=integrator, calculator=calculator, simulator_hooks=hooks, progress=True, ) # Run simulation simulator.simulate(n_steps=10000) # Save state for restart state = simulator.state_dict torch.save(state, "simulation_state.pt") # Restart simulation state = torch.load("simulation_state.pt") simulator.restart_simulation(state) simulator.simulate(n_steps=10000) ``` -------------------------------- ### Run MD Simulation Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Execute the molecular dynamics simulation for a specified number of steps. This command starts the simulation process using the configured simulator and hooks. ```python n_steps = 20000 md_simulator.simulate(n_steps) ``` -------------------------------- ### Build Neural Network Potential Source: https://context7.com/atomistic-machine-learning/schnetpack/llms.txt Construct a complete neural network potential model by combining a representation network (e.g., PaiNN) with output modules for property prediction. This example sets up a model to predict energy and forces. ```python import torch from schnetpack.model import NeuralNetworkPotential from schnetpack.representation import PaiNN from schnetpack.atomistic import Atomwise, Forces from schnetpack.nn.radial import GaussianRBF from schnetpack.nn.cutoff import CosineCutoff from schnetpack.transform import CastTo32 cutoff = 5.0 # Create representation representation = PaiNN( n_atom_basis=128, n_interactions=3, radial_basis=GaussianRBF(n_rbf=20, cutoff=cutoff), cutoff_fn=CosineCutoff(cutoff=cutoff), ) # Create output modules output_modules = [ Atomwise( n_in=128, n_out=1, n_layers=2, aggregation_mode="sum", output_key="energy", ), Forces( calc_forces=True, calc_stress=False, energy_key="energy", force_key="forces", ), ] # Build complete model model = NeuralNetworkPotential( representation=representation, output_modules=output_modules, postprocessors=[CastTo32()], input_dtype_str="float32", do_postprocessing=True, ) # Model outputs both energy and forces via automatic differentiation print(f"Model outputs: {model.model_outputs}") # ['energy', 'forces'] print(f"Required derivatives: {model.required_derivatives}") # ['_positions'] ``` -------------------------------- ### Assemble and Configure Simulator Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Creates the simulator instance and applies device and precision settings. ```python # Assemble the simulator rpmd_simulator = Simulator( rpmd_system, rpmd_integrator, md_calculator, simulator_hooks=rpmd_hooks ) rpmd_simulator = rpmd_simulator.to(md_device) rpmd_simulator = rpmd_simulator.to(md_precision) ``` -------------------------------- ### Instantiate and prepare QM9 dataset Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_01_preparing_data.ipynb Initialize the QM9 benchmark dataset with specific batch sizes, splits, and neighbor list transforms. ```python from schnetpack.datasets import QM9 from schnetpack.transform import ASENeighborList qm9data = QM9( "./qm9.db", batch_size=10, num_train=110000, num_val=10000, split_file="./split_qm9.npz", transforms=[ASENeighborList(cutoff=5.0)], ) qm9data.prepare_data() qm9data.setup() ``` -------------------------------- ### Launch TensorBoard for Training Logs Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_03_force_models.ipynb Command to visualize training progress using TensorBoard. ```bash tensorboard --logdir=forcetut/lightning_logs ``` -------------------------------- ### Get predictions with uncertainty Source: https://context7.com/atomistic-machine-learning/schnetpack/llms.txt Calculate energy, forces, and uncertainty using an ensemble calculator. ```python atoms = Atoms("CH4", positions=[[0, 0, 0], [1, 1, 1], [-1, 1, -1], [1, -1, -1], [-1, -1, 1]]) atoms.calc = ensemble_calc energy = atoms.get_potential_energy() # Mean energy from ensemble forces = atoms.get_forces() # Mean forces from ensemble uncertainty = ensemble_calc.get_uncertainty(atoms) print(f"Mean energy: {energy:.4f} eV") print(f"Uncertainty: {uncertainty}") # Dict with AbsoluteUncertainty, RelativeUncertainty values ``` -------------------------------- ### Override Configuration for Experiments Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/docs/userguide/configs.md Example of an experiment configuration file that overrides default model and data settings. ```default # @package _global_ defaults: - override /model: nnp - override /data: qm9 ``` -------------------------------- ### Initialize System with ASE Molecules Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Create a System instance and load molecular structures from ASE Atoms objects. Ensure the input units are specified for correct internal conversion. ```python from schnetpack.md import System from ase.io import read # Load atoms with ASE molecule = read(molecule_path) # Number of molecular replicas n_replicas = 1 # Create system instance and load molecule md_system = System() md_system.load_molecules(molecule, n_replicas, position_unit_input="Angstrom") ``` -------------------------------- ### Initializing RPMD System Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Configures a system with multiple replicas for Ring Polymer Molecular Dynamics simulations. ```python # Number of beads in RPMD simulation n_replicas = 4 # Set up the system, load structures rpmd_system = System() rpmd_system.load_molecules(molecule, n_replicas, position_unit_input="Angstrom") ``` -------------------------------- ### Initialize Atoms and Run Langevin Dynamics Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/howtos/howto_ensemble_calculation.ipynb Sets up initial atoms, defines a calculator, and runs a Langevin dynamics simulation. Collects temperature, uncertainties, and trajectory data over multiple steps and temperatures. ```python from schnetpack.md import MaxwellBoltzmannDistribution from ase.md.langevin import Langevin from ase.io import read from ase import units from tqdm import tqdm # setting up initial atoms atoms = read('../../tests/testdata/md_ethanol.xyz', index=0) atoms.calc = abs_ensemble_calculator MaxwellBoltzmannDistribution(atoms, temperature_K=target_temperatures[0]) ats_traj = [] uncertainties = [] temp = [] for target_temperature in target_temperatures: print(f"Temp: {target_temperature:.2f} K") for step in tqdm(range(n_steps // sampling_interval)): dyn = Langevin( atoms, timestep=step_size * units.fs, temperature_K=target_temperature, friction=0.01 / units.fs ) dyn.run(sampling_interval) temp.append(atoms.get_temperature()) uncertainties.append(abs_ensemble_calculator.get_uncertainty(atoms)) ats_traj.append(atoms.copy()) ``` -------------------------------- ### Get Predictions and Uncertainty from Ensemble Calculator Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/howtos/howto_ensemble_calculation.ipynb Retrieves the total energy, atomic forces, and calculated uncertainty values for the given atomic system using the ensemble calculator. ```python print("Prediction:") print("energy:", atoms.get_total_energy()) print("forces:", atoms.get_forces()) print("uncertainty:", ensemble_calculator.get_uncertainty(atoms)) ``` -------------------------------- ### View Tensorboard logs Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/docs/getstarted.md Launches the Tensorboard server to visualize training results from a specific run directory. ```bash $ tensorboard --logdir= ``` -------------------------------- ### Create Working Directory Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/README.md Use these commands to create a working directory for storing data and training runs. ```bash mkdir spk_workdir cd spk_workdir ``` -------------------------------- ### Adjust Loss Weights for Energy and Forces Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/README.md Customizes the loss weights for energy and forces during training on the MD17 dataset. The example sets a stronger weight for force prediction. ```bash spktrain experiment=md17 data.molecule=uracil task.outputs.0.loss_weight=0.005 task.outputs.1.loss_weight=0.995 ``` -------------------------------- ### Initialize HDF5Loader Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Instantiate the HDF5Loader by providing the path to the simulation output file. ```python from schnetpack.md.data import HDF5Loader data = HDF5Loader(log_file) ``` -------------------------------- ### Set Precision and Device for Simulator Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Configures the computational device (GPU or CPU) and floating-point precision (e.g., float32) for the MD simulator. This step is recommended before starting the simulation. ```python import torch # check if a GPU is available and use a CPU otherwise if torch.cuda.is_available(): md_device = "cuda" else: md_device = "cpu" # use single precision md_precision = torch.float32 # set precision md_simulator = md_simulator.to(md_precision) ``` -------------------------------- ### PaiNN Forward Pass Example Source: https://context7.com/atomistic-machine-learning/schnetpack/llms.txt Perform a forward pass with a PaiNN model. This demonstrates how PaiNN outputs both scalar and vector representations, which are essential for predicting properties like dipole moments. ```python # Forward pass returns both scalar and vector representations inputs = { "_atomic_numbers": torch.tensor([8, 1, 1]), # H2O "_positions": torch.tensor([[0.0, 0.0, 0.0], [0.96, 0.0, 0.0], [0.24, 0.93, 0.0]]), "_idx_i": torch.tensor([0, 0, 1, 2]), "_idx_j": torch.tensor([1, 2, 0, 0]), "_Rij": torch.randn(4, 3), } outputs = painn(inputs) print(f"Scalar representation: {outputs['scalar_representation'].shape}") # [3, 128] print(f"Vector representation: {outputs['vector_representation'].shape}") # [3, 3, 128] ``` -------------------------------- ### Initialize simulation directory Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Creates a dedicated directory for storing simulation outputs if it does not already exist. ```python import os md_workdir = "mdtut" # Gnerate a directory of not present if not os.path.exists(md_workdir): os.mkdir(md_workdir) ``` -------------------------------- ### Initialize AseInterface Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_03_force_models.ipynb Configures the AseInterface with model paths, neighbor lists, unit definitions, and hardware settings. ```python ethanol_ase = spk.interfaces.AseInterface( molecule_path, ase_dir, model_file=model_path, neighbor_list=trn.ASENeighborList(cutoff=5.0), energy_key=MD17.energy, force_key=MD17.forces, energy_unit="kcal/mol", position_unit="Ang", device="cpu", dtype=torch.float64, ) ``` -------------------------------- ### SchNet Representation Configuration Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/docs/userguide/configs.md Example configuration for the SchNet representation, including atom basis, interactions, radial basis functions, and cutoff functions. This is used when overriding the default model representation. ```yaml model: representation: _target_: schnetpack.representation.SchNet n_atom_basis: 128 n_interactions: 6 radial_basis: _target_: schnetpack.nn.radial.GaussianRBF n_rbf: 20 cutoff: ${globals.cutoff} cutoff_fn: _target_: schnetpack.nn.cutoff.CosineCutoff cutoff: ${globals.cutoff} ``` -------------------------------- ### Train on MD17 Dataset for a Specific Molecule Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/README.md Starts training on the MD17 dataset for a specified molecule, e.g., 'uracil'. This configuration selects appropriate representation and output modules for potential energy surface prediction. ```bash spktrain experiment=md17 data.molecule=uracil ``` -------------------------------- ### Initialize QM9 Data Module Source: https://context7.com/atomistic-machine-learning/schnetpack/llms.txt Initialize the QM9 dataset module, which handles automatic downloading and loading of the QM9 benchmark dataset. Specify datapath, batch size, dataset splits, properties to load, transformations, and units. ```python import schnetpack as spk from schnetpack.datasets import QM9 from schnetpack.transform import ASENeighborList # Initialize QM9 data module with automatic download qm9 = QM9( datapath="./qm9.db", batch_size=32, num_train=110000, num_val=10000, num_test=13885, load_properties=[QM9.U0, QM9.homo, QM9.lumo, QM9.gap], transforms=[ASENeighborList(cutoff=5.0)], remove_uncharacterized=True, property_units={QM9.U0: "eV"}, # Convert Hartree to eV distance_unit="Ang", ) ``` -------------------------------- ### Get Total Energy using SpkCalculator Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_02_qm9.ipynb Assigns the initialized SpkCalculator to an ASE Atoms object and retrieves the total energy. The calculator handles unit conversions to ASE's internal units (eV for energy). ```python atoms.calc = calculator print("Prediction:", atoms.get_total_energy()) ``` -------------------------------- ### Set up Checkpoint Logger Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Configure the Checkpoint hook to save the system and simulation state at regular intervals. Specify the file path and the frequency for generating checkpoints. ```python # Set the path to the checkpoint file chk_file = os.path.join(md_workdir, "simulation.chk") # Create the checkpoint logger checkpoint = callback_hooks.Checkpoint(chk_file, every_n_steps=100) # Update the simulation hooks simulation_hooks.append(checkpoint) ``` -------------------------------- ### View TensorBoard Logs Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/README.md Command to launch the TensorBoard interface for visualizing training results. ```bash tensorboard --logdir= ``` -------------------------------- ### Initialize System Momenta Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Initializes the system momenta for the RPMD system. ```python md_initializer.initialize_system(rpmd_system) ``` -------------------------------- ### Initialize SchNetPack Environment Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_02_qm9.ipynb Imports necessary modules and creates a local directory for storing data and model files. ```python import os import schnetpack as spk from schnetpack.datasets import QM9 import schnetpack.transform as trn import torch import torchmetrics import pytorch_lightning as pl qm9tut = "./qm9tut" if not os.path.exists("qm9tut"): os.makedirs(qm9tut) ``` -------------------------------- ### Initialize Langevin Thermostat Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Configures a Langevin thermostat with a specific bath temperature and time constant for NVT simulations. ```python from schnetpack.md.simulation_hooks import LangevinThermostat # Set temperature and thermostat constant bath_temperature = 300 # K time_constant = 100 # fs # Initialize the thermostat langevin = LangevinThermostat(bath_temperature, time_constant) ``` -------------------------------- ### Prepare Molecule for ASE Interface Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_03_force_models.ipynb Generates a directory and saves a molecule configuration as an XYZ file for use with the AseInterface. ```python from ase import io # Generate a directory for the ASE computations ase_dir = os.path.join(forcetut, "ase_calcs") if not os.path.exists(ase_dir): os.mkdir(ase_dir) # Write a sample molecule molecule_path = os.path.join(ase_dir, "ethanol.xyz") io.write(molecule_path, atoms, format="xyz") ``` -------------------------------- ### Import ASEAtomsData Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_01_preparing_data.ipynb Import the base class for handling ASE database files. ```python from schnetpack.data import ASEAtomsData ``` -------------------------------- ### Basic `spkmd` Command Line Input Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/docs/userguide/md.md Use this command to initiate an MD simulation with specified parameters. Ensure the model and structure files are accessible. ```default spkmd simulation_dir=mdtut_cli system.molecule_file=md_ethanol.xyz calculator.model_file=md_ethanol.model calculator.neighbor_list.cutoff=5.0 ``` -------------------------------- ### Create and Edit Custom Experiment Configuration Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/docs/userguide/configs.md Set up the directory structure for custom configurations and edit the experiment configuration file. The config directory is automatically detected if it's in the current working directory. ```bash # create main config directory and subdirectory for experiment config group $ mkdir configs $ mkdir configs/experiment # create experiment and edit config $ vim my_configs/experiments/my_experiment.yaml # explicitly stating config dir is not required since it is in current working dir $ spktrain experiment=my_experiment ``` -------------------------------- ### Initialize SchNetPack Calculator and Optimizer Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_05_materials.ipynb This Python code initializes the SchNetPack calculator using `SpkCalculator` and sets up the L-BFGS optimizer from ASE for structure optimization, including `ExpCellFilter` for cell dynamics. ```python import schnetpack as spk from schnetpack.transform import ASENeighborList from schnetpack.interfaces.ase_interface import SpkCalculator from ase.optimize.lbfgs import LBFGS from ase.constraints import ExpCellFilter ``` -------------------------------- ### Initialize Batchwise Calculator Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/howtos/howto_batchwise_relaxations.ipynb Load the force field model and configure the BatchwiseCalculator for energy and force calculations. ```python # model_path = "../../tests/testdata/md_ethanol.model" ## set device # device = torch.device("cpu") ## load model # model = torch.load(model_path, map_location=device, weights_only=False) ## define neighbor list # cutoff = model.representation.cutoff.item() # nbh_list=spk.transform.MatScipyNeighborList(cutoff=cutoff) ## build atoms converter # atoms_converter = AtomsConverter( # neighbor_list=nbh_list, # device=device, # ) ## build calculator # calculator = BatchwiseCalculator( # model=model_path, # atoms_converter=atoms_converter, # device=device, # energy_unit="kcal/mol", # position_unit="Ang", # ) ``` -------------------------------- ### Assemble the Atomistic Training Task Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_03_force_models.ipynb Initialize the training task by combining the model, defined outputs, and optimizer settings. ```python task = spk.task.AtomisticTask( model=nnpot, outputs=[output_energy, output_forces], optimizer_cls=torch.optim.AdamW, optimizer_args={"lr": 1e-4}, ) ``` -------------------------------- ### Train with Custom Directories and Batch Size Source: https://context7.com/atomistic-machine-learning/schnetpack/llms.txt Customize training by specifying data directories, run paths, and batch size using the `spktrain` CLI. This allows for flexible data management and resource allocation. ```bash spktrain experiment=qm9_atomwise run.data_dir=/my/data/dir run.path=~/all_my_runs run.id=this_run data.batch_size=64 ``` -------------------------------- ### Create SchnetPack Dataset with ASE Format Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_05_materials.ipynb Initialize a new SchnetPack dataset using the `create_dataset` function. Specify the database path, format (ASE), distance unit, and a dictionary mapping properties to their units. Unitless properties like `considered_atoms` should have an empty string as their unit. ```python from schnetpack.data import create_dataset, AtomsDataFormat db_path = "./si16.db" new_dataset = create_dataset( datapath=db_path, format=AtomsDataFormat.ASE, distance_unit="Ang", property_unit_dict=dict( energy="eV", forces="eV/Ang", stress="eV/Ang/Ang/Ang", considered_atoms="", filtered_out_neighbors="", ), ) ``` -------------------------------- ### Initialize SpkCalculator for ASE Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_02_qm9.ipynb Creates an SpkCalculator to interface SchNetPack models with ASE. This requires the model path, a neighbor list, the key for the energy property, and optionally units, device, and force key. ```python calculator = spk.interfaces.SpkCalculator( model=os.path.join(qm9tut, "best_inference_model"), # path to model neighbor_list=trn.ASENeighborList(cutoff=5.0), # neighbor list energy_key=QM9.U0, # name of energy property in model force_key=None, energy_unit="eV", # units of energy property device="cpu", # device for computation ) ``` -------------------------------- ### Run simulation from config file Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/docs/userguide/md.md Command to execute a molecular dynamics simulation using a specified YAML configuration file. ```default spkmd simulation_dir=md_from_config load_config=md_input_langevin.yaml ``` -------------------------------- ### Set up TensorBoard Logger for Monitoring Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Configure TensorBoardLogger to monitor simulation properties like energy, temperature, pressure, and volume. Specify the directory for log files and the properties to track. ```python # directory where tensorboard log will be stored to tensorboard_dir = os.path.join(md_workdir, "logs") tensorboard_logger = callback_hooks.TensorBoardLogger( tensorboard_dir, ["energy", "temperature"], # properties to log ) # update simulation hooks simulation_hooks.append(tensorboard_logger) ``` -------------------------------- ### Initialize Neighbor List for MD Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Sets up a neighbor list for molecular dynamics simulations using SchNetPack. Requires specifying a cutoff radius and buffer region, and choosing a base neighbor list implementation like ASENeighborList. ```python from schnetpack.md.neighborlist_md import NeighborListMD from schnetpack.transform import ASENeighborList # set cutoff and buffer region cutoff = 5.0 # Angstrom (units used in model) cutoff_shell = 2.0 # Angstrom # initialize neighbor list for MD using the ASENeighborlist as basis md_neighborlist = NeighborListMD( cutoff, cutoff_shell, ASENeighborList, ) ``` -------------------------------- ### Assemble Simulation Hooks Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Configures logging, checkpointing, and TensorBoard monitoring for the RPMD simulation. ```python # Logging rpmd_log_file = os.path.join(md_workdir, "rpmd_simulation.hdf5") rpmd_file_logger = callback_hooks.FileLogger( rpmd_log_file, buffer_size, data_streams=[ callback_hooks.MoleculeStream( store_velocities=True, ), callback_hooks.PropertyStream(["energy"]), ], ) # Checkpoints rpmd_chk_file = os.path.join(md_workdir, "rpmd_simulation.chk") rpmd_checkpoint = callback_hooks.Checkpoint(rpmd_chk_file, every_n_steps=100) # Tensorboard rpmd_tensorboard_dir = os.path.join(md_workdir, "rpmd_logs") rpmd_tensorboard_logger = callback_hooks.TensorBoardLogger( rpmd_tensorboard_dir, ["energy", "temperature"], ) # Assemble the hooks: rpmd_hooks = [ pile, rpmd_file_logger, rpmd_checkpoint, rpmd_tensorboard_logger, ] ``` -------------------------------- ### Initialize SpkCalculator for ASE Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_03_force_models.ipynb Creates an ASE calculator using a trained model, specifying energy and force keys along with their respective units. ```python calculator = spk.interfaces.SpkCalculator( model=model_path, neighbor_list=trn.ASENeighborList(cutoff=5.0), energy_key=MD17.energy, force_key=MD17.forces, energy_unit="kcal/mol", position_unit="Ang", ) atoms.calc = calculator print("Prediction:") print("energy:", atoms.get_total_energy()) print("forces:", atoms.get_forces()) ``` -------------------------------- ### Set Up LBFGS Optimizer and Ensemble Calculator Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/howtos/howto_ensemble_calculation.ipynb Initializes the LBFGS optimizer for atomic systems and assigns an ensemble calculator to the atoms object. This connects the prediction engine to the system for optimization. ```python optimizer = LBFGS(atoms) atoms.calc = ensemble_calculator ``` -------------------------------- ### Load Initial Structures Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/howtos/howto_batchwise_relaxations.ipynb Read initial structures from a file using ASE. ```python # input_structure_file = "../../tests/testdata/md_ethanol.xyz" ## load initial structures # ats = read(input_structure_file, index=":") ``` -------------------------------- ### AseInterface for Simulations Source: https://context7.com/atomistic-machine-learning/schnetpack/llms.txt High-level interface for geometry optimization, normal mode analysis, and molecular dynamics using ASE. ```python from schnetpack.interfaces import AseInterface from schnetpack.transform import ASENeighborList from ase.optimize import LBFGS # Create interface interface = AseInterface( molecule_path="molecule.xyz", working_dir="./simulation", model_file="./best_model", neighbor_list=ASENeighborList(cutoff=5.0), energy_key="energy", force_key="forces", energy_unit="eV", position_unit="Ang", device="cuda", optimizer_class=LBFGS, fixed_atoms=[0, 1], # Fix first two atoms ) # Single point calculation interface.calculate_single_point() # Geometry optimization interface.optimize(fmax=0.01, steps=500) # Molecular dynamics interface.init_md( name="nvt_simulation", time_step=0.5, # fs temp_init=300, # K temp_bath=300, # K (Langevin thermostat, None for NVE) interval=10, # Save every 10 steps ) interface.run_md(steps=10000) # Normal mode analysis interface.compute_normal_modes(write_jmol=True) # Save final geometry interface.save_molecule("final", file_format="extxyz") ``` -------------------------------- ### Import SchNetPack and ASE modules Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/howtos/howto_batchwise_relaxations.ipynb Required imports for setting up batchwise optimization and handling ASE atoms. ```python # import os # import shutil # import torch # from ase.io import read # import schnetpack as spk # from schnetpack import properties # from schnetpack.interfaces.ase_interface import AtomsConverter # from schnetpack.interfaces.batchwise_optimization import ASEBatchwiseLBFGS, BatchwiseCalculator ``` -------------------------------- ### Create and Populate SchNetPack Database Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_01_preparing_data.ipynb Creates a new SchNetPack database file from a list of ASE Atoms objects and their corresponding properties. It specifies units for distances and properties. ```python %rm './new_dataset.db' new_dataset = ASEAtomsData.create( "./new_dataset.db", distance_unit="Ang", property_unit_dict={"energy": "kcal/mol", "forces": "kcal/mol/Ang"}, ) new_dataset.add_systems(property_list, atoms_list) ``` -------------------------------- ### Initialize Simulator with Hooks Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Initialize the MD simulator with the collected simulation hooks. This step integrates the configured loggers and callbacks into the simulation process. ```python md_simulator = Simulator( md_system, md_integrator, md_calculator, simulator_hooks=simulation_hooks ) md_simulator = md_simulator.to(md_precision) md_simulator = md_simulator.to(md_device) ``` -------------------------------- ### Load and Configure QM9 Dataset Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_02_qm9.ipynb Configures the QM9 dataset loader with specific transforms, property units, and data splitting parameters. ```python %rm split.npz qm9data = QM9( "./qm9.db", batch_size=100, num_train=1000, num_val=1000, transforms=[ trn.ASENeighborList(cutoff=5.0), trn.RemoveOffsets(QM9.U0, remove_mean=True, remove_atomrefs=True), trn.CastTo32(), ], property_units={QM9.U0: "eV"}, num_workers=1, split_file=os.path.join(qm9tut, "split.npz"), pin_memory=True, # set to false, when not using a GPU load_properties=[QM9.U0], # only load U0 property ) qm9data.prepare_data() qm9data.setup() ``` -------------------------------- ### Initialize AtomsConverter Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_02_qm9.ipynb Sets up an AtomsConverter for converting ASE Atoms objects into SchNetPack input format. A cutoff radius for neighbor lists and the desired data type should be specified. ```python converter = spk.interfaces.AtomsConverter( neighbor_list=trn.ASENeighborList(cutoff=5.0), dtype=torch.float32 ) ``` -------------------------------- ### Initialize Simulator for MD Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Brings together the system, integrator, and calculator to perform MD simulations. The Simulator orchestrates the simulation loop over time steps. ```python from schnetpack.md import Simulator md_simulator = Simulator(md_system, md_integrator, md_calculator) ``` -------------------------------- ### Add Systems to the SchnetPack Dataset Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_05_materials.ipynb Populate the newly created dataset by adding systems using the `add_systems` method. This method takes a list of data dictionaries and a corresponding list of ASE Atoms objects. ```python new_dataset.add_systems( property_list=[data], atoms_list=[atoms], ) ``` -------------------------------- ### Inspect Loaded Properties Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_03_force_models.ipynb Prints the keys of the properties dictionary for the first data point in the loaded dataset to verify that 'energy' and 'forces' are included. This confirms the dataset is ready for force-based model training. ```python properties = ethanol_data.dataset[0] print("Loaded properties:\n", *["{:s}\n".format(i) for i in properties.keys()]) ``` -------------------------------- ### Initialize Absolute Uncertainty Calculator Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/howtos/howto_ensemble_calculation.ipynb Sets up an `AbsoluteUncertainty` calculator with specified weights for energy and force. This is used within an ensemble calculator. ```python uncertainty_abs = AbsoluteUncertainty(energy_weight=0.5,force_weight=1.0) ``` -------------------------------- ### Visualize MD Results Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_03_force_models.ipynb Loads simulation logs and prepares data for plotting energy evolution. ```python # Load logged results results = np.loadtxt(os.path.join(ase_dir, "simulation.log"), skiprows=1) # Determine time axis time = results[:, 0] # Load energies energy_tot = results[:, 1] energy_pot = results[:, 2] energy_kin = results[:, 3] # Construct figure plt.figure(figsize=(14, 6)) ``` -------------------------------- ### Initialize SchNetPack Calculator for MD Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Configures the SchNetPackCalculator for MD simulations. Requires the path to a trained model, force and energy keys, units for energy and positions, and the initialized neighbor list. Optional parameters include energy_key and required_properties. ```python from schnetpack.md.calculators import SchNetPackCalculator from schnetpack import properties md_calculator = SchNetPackCalculator( model_path, # path to stored model "forces", # force key "kcal/mol", # energy units "Angstrom", # length units md_neighborlist, # neighbor list energy_key="energy", # name of potential energies required_properties=[], # additional properties extracted from the model ) ``` -------------------------------- ### Set up PyTorch Lightning Trainer and Callbacks Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_02_qm9.ipynb Configures the PyTorch Lightning Trainer with TensorBoard logging and a ModelCheckpoint callback to save the best performing model during training. The trainer is then used to fit the AtomisticTask to the provided data module. ```python logger = pl.loggers.TensorBoardLogger(save_dir=qm9tut) callbacks = [ spk.train.ModelCheckpoint( model_path=os.path.join(qm9tut, "best_inference_model"), save_top_k=1, monitor="val_loss", ) ] trainer = pl.Trainer( callbacks=callbacks, logger=logger, default_root_dir=qm9tut, max_epochs=3, # for testing, we restrict the number of epochs ) trainer.fit(task, datamodule=qm9data) ``` -------------------------------- ### Configure Ring Polymer Integrator Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Sets up the RingPolymer integrator with a smaller time step for numerical stability. ```python from schnetpack.md.integrators import RingPolymer # Here, a smaller time step is required for numerical stability rpmd_time_step = 0.2 # fs # Initialize the integrator, RPMD also requires a polymer temperature which determines the coupling of beads. # Here, we set it to the system temperature rpmd_integrator = RingPolymer( rpmd_time_step, n_replicas, system_temperature, ) ``` -------------------------------- ### Run Molecular Dynamics with Langevin Thermostat Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_03_force_models.ipynb Configures and executes a molecular dynamics simulation at a target temperature using the AseInterface. ```python ethanol_ase.optimize(fmax=1e-2) # reoptimize structure ethanol_ase.init_md("simulation_300K", temp_bath=300, reset=True) ethanol_ase.run_md(20000) ``` -------------------------------- ### Define MD Simulation Parameters Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/howtos/howto_ensemble_calculation.ipynb Sets up parameters for a molecular dynamics simulation, including target temperatures, number of steps, sampling interval, and step size. ```python target_temperatures = [_ for _ in range(50, 800, 100)] n_steps = 1000 sampling_interval = 10 step_size = 0.5 ``` -------------------------------- ### Run Molecular Dynamics Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_03_force_models.ipynb Initializes and executes a molecular dynamics simulation for a specified number of steps. ```python ethanol_ase.init_md("simulation") ``` ```python ethanol_ase.run_md(1000) ``` -------------------------------- ### Create Custom Atomistic Dataset Source: https://context7.com/atomistic-machine-learning/schnetpack/llms.txt Create a custom atomistic dataset using `ASEAtomsData`. This involves specifying the database path, distance units, property units, and atom references. It allows for flexible data storage and management. ```python import numpy as np from ase import Atoms from schnetpack.data import ASEAtomsData, AtomsDataModule from schnetpack.transform import ASENeighborList # Create a new dataset dataset = ASEAtomsData.create( datapath="./my_dataset.db", distance_unit="Ang", property_unit_dict={ "energy": "eV", "forces": "eV/Ang", "dipole": "Debye", }, atomrefs={"energy": [0.0, -13.6, 0.0, 0.0, 0.0, 0.0, -1029.5, -1485.3, -2042.6]}, # H, ..., C, N, O ) ``` -------------------------------- ### Set up FileLogger for Data Collection Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_04_molecular_dynamics.ipynb Configure FileLogger to store positions, velocities, and energy predictions to an HDF5 database. Specify buffer size, data streams, logging frequency, and floating-point precision. ```python from schnetpack.md.simulation_hooks import callback_hooks # Path to database log_file = os.path.join(md_workdir, "simulation.hdf5") # Size of the buffer buffer_size = 100 # Set up data streams to store positions, momenta and the energy data_streams = [ callback_hooks.MoleculeStream(store_velocities=True), callback_hooks.PropertyStream(target_properties=[properties.energy]), ] # Create the file logger file_logger = callback_hooks.FileLogger( log_file, buffer_size, data_streams=data_streams, every_n_steps=1, # logging frequency precision=32, # floating point precision used in hdf5 database ) # Update the simulation hooks simulation_hooks.append(file_logger) ``` -------------------------------- ### Langevin thermostat configuration file Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/docs/userguide/md.md A YAML configuration file defining the calculator, system, dynamics, and callbacks for a Langevin thermostat simulation. ```default calculator: neighbor_list: _target_: schnetpack.md.neighborlist_md.NeighborListMD cutoff: 5.0 cutoff_shell: 2.0 requires_triples: false base_nbl: schnetpack.transform.ASENeighborList collate_fn: schnetpack.data.loader._atoms_collate_fn _target_: schnetpack.md.calculators.SchNetPackCalculator required_properties: - energy - forces model_file: md_ethanol.model force_key: forces energy_unit: kcal / mol position_unit: Angstrom energy_key: energy stress_key: null script_model: false system: initializer: _target_: schnetpack.md.UniformInit temperature: 300 remove_center_of_mass: true remove_translation: true remove_rotation: true wrap_positions: false molecule_file: md_ethanol.xyz load_system_state: null n_replicas: 1 position_unit_input: Angstrom mass_unit_input: 1.0 dynamics: integrator: _target_: schnetpack.md.integrators.VelocityVerlet time_step: 0.5 n_steps: 20000 thermostat: _target_: schnetpack.md.simulation_hooks.LangevinThermostat temperature_bath: 300.0 time_constant: 100.0 barostat: null progress: true simulation_hooks: [] callbacks: checkpoint: _target_: schnetpack.md.simulation_hooks.Checkpoint checkpoint_file: checkpoint.chk every_n_steps: 10 hdf5: _target_: schnetpack.md.simulation_hooks.FileLogger filename: simulation.hdf5 buffer_size: 100 data_streams: - _target_: schnetpack.md.simulation_hooks.MoleculeStream store_velocities: true - _target_: schnetpack.md.simulation_hooks.PropertyStream target_properties: - energy every_n_steps: 1 precision: ${precision} tensorboard: _target_: schnetpack.md.simulation_hooks.TensorBoardLogger log_file: logs properties: - energy - temperature every_n_steps: 10 device: cuda precision: 32 seed: null simulation_dir: mdtut_cli overwrite: false restart: null ``` -------------------------------- ### Change Individual Parameters Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/README.md Demonstrates how to change specific parameters like the data directory and batch size directly from the command line. ```bash spktrain experiment=qm9_atomwise run.data_dir= data.batch_size=64 ``` -------------------------------- ### Prepare Dataset for Periodic Boundary Conditions Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/tutorials/tutorial_05_materials.ipynb This snippet demonstrates how to define atomic positions, cell shape, atom types, and properties like energy, forces, and stress for a dataset entry. It's used to prepare data for SchNetPack, enabling features like periodic boundary conditions. ```python import numpy as np n_atoms = 16 positions = np.array( [ [5.88321935, 2.88297608, 6.11028356], [3.55048572, 4.80964742, 2.77677731], [0.40720652, 6.73142071, 3.88666154], [2.73860477, 0.96144918, 0.55409947], [0.40533082, 4.80977264, 0.55365277], [2.73798189, 2.88306742, 3.88717458], [5.88129464, 0.96133042, 2.77731562], [3.54993842, 6.73126316, 6.10980443], [0.4072795, 2.88356071, 3.88798019], [2.7361945, 4.80839638, 0.55454406], [5.8807282, 6.732434, 6.10842469], [3.55049053, 0.96113024, 2.77692083], [5.88118878, 4.80922032, 2.7759235], [3.55233987, 2.8843493, 6.10940225], [0.4078124, 0.96031906, 0.5555672], [2.73802399, 6.73163254, 3.88698037], ] ) cell = np.array( [ [6.287023489207423, -0.00034751886075738795, -0.0008093810364881463], [0.00048186949720712026, 7.696440684406158, -0.001909478919115524], [0.0010077843421425583, -0.0033467698530393886, 6.666654324468158], ] ) symbols = ["Si"] * n_atoms energy = np.array([-10169.33552017]) forces = np.array( [ [0.02808107, -0.02261815, -0.00868415], [-0.03619687, -0.02530285, -0.00912962], ``` -------------------------------- ### Run RPMD simulation via CLI Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/docs/userguide/md.md Configures and executes a Ring Polymer Molecular Dynamics simulation with specific integrator, replica, and thermostat settings. ```default spkmd simulation_dir=mdtut_cli_rpmd system.molecule_file=md_ethanol.xyz calculator.model_file=md_ethanol.model calculator.neighbor_list.cutoff=5.0 dynamics/integrator=rpmd system.n_replicas=4 +dynamics/thermostat=pile_local dynamics.n_steps=50000 ``` -------------------------------- ### Run Optimization Source: https://github.com/atomistic-machine-learning/schnetpack/blob/master/examples/howtos/howto_batchwise_relaxations.ipynb Execute the batchwise optimization and clean up the output directory. ```python # results_dir = "./howto_batchwise_relaxations_outputs" # if not os.path.exists(results_dir): # os.makedirs(results_dir) ## Initialize optimizer # optimizer = ASEBatchwiseLBFGS( # calculator=calculator, # atoms=ats, # trajectory="./howto_batchwise_relaxations_outputs/relax_traj", # ) ## run optimization # optimizer.run(fmax=0.0005, steps=1000) ``` ```python # if os.path.exists(results_dir): # shutil.rmtree(results_dir) ```