Coverage for openxps/regression.py: 98%
200 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-22 22:23 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-22 22:23 +0000
1"""
2.. module:: openxps.regression
3 :platform: Linux, MacOS, Windows
4 :synopsis: Radial basis function regressor for free energy surface fitting.
6.. classauthor:: Charlles Abreu <craabreu@gmail.com>
8"""
10import contextlib
11import logging
12import tempfile
13import typing as t
14import warnings
16import numpy as np
18try:
19 import pandas as pd
20 import torch
21 from lightning import pytorch as pl
22 from torch import nn
23 from torch.utils.data import DataLoader, TensorDataset
24except ImportError as error:
25 raise ImportError(
26 "ForceMatchingRegressor requires PyTorch, Lightning and pandas. Install them "
27 "with `pip install openxps[regression]` or `conda install -c conda-forge "
28 "pytorch lightning pandas`."
29 ) from error
31from .bounds import PeriodicBounds
32from .dynamical_variable import DynamicalVariable
34if t.TYPE_CHECKING:
35 from numpy.typing import ArrayLike
36else:
38 class ArrayLike(t.Protocol): ...
41INIT_NUM_SIGMAS = 4.0
44class RBFPotential(nn.Module):
45 """Radial basis function potential.
47 Parameters
48 ----------
49 dynamical_variables
50 A sequence of dynamical variables defining the dimensions and bounds
51 for the potential. The length of this sequence determines the input
52 dimension.
53 M
54 The number of radial basis functions.
55 learn_centers
56 Whether to learn the centers of the radial basis functions.
57 generator
58 The random number generator used to place the initial centers. If None,
59 PyTorch's global generator is used.
60 """
62 def __init__(
63 self,
64 dynamical_variables: t.Sequence[DynamicalVariable],
65 M: int = 256,
66 learn_centers: bool = True,
67 generator: torch.Generator | None = None,
68 ) -> None:
69 super().__init__()
70 lengths, periodic, random_points = [], [], []
71 for dv in dynamical_variables:
72 lengths.append(dv.bounds.length)
73 periodic.append(isinstance(dv.bounds, PeriodicBounds))
74 random_points.append(
75 torch.rand(M, generator=generator) * dv.bounds.length + dv.bounds.lower
76 )
78 self.c = nn.Parameter(
79 torch.stack(random_points, dim=-1), requires_grad=learn_centers
80 )
81 log_sigmas = np.log(lengths) - np.log(INIT_NUM_SIGMAS)
82 self.logsig = nn.Parameter(
83 torch.tensor(np.repeat(log_sigmas[None, :], M, axis=0), dtype=torch.float32)
84 )
85 self.w = nn.Parameter(torch.zeros(M))
86 self.register_buffer(
87 "_length_over_pi",
88 torch.tensor(np.array(lengths) / np.pi, dtype=torch.float32)[None, None, :],
89 )
90 self.register_buffer(
91 "_periodic", torch.tensor(periodic, dtype=torch.bool)[None, None, :]
92 )
94 def _delta2_fn(self, disp: torch.Tensor) -> torch.Tensor:
95 return torch.where(
96 self._periodic,
97 self._length_over_pi * torch.sin(disp / self._length_over_pi),
98 disp,
99 ).square()
101 def _delta2_grad(self, disp: torch.Tensor) -> torch.Tensor:
102 return torch.where(
103 self._periodic,
104 self._length_over_pi * torch.sin(2 * disp / self._length_over_pi),
105 2 * disp,
106 )
108 def _phi(self, disp: torch.Tensor) -> torch.Tensor:
109 delta2 = self._delta2_fn(disp)
110 sigma2 = torch.exp(2 * self.logsig)
111 return torch.exp(-0.5 * (delta2 / sigma2[None, :, :]).sum(-1))
113 def forward(self, x: torch.Tensor) -> torch.Tensor:
114 disp = x[:, None, :] - self.c[None, :, :]
115 return self._phi(disp) @ self.w
117 def grad(self, x: torch.Tensor) -> torch.Tensor:
118 disp = x[:, None, :] - self.c[None, :, :]
119 Phi = self._phi(disp)
120 sigma2 = torch.exp(2 * self.logsig)
121 fac = (-0.5 * self.w[:, None] / sigma2)[None, :, :]
122 return (fac * Phi[:, :, None] * self._delta2_grad(disp)).sum(1)
125class GradMatch(pl.LightningModule):
126 """Gradient matching regressor.
128 Parameters
129 ----------
130 dynamical_variables
131 A sequence of dynamical variables defining the dimensions and bounds
132 for the potential. The length of this sequence determines the input
133 dimension.
135 Keyword Arguments
136 -----------------
137 M
138 The number of radial basis functions.
139 lr
140 The learning rate.
141 wd
142 The weight decay.
143 generator
144 The random number generator used to place the initial kernel centers.
145 """
147 def __init__(
148 self,
149 dynamical_variables: t.Sequence[DynamicalVariable],
150 M: int = 256,
151 lr: float = 2e-3,
152 wd: float = 1e-4,
153 generator: torch.Generator | None = None,
154 ) -> None:
155 super().__init__()
156 self.save_hyperparameters(ignore=["dynamical_variables", "generator"])
157 self.f = RBFPotential(dynamical_variables, M, generator=generator)
159 def configure_optimizers(self) -> torch.optim.Optimizer:
160 return torch.optim.AdamW(
161 [
162 {"params": [self.f.w], "weight_decay": self.hparams.wd},
163 {"params": [self.f.c, self.f.logsig], "weight_decay": 0.0},
164 ],
165 lr=self.hparams.lr,
166 )
168 def _loss(self, batch: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
169 x, G = batch
170 return ((self.f.grad(x) - G) ** 2).mean()
172 def training_step(
173 self, batch: tuple[torch.Tensor, torch.Tensor], batch_idx: int
174 ) -> torch.Tensor:
175 loss = self._loss(batch)
176 self.log("train_loss", loss, prog_bar=True, on_step=False, on_epoch=True)
177 return loss
179 def validation_step(
180 self, batch: tuple[torch.Tensor, torch.Tensor], batch_idx: int
181 ) -> torch.Tensor:
182 loss = self._loss(batch)
183 self.log("val_loss", loss, prog_bar=True, on_step=False, on_epoch=True)
184 return loss
187class _LearningCurveRecorder(pl.Callback):
188 """Collect per-epoch training and validation losses keyed by epoch."""
190 def __init__(self) -> None:
191 super().__init__()
192 self._records: dict[int, dict[str, float]] = {}
194 def _record(self, trainer: pl.Trainer, key: str) -> None:
195 value = trainer.callback_metrics.get(key)
196 if value is not None:
197 epoch = trainer.current_epoch
198 record = self._records.setdefault(epoch, {"epoch": epoch})
199 record[key] = float(value)
201 def on_train_epoch_end(
202 self, trainer: pl.Trainer, pl_module: pl.LightningModule
203 ) -> None:
204 self._record(trainer, "train_loss")
206 def on_validation_epoch_end(
207 self, trainer: pl.Trainer, pl_module: pl.LightningModule
208 ) -> None:
209 if not trainer.sanity_checking:
210 self._record(trainer, "val_loss")
212 def to_frame(self) -> pd.DataFrame:
213 """Return the recorded losses with one row per epoch."""
214 records = list(self._records.values())
215 columns = ["epoch", "train_loss"]
216 if any("val_loss" in record for record in records):
217 columns.append("val_loss")
218 return pd.DataFrame(records, columns=columns)
221#: Lightning warnings that don't apply to fitting a small in-memory data set
222_BENIGN_LIGHTNING_WARNINGS = (
223 # The data loaders use few workers on purpose: the data are small tensors in memory
224 r"The '\w+' does not have many workers",
225 # A validation step is always defined, but validation_fraction=0 means no data
226 r"You defined a `validation_step` but have no `val_dataloader`",
227 # Raised on any machine with SLURM installed, even when it is not being used
228 r"The `srun` command is available on your system but is not used",
229 # Lightning's own use of an API deprecated by recent PyTorch versions
230 r"`isinstance\(treespec, LeafSpec\)` is deprecated",
231)
234@contextlib.contextmanager
235def _quiet_lightning() -> t.Iterator[None]:
236 """Silence Lightning's informational log messages."""
237 loggers = [logging.getLogger(name) for name in ("lightning.pytorch", "lightning")]
238 levels = [logger.level for logger in loggers]
239 try:
240 for logger in loggers:
241 logger.setLevel(logging.WARNING)
242 yield
243 finally:
244 for logger, level in zip(loggers, levels):
245 logger.setLevel(level)
248@contextlib.contextmanager
249def _ignore_benign_lightning_warnings() -> t.Iterator[None]:
250 """Ignore Lightning warnings that don't apply to this regressor."""
251 with warnings.catch_warnings():
252 for message in _BENIGN_LIGHTNING_WARNINGS:
253 warnings.filterwarnings("ignore", message=message)
254 yield
257class ForceMatchingRegressor:
258 r"""Potential regressor from sampled position/force pairs.
260 A potential function in a :math:`d`-dimensional variable space is approximated as:
262 .. math::
263 U({\bf s}) = \sum_{m=1}^n w_m \exp\left(
264 -\frac{1}{2} \sum_{k=1}^d \frac{\delta_k^2(s_k - c_{m,k})}{\sigma_{m,k}^2}
265 \right)
267 where the :math:`n` weights :math:`w_m`, kernel bandwidths :math:`\sigma_m`, and
268 kernel centers :math:`{\bf c}_m` are adjustable parameters. The displacement
269 function :math:`\delta_k(x)` depends on the periodicity of the variable :math:`s_k`
270 and is defined as:
272 .. math::
273 \delta_k(x) = \left\{\begin{array}{ll}
274 x & \text{if }s_k\text{ is non-periodic} \\
275 \frac{L_k}{\pi}\sin(\frac{\pi x}{L_k}) & \text{if }s_k\text{ has period }L_k
276 \end{array}\right.
278 Given :math:`N` position-force pairs :math:`({\bf s}_i, {\bf F}_i)`, the parameters
279 are adjusted by minimizing the mean squared error loss:
281 .. math::
282 L = \frac{1}{Nd} \sum_{i=1}^N \left\|{\bf f}({\bf s}_i) - {\bf F}_i\right\|^2,
284 where :math:`d` is the number of dynamical variables and
285 :math:`{\bf f}({\bf s}) = -\nabla_{\bf s} U({\bf s})` is the predicted force.
287 .. note::
288 This class needs PyTorch, Lightning and pandas, which are not installed with
289 openxps. Install them with ``pip install openxps[regression]`` or
290 ``conda install -c conda-forge pytorch lightning pandas``.
292 Parameters
293 ----------
294 dynamical_variables
295 The dynamical variables to be used in the potential. They are converted to
296 the MD unit system, so the positions and forces passed to :meth:`fit` and
297 :meth:`predict` must be expressed in MD units.
298 num_kernels
299 The number of kernels to be used in the potential.
301 Keyword Arguments
302 -----------------
303 validation_fraction
304 The fraction of the data to be used for validation.
305 batch_size
306 The batch size to be used for training.
307 num_epochs
308 The number of epochs to be used for training.
309 patience
310 The patience for early stopping.
311 learning_rate
312 The learning rate to be used for training.
313 weight_decay
314 The weight decay to be used for training.
315 accelerator
316 The accelerator to be used for training. Valid options can be found
317 `here <https://lightning.ai/docs/pytorch/LTS/common/trainer.html#accelerator>`_.
318 devices
319 The number of devices, or ``"auto"``, passed to the Lightning trainer. The
320 default of 1 avoids launching distributed training on multi-GPU hosts.
321 num_workers
322 The number of data loading workers to be used for training.
323 verbose
324 Whether :meth:`fit` shows Lightning's progress bar, model summary and
325 informational messages.
326 """
328 def __init__( # noqa: PLR0913
329 self,
330 dynamical_variables: t.Sequence[DynamicalVariable],
331 num_kernels: int,
332 *,
333 validation_fraction: float = 0.1,
334 batch_size: int = 256,
335 num_epochs: int = 50,
336 patience: int = 10,
337 learning_rate: float = 2e-3,
338 weight_decay: float = 1e-4,
339 accelerator: str = "auto",
340 devices: int | str = 1,
341 num_workers: int = 0,
342 verbose: bool = False,
343 ):
344 if not 0 <= validation_fraction < 1:
345 raise ValueError("validation_fraction must be in the interval [0, 1).")
346 self._dynamical_variables = tuple(
347 dv.in_md_units() for dv in dynamical_variables
348 )
349 self._val_frac = validation_fraction
350 self._batch_size = batch_size
351 self._num_epochs = num_epochs
352 self._patience = patience
353 self._lr = learning_rate
354 self._wd = weight_decay
355 self._accelerator = accelerator
356 self._devices = devices
357 self._num_workers = num_workers
358 self._verbose = verbose
359 self._M = num_kernels
360 self._model = None
361 self._metrics = None
363 @staticmethod
364 def _as_numpy(x: torch.Tensor) -> np.ndarray:
365 return x.detach().cpu().clone().numpy()
367 def _num_validation_samples(self, num_samples: int) -> int:
368 return int(round(self._val_frac * num_samples))
370 def _create_dataloaders(
371 self, X: torch.Tensor, G: torch.Tensor, generator: torch.Generator
372 ) -> tuple[DataLoader, DataLoader | None]:
373 N = len(X)
374 idx = torch.randperm(N, generator=generator)
375 nval = self._num_validation_samples(N)
376 val_idx, tr_idx = idx[:nval], idx[nval:]
377 train_dl = DataLoader(
378 TensorDataset(X[tr_idx], G[tr_idx]),
379 batch_size=self._batch_size,
380 shuffle=True,
381 generator=generator,
382 num_workers=self._num_workers,
383 persistent_workers=self._num_workers > 0,
384 )
385 if len(val_idx) == 0:
386 return train_dl, None
387 val_dl = DataLoader(
388 TensorDataset(X[val_idx], G[val_idx]),
389 batch_size=self._batch_size,
390 generator=generator,
391 num_workers=self._num_workers,
392 persistent_workers=self._num_workers > 0,
393 )
394 return train_dl, val_dl
396 def _create_callbacks(
397 self, directory: str
398 ) -> tuple[pl.callbacks.ModelCheckpoint, pl.callbacks.EarlyStopping]:
399 checkpoint = pl.callbacks.ModelCheckpoint(
400 monitor="val_loss",
401 save_last=False,
402 filename="best-{epoch:02d}-{val_loss:.6f}",
403 dirpath=directory,
404 )
405 early_stopping = pl.callbacks.EarlyStopping(
406 monitor="val_loss", patience=self._patience
407 )
408 return checkpoint, early_stopping
410 def _as_positions(self, positions: ArrayLike) -> torch.Tensor:
411 X = torch.as_tensor(np.asarray(positions, dtype=np.float32))
412 d = len(self._dynamical_variables)
413 if X.ndim != 2 or X.shape[1] != d: # noqa: PLR2004
414 raise ValueError(
415 f"positions must have shape (N, {d}), got {tuple(X.shape)}"
416 )
417 return X
419 def _validate_forces(self, X: torch.Tensor, G: torch.Tensor) -> None:
420 if G.shape != X.shape:
421 raise ValueError(
422 f"forces must have the same shape as positions {tuple(X.shape)}, "
423 f"got {tuple(G.shape)}"
424 )
426 def fit(
427 self, positions: ArrayLike, forces: ArrayLike, *, seed: int | None = None
428 ) -> None:
429 """Fit the potential regressor to the given positions and forces.
431 Parameters
432 ----------
433 positions
434 An array of shape (N, d) with the positions in MD units.
435 forces
436 An array of shape (N, d) with the forces in MD units.
438 Keyword Arguments
439 -----------------
440 seed
441 The seed used to split the data, shuffle the batches and initialize the
442 kernels. If None, a random seed is used. The global random states of
443 NumPy and PyTorch are left untouched.
445 Notes
446 -----
447 The fitted model and learning curve replace the previous ones only if
448 training completes, so a failed fit leaves the regressor unchanged.
449 """
450 generator = torch.Generator()
451 generator.manual_seed(int(np.random.default_rng(seed).integers(0, 2**63 - 1)))
453 X = self._as_positions(positions)
454 G = -torch.as_tensor(np.asarray(forces, dtype=np.float32))
455 self._validate_forces(X, G)
456 num_samples = len(X)
457 if num_samples - self._num_validation_samples(num_samples) < 1:
458 raise ValueError(
459 f"No training data left: {num_samples} samples with "
460 f"validation_fraction={self._val_frac}."
461 )
462 train_dl, val_dl = self._create_dataloaders(X, G, generator)
464 model = GradMatch(
465 self._dynamical_variables, self._M, self._lr, self._wd, generator
466 )
467 recorder = _LearningCurveRecorder()
469 quiet = contextlib.nullcontext() if self._verbose else _quiet_lightning()
470 with (
471 quiet,
472 _ignore_benign_lightning_warnings(),
473 tempfile.TemporaryDirectory() as tmp_dir,
474 ):
475 trainer_kwargs = {
476 "max_epochs": self._num_epochs,
477 "accelerator": self._accelerator,
478 "devices": self._devices,
479 "logger": False,
480 "enable_progress_bar": self._verbose,
481 "enable_model_summary": self._verbose,
482 "callbacks": [recorder],
483 }
484 if val_dl is None:
485 trainer_kwargs["enable_checkpointing"] = False
486 trainer = pl.Trainer(**trainer_kwargs)
487 trainer.fit(model, train_dl)
488 else:
489 checkpoint, early_stopping = self._create_callbacks(tmp_dir)
490 trainer_kwargs["callbacks"] += [checkpoint, early_stopping]
491 trainer = pl.Trainer(**trainer_kwargs)
492 trainer.fit(model, train_dl, val_dl)
493 if checkpoint.best_model_path:
494 state = torch.load(
495 checkpoint.best_model_path,
496 map_location="cpu",
497 weights_only=True,
498 )
499 model.load_state_dict(state["state_dict"])
501 self._model = model
502 self._metrics = recorder.to_frame()
504 def predict(self, positions: ArrayLike) -> np.ndarray:
505 """Predict the potential at the given positions.
507 Parameters
508 ----------
509 positions
510 An array of shape (M, d) containing the positions at which to predict the
511 potential.
513 Returns
514 -------
515 np.ndarray
516 An array of shape (M,) containing the potential at the given positions.
517 """
518 if self._model is None:
519 raise RuntimeError("The model has not been fitted yet.")
520 device = next(self._model.parameters()).device
521 X = self._as_positions(positions).to(device)
522 with torch.no_grad():
523 return self._as_numpy(self._model.f(X))
525 def get_parameters(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
526 """Get the parameters of the potential regressor.
528 Returns
529 -------
530 centers
531 The centers of the radial basis functions, shape (M, d).
532 sigmas
533 The bandwidths of the radial basis functions per dimension,
534 shape (M, d).
535 weights
536 The weights of the radial basis functions, shape (M,).
538 Notes
539 -----
540 Centers of periodic variables are wrapped into their bounds. Centers of
541 non-periodic variables are returned as fitted, even if they lie outside the
542 bounds, because the kernels use plain displacements for those variables.
544 Raises
545 ------
546 RuntimeError
547 If :meth:`fit` has not been called.
548 """
549 if self._model is None:
550 raise RuntimeError("The model has not been fitted yet.")
551 centers = self._as_numpy(self._model.f.c)
552 for dv, column in zip(self._dynamical_variables, centers.T):
553 if isinstance(dv.bounds, PeriodicBounds):
554 column[:], _ = np.vectorize(dv.bounds.wrap)(column, 0)
555 return (
556 centers,
557 self._as_numpy(self._model.f.logsig.exp()),
558 self._as_numpy(self._model.f.w),
559 )
561 def get_learning_curve(self) -> pd.DataFrame:
562 """Get the learning curve of the last fit.
564 Returns
565 -------
566 pd.DataFrame
567 A copy of the per-epoch losses, with columns ``epoch``, ``train_loss``
568 and, when a validation set is used, ``val_loss``.
570 Raises
571 ------
572 RuntimeError
573 If :meth:`fit` has not been called.
574 """
575 if self._metrics is None:
576 raise RuntimeError("The model has not been fitted yet.")
577 return self._metrics.copy()