|
| 1 | +# Copyright 2025 InstaDeep Ltd |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import logging |
| 16 | +import time |
| 17 | +from typing import Callable |
| 18 | + |
| 19 | +import ase |
| 20 | +import numpy as np |
| 21 | +from ase.calculators.calculator import Calculator as ASECalculator |
| 22 | +from ase.mep import NEB |
| 23 | +from ase.optimize import BFGS |
| 24 | +from mlip.models import ForceField |
| 25 | +from mlip.simulation import SimulationState |
| 26 | +from mlip.simulation.ase.mlip_ase_calculator import MLIPForceFieldASECalculator |
| 27 | +from mlip.simulation.configs import ASESimulationConfig |
| 28 | +from mlip.simulation.simulation_engine import SimulationEngine |
| 29 | + |
| 30 | +logger = logging.getLogger("mlip") |
| 31 | + |
| 32 | + |
| 33 | +class NEBSimulationConfig(ASESimulationConfig): |
| 34 | + """Configuration for the NEB simulations. |
| 35 | + Also includes the attributes of the parent class |
| 36 | + :ASESimulationConfig. |
| 37 | + """ |
| 38 | + |
| 39 | + simulation_type: str = "neb" |
| 40 | + num_images: int = 7 |
| 41 | + neb_k: float | None = 10.0 |
| 42 | + max_force_convergence_threshold: float | None = 0.1 |
| 43 | + continue_from_previous_run: bool = False |
| 44 | + climb: bool = False |
| 45 | + |
| 46 | + |
| 47 | +class NEBSimulationEngine(SimulationEngine): |
| 48 | + """Simulation engine handling NEB simulations with the ASE backend.""" |
| 49 | + |
| 50 | + Config = NEBSimulationConfig |
| 51 | + |
| 52 | + def __init__( |
| 53 | + self, |
| 54 | + atoms_initial: ase.Atoms, |
| 55 | + atoms_final: ase.Atoms, |
| 56 | + force_field: ForceField | ASECalculator, |
| 57 | + config: NEBSimulationConfig, |
| 58 | + images: list[ase.Atoms] | None = None, |
| 59 | + transition_state: ase.Atoms | None = None, |
| 60 | + ) -> None: |
| 61 | + """Initialize the NEB simulation engine.""" |
| 62 | + self._initialize( |
| 63 | + atoms_initial, |
| 64 | + atoms_final, |
| 65 | + force_field, |
| 66 | + config, |
| 67 | + images, |
| 68 | + transition_state, |
| 69 | + ) |
| 70 | + |
| 71 | + def _initialize( |
| 72 | + self, |
| 73 | + atoms_initial: ase.Atoms, |
| 74 | + atoms_final: ase.Atoms, |
| 75 | + force_field: ForceField | ASECalculator, |
| 76 | + config: NEBSimulationConfig, |
| 77 | + images: list[ase.Atoms] | None = None, |
| 78 | + transition_state: ase.Atoms | None = None, |
| 79 | + ) -> None: |
| 80 | + """Initialize the NEB simulation.""" |
| 81 | + self.state = SimulationState() |
| 82 | + self.loggers: list[Callable[[SimulationState], None]] = [] |
| 83 | + |
| 84 | + self._config = config |
| 85 | + self.atoms = atoms_initial |
| 86 | + positions = atoms_initial.get_positions() |
| 87 | + self._num_atoms = positions.shape[0] |
| 88 | + self.state.atomic_numbers = atoms_initial.numbers |
| 89 | + self.force_field = force_field |
| 90 | + |
| 91 | + self.model_calculator = self._get_model_calculator() |
| 92 | + |
| 93 | + self.atoms_final = atoms_final |
| 94 | + |
| 95 | + self._init_box_neb(self.atoms) |
| 96 | + self._init_box_neb(self.atoms_final) |
| 97 | + |
| 98 | + self.atoms.calc = self._get_model_calculator() |
| 99 | + self.atoms_final.calc = self._get_model_calculator() |
| 100 | + |
| 101 | + self.neb = NEB([]) |
| 102 | + self.images = images |
| 103 | + self.transition_state = transition_state |
| 104 | + |
| 105 | + def run(self) -> None: |
| 106 | + """Run the NEB simulation. |
| 107 | +
|
| 108 | + Raises: |
| 109 | + ValueError: If continue_from_previous_run is True |
| 110 | + and images are not provided. |
| 111 | + """ |
| 112 | + if not self._config.continue_from_previous_run: |
| 113 | + self._init_neb() |
| 114 | + else: |
| 115 | + if not self.images: |
| 116 | + raise ValueError( |
| 117 | + "Images must be provided if continue_from_previous_run is True" |
| 118 | + ) |
| 119 | + |
| 120 | + for image in self.images: |
| 121 | + image.calc = self._get_model_calculator() |
| 122 | + |
| 123 | + self.neb = NEB( |
| 124 | + self.images, |
| 125 | + k=self._config.neb_k, |
| 126 | + climb=self._config.climb, |
| 127 | + parallel=True, |
| 128 | + ) |
| 129 | + |
| 130 | + dyn = BFGS(self.neb, alpha=70, maxstep=0.03) |
| 131 | + |
| 132 | + def log_to_console() -> None: |
| 133 | + """Logs info to console.""" |
| 134 | + step = dyn.get_number_of_steps() |
| 135 | + compute_time = time.perf_counter() - self.self_start_interval_time |
| 136 | + self._log_to_console(step, compute_time) |
| 137 | + |
| 138 | + def set_beginning_interval_time() -> None: |
| 139 | + self.self_start_interval_time = time.perf_counter() |
| 140 | + |
| 141 | + def update_state() -> None: |
| 142 | + """Update the internal SimulationState object.""" |
| 143 | + step = dyn.get_number_of_steps() |
| 144 | + compute_time = time.perf_counter() - self.self_start_interval_time |
| 145 | + self._update_state_neb(step, compute_time) |
| 146 | + |
| 147 | + dyn.attach(log_to_console, interval=self._config.log_interval) |
| 148 | + dyn.attach(self._call_loggers, interval=self._config.log_interval) |
| 149 | + dyn.attach(update_state, interval=self._config.snapshot_interval) |
| 150 | + dyn.attach(set_beginning_interval_time, interval=self._config.log_interval) |
| 151 | + self.self_start_interval_time = time.perf_counter() |
| 152 | + |
| 153 | + dyn.run( |
| 154 | + steps=self._config.num_steps, |
| 155 | + fmax=self._config.max_force_convergence_threshold, |
| 156 | + ) |
| 157 | + |
| 158 | + def _init_neb(self) -> None: |
| 159 | + if not self.transition_state: |
| 160 | + num_images = max(self._config.num_images, 2) |
| 161 | + images = [self.atoms] |
| 162 | + images.extend([self.atoms.copy() for _ in range(num_images - 2)]) |
| 163 | + images.append(self.atoms_final) |
| 164 | + else: |
| 165 | + num_images = max(self._config.num_images, 3) |
| 166 | + num_images_1 = num_images // 2 + 1 |
| 167 | + num_images_2 = num_images - num_images_1 + 1 |
| 168 | + |
| 169 | + images_1 = [self.atoms] |
| 170 | + images_1.extend([self.atoms.copy() for _ in range(num_images_1 - 2)]) |
| 171 | + images_1.append(self.transition_state) |
| 172 | + |
| 173 | + images_2 = [self.transition_state.copy()] |
| 174 | + images_2.extend([self.atoms_final.copy() for _ in range(num_images_2 - 2)]) |
| 175 | + images_2.append(self.atoms_final) |
| 176 | + |
| 177 | + for image in images_1: |
| 178 | + image.calc = self._get_model_calculator() |
| 179 | + for image in images_2: |
| 180 | + image.calc = self._get_model_calculator() |
| 181 | + |
| 182 | + neb1 = NEB( |
| 183 | + images_1, k=self._config.neb_k, climb=self._config.climb, parallel=True |
| 184 | + ) |
| 185 | + neb2 = NEB( |
| 186 | + images_2, k=self._config.neb_k, climb=self._config.climb, parallel=True |
| 187 | + ) |
| 188 | + |
| 189 | + neb1.interpolate(method="idpp") |
| 190 | + neb2.interpolate(method="idpp") |
| 191 | + |
| 192 | + images = neb1.images + neb2.images[1:] |
| 193 | + |
| 194 | + for image in images: |
| 195 | + image.calc = self._get_model_calculator() |
| 196 | + |
| 197 | + self.neb = NEB( |
| 198 | + images, k=self._config.neb_k, climb=self._config.climb, parallel=True |
| 199 | + ) |
| 200 | + |
| 201 | + if not self.transition_state: |
| 202 | + self.neb.interpolate(method="idpp") |
| 203 | + |
| 204 | + def _init_box_neb(self, atoms: ase.Atoms) -> None: |
| 205 | + if isinstance(self._config.box, float): |
| 206 | + atoms.cell = np.eye(3) * self._config.box |
| 207 | + atoms.pbc = True |
| 208 | + elif isinstance(self._config.box, list): |
| 209 | + atoms.cell = np.diag(np.array(self._config.box)) |
| 210 | + atoms.pbc = True |
| 211 | + else: |
| 212 | + atoms.cell = None |
| 213 | + atoms.pbc = False |
| 214 | + |
| 215 | + def _update_state_neb( |
| 216 | + self, |
| 217 | + step: int, |
| 218 | + compute_time: float, |
| 219 | + ) -> None: |
| 220 | + """Update the internal state of the simulation. |
| 221 | + Here, the positions, forces and potential energy for every image |
| 222 | + are updated and not concatenated, as for the MD simulations and energy |
| 223 | + minimizations. |
| 224 | +
|
| 225 | + Args: |
| 226 | + step: The current step. |
| 227 | + compute_time: The compute time. |
| 228 | + """ |
| 229 | + self.state.positions = np.zeros(( |
| 230 | + len(self.neb.images), |
| 231 | + len(self.neb.images[0].positions), |
| 232 | + 3, |
| 233 | + )) |
| 234 | + self.state.potential_energy = np.zeros(len(self.neb.images)) |
| 235 | + |
| 236 | + for i, image in enumerate(self.neb.images): |
| 237 | + self.state.positions[i] = image.positions |
| 238 | + self.state.potential_energy[i] = image.get_potential_energy() |
| 239 | + |
| 240 | + self.state.forces = self.neb.get_forces() |
| 241 | + |
| 242 | + self.state.step = step |
| 243 | + self.state.compute_time_seconds += compute_time |
| 244 | + |
| 245 | + def _get_model_calculator(self) -> MLIPForceFieldASECalculator | ASECalculator: |
| 246 | + if isinstance(self.force_field, ForceField): |
| 247 | + return MLIPForceFieldASECalculator( |
| 248 | + self.atoms, |
| 249 | + self._config.edge_capacity_multiplier, |
| 250 | + self.force_field, |
| 251 | + ) |
| 252 | + else: |
| 253 | + return self.force_field |
| 254 | + |
| 255 | + def _call_loggers(self) -> None: |
| 256 | + for _logger in self.loggers: |
| 257 | + _logger(self.state) |
| 258 | + |
| 259 | + def _log_to_console(self, step: int, compute_time: float) -> None: |
| 260 | + """Logs timing information to console via our logger.""" |
| 261 | + if step == 0: |
| 262 | + logger.debug( |
| 263 | + "Initialization took %.2f seconds.", |
| 264 | + compute_time, |
| 265 | + ) |
| 266 | + else: |
| 267 | + logger.info( |
| 268 | + "Steps %s to %s completed in %.2f seconds.", |
| 269 | + self.state.step, |
| 270 | + step, |
| 271 | + compute_time, |
| 272 | + ) |
0 commit comments