gpridge.gp ========== .. py:module:: gpridge.gp .. autoapi-nested-parse:: GaussianProcess: the first-class GP surrogate object. Everything in gpridge builds from ``GaussianProcess``. It is: - an *ASE Calculator* -- ``atoms.calc = gp`` works directly, returning GP-predicted energies and forces. Variance is exposed via ``gp.predict_with_uncertainty(atoms)`` or ``gp.uncertainty(atoms)`` for acquisition and trust logic. - a *trainable model* -- ``gp.observe(atoms)`` appends one evaluated structure, and ``gp.fit(atoms_list)`` can accumulate a short list and refit theta in one call. NEB / Dimer drivers use the same appender between inner-loop iterations. - a *handoff token* -- pass the same ``GaussianProcess`` instance to ``GPNEB`` and then to ``GPDimer`` to chain warm-started searches. The GP carries its accumulated observations + fitted theta + the layered-chain config; downstream drivers don't re-train cold. Example:: from metatomic.torch.ase_calculator import MetatomicCalculator from gpridge.gp import GaussianProcess petmad = MetatomicCalculator("model.pt") # an exported model file gp = GaussianProcess( uncertainty='laplace', psis=True, psis_deterministic=True, use_delta=True, rff_features=512, hyperparameters='inla', ) # Use directly as an ASE Calculator (after at least one fit()) initial_atoms.calc = petmad initial_atoms.get_potential_energy() # oracle eval gp.fit([initial_atoms]) # seed the GP test_atoms.calc = gp e_pred = test_atoms.get_potential_energy() # GP prediction f_pred = test_atoms.get_forces() pred = gp.predict_with_uncertainty(test_atoms) # Drive with NEB. Omitting model_profile leaves the library profile. # This example names extended to keep the chain above. from gpridge.neb import GPNEB neb = GPNEB(images, oracle=petmad, gp=gp, model_profile="extended") neb.run(fmax=0.05) # Pass SAME gp to Dimer for warm-started refinement from gpridge.dimer import GPDimer saddle = neb.images[neb.max_energy_image] dimer = GPDimer(saddle, oracle=petmad, gp=gp, model_profile="extended") dimer.run(fmax=0.01) Classes ------- .. autoapisummary:: gpridge.gp.FitDiagnostics gpridge.gp.GaussianProcess gpridge.gp.NoiseReport gpridge.gp.Prediction gpridge.gp.TrainingSet Package Contents ---------------- .. py:class:: FitDiagnostics Summary of the most recent hyperparameter fit. .. py:attribute:: iterations :type: int .. py:attribute:: stop_reason :type: str .. py:attribute:: optimizer_failed :type: bool .. py:class:: GaussianProcess(*, chain=None, uncertainty: str | None = None, use_delta: bool = False, psis: bool | None = None, psis_deterministic: bool = True, rff_features: int | str = 0, rff_force_tol_fraction: float = 0.0, hyperparameters: str = 'scg', template_atoms=None, gpr_params: dict | None = None) Bases: :py:obj:`_CALC_BASE` First-class GP surrogate. Acts as an ASE Calculator + a trainable model. :param chain: Layered-chain configuration. Defaults to ``Surrogate.map()``. Direct ``uncertainty=`` options cover the common ASE workflow. :type chain: :py:class:`Surrogate`, *optional* :param uncertainty: Posterior estimator for user-facing ASE workflows. ``"laplace"`` selects the production Laplace-slice path. :type uncertainty: ``{"map", "laplace", "laplace-slice", "bma", "eb", "svgd"}``, *optional* :param use_delta: Enable the analytical INLA-Delta variance estimator. Requires ``uncertainty="laplace"``. :type use_delta: :py:class:`bool`, *default* :py:obj:`False` :param psis: Enable or disable PSIS correction inside the Laplace-slice path. Defaults to enabled when ``uncertainty="laplace"``. :type psis: :py:class:`bool`, *optional* :param psis_deterministic: Use the deterministic axial-grid PSIS sampler for reproducible Laplace-slice corrections. :type psis_deterministic: :py:class:`bool`, *default* :py:obj:`True` :param rff_features: Number of Random Fourier Features for the mean prediction path. Zero disables RFF. A positive count requires ``uncertainty="laplace"``. ``"auto"`` doubles the count until a held-out random-feature posterior matches the exact GP. :type rff_features: :py:class:`int` or :py:class:``````"auto"``:py:class:````, *default* ``0`` :param rff_force_tol_fraction: Share of the 0.0514221 eV/Å force tolerance that ``"auto"`` may spend on the force error. 0 derives the share from the deployed gradient noise, so the random-feature error cannot move a converged / not-converged decision outside the band already blurred by one gradient-noise standard deviation. The energy tolerance scales the energy-noise standard deviation by the same force-tolerance-to-gradient-noise ratio. Ignored for a fixed count. :type rff_force_tol_fraction: :py:class:`float`, *default* ``0`` :param hyperparameters: Hyperparameter optimization mode. :type hyperparameters: ``{"scg", "inla"}``, *default* ``"scg"`` :param template_atoms: Reference structure used to materialise the GP's AtomsConfiguration. If omitted, the first call to ``add_observation`` / ``predict`` infers it from the supplied atoms. Periodic models use its fixed cell; observations and queries must retain its atomic numbers, periodicity, and the cell vectors of its periodic axes. A partly periodic template (a slab with ``pbc=(True, True, False)``) takes the minimum image along its periodic axes only. :type template_atoms: :py:class:`ase.Atoms`, *optional* :param gpr_params: Override for the underlying GPR parameter dict (rare; the defaults match the gprd binary). :type gpr_params: :py:class:`dict`, *optional* .. py:attribute:: implemented_properties :type: ClassVar[list[str]] :value: ['energy', 'forces'] Properties calculator can handle (energy, forces, ...) .. py:attribute:: name :type: str :value: 'GaussianProcess' .. py:attribute:: chain .. py:method:: observe(atoms, *, energy=None, forces=None) -> GaussianProcess Append an ASE geometry to the training set. If *energy* and *forces* are supplied, no calculator is queried. Otherwise the values are read from ``atoms`` using ASE's standard ``get_potential_energy()`` and ``get_forces()`` calls. .. py:method:: add_observation(atoms) -> None Append (positions, energy, forces) from an ASE Atoms object. ``atoms.get_potential_energy()`` and ``atoms.get_forces()`` are called; the caller is responsible for having the oracle Calculator attached. Subsequent ``fit()`` will pick up the new sample. .. py:method:: add_evaluated_observation(atoms, energy: float, forces) -> None Append a caller-supplied energy/forces sample. Use this from drivers that have already evaluated the oracle. The core GP stores gradients, so ASE forces are negated on insert. .. py:method:: fit_from_atoms(atoms_list: collections.abc.Sequence) -> GaussianProcess Convenience: ``add_observation`` for each + ``fit``. Each Atoms in the iterable must already have been evaluated by the oracle Calculator (i.e. ``get_potential_energy`` returns). .. py:method:: fit(atoms_list: collections.abc.Sequence | None = None) -> GaussianProcess Refit hyperparameters on the accumulated observations. Cache-free: re-creates the underlying GP each call so flipping layered-chain flags between runs has no hidden state. .. py:method:: save(path) Write this fitted GP to a ``gp-state.npz`` file. .. py:method:: to_observation() Materialise accumulated training rows as a core Observation. .. py:method:: train_marginal_likelihood() -> dict Refit the current observations with the marginal-likelihood path. .. py:method:: append_fixed(atoms_list: collections.abc.Sequence) Append evaluated geometries without changing fitted hyperparameters. Returns the combined core ``Observation`` used to refresh the posterior. HS-SVD fits must first call ``train_marginal_likelihood()``, which materializes the Cholesky factor required for this update. .. py:method:: calibrate_forces(atoms_list: collections.abc.Sequence, nominal_probability: float = 0.95) -> dict Calibrate force uncertainty against evaluated held-out geometries. .. py:method:: calibrate_loo(nominal_probability: float = 0.95) -> dict Calibrate uncertainty by leave-one-out residuals. .. py:method:: predict(atoms) -> tuple[float, numpy.ndarray] Return (energy, forces) predicted by the GP at ``atoms``. .. py:method:: energy(x) -> float Posterior-mean energy at an Atoms object or position array. .. py:method:: forces(x) -> numpy.ndarray Posterior-mean ASE forces at an Atoms object or position array. .. py:method:: energy_and_forces(x) -> tuple[float, numpy.ndarray] Posterior-mean energy and ASE forces from one prediction. .. py:method:: variance(x) -> float Posterior predictive energy variance. .. py:method:: predict_batch(atoms_list: collections.abc.Sequence, *, with_variance: bool = True) -> tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray | None, numpy.ndarray | None] Batch predict energies, forces, and optional variances. .. py:method:: predict_with_uncertainty(atoms) -> Prediction Return energy, forces, and predictive variance for ``atoms``. .. py:method:: uncertainty(atoms) -> float Return the predictive energy variance for ``atoms``. .. py:method:: get_variance(atoms) -> float Return predictive variance at ``atoms``. Routes through the layered-chain variance arm (MAP within-sample, INLA-Delta when configured, etc.). .. py:method:: predict_hessian(atoms) -> numpy.ndarray Return the symmetric (3N, 3N) posterior-mean Hessian at ``atoms``. .. py:method:: predict_hessian_action(atoms, direction) -> numpy.ndarray Return H(atoms) @ direction for the posterior mean. .. py:method:: predict_energy_variance_interval(atoms_list: collections.abc.Sequence) -> tuple[numpy.ndarray, numpy.ndarray] Return certified (lower, upper) energy-variance bounds per geometry. Requires an exact-kernel HS-SVD MAP model; the noise is the one the trained factor inverts (see :meth:`noise_floor_report`). A negative lower endpoint is clamped to zero when the upper endpoint is nonnegative. .. py:method:: noise_floor_report() -> dict Return the condition-floored noise and certificate gap of the fit. .. py:method:: hessian_action(x, direction) -> numpy.ndarray Posterior-mean Hessian action at an Atoms object or positions. .. py:method:: prediction_supported(atoms) -> bool Return True when the trained kernel supports ``atoms``. .. py:method:: prediction_factors(atoms) -> dict Return the prediction factors (energy, scale, mean, kstar, weights). .. py:property:: fit_iterations :type: int Optimizer iterations of the last fit, or -1 if unfitted. The count is rgmin's SCG steps plus the L-BFGS fallback steps that finish a stalled rgmin SCG fit. .. py:property:: fit_restarts :type: int Restarts of the last fit, or -1 if unfitted. Only ``train_marginal_likelihood`` restarts, at most once. .. py:property:: fit_stop_reason :type: str Stop reason of the last fit, or ``'unset'`` if unfitted. A fitted model reports ``budget``, ``library``, ``restored scg point``, ``wall-clock limit``, ``non-finite marginal likelihood``, or ``unset``. .. py:property:: hyperparameters :type: dict Fitted kernel and noise parameters as owned Python values. .. py:property:: training_set :type: TrainingSet Copy of positions, energies, and ASE forces used by the model. .. py:property:: noise_report :type: NoiseReport Likelihood floor, fitted noise, jitter, and their effective sum. .. py:property:: fit_diagnostics :type: FitDiagnostics Optimizer status for the most recent fit. .. py:method:: as_calculator() Return this surface as an ASE Calculator. .. py:method:: as_rgpot() Return the trained model through rgpot's PotentialBase interface. This is the supported construction path. The returned surface stays current when this model is refit and retains its fitted core model if this Python owner is deleted. .. py:property:: rff_selection :type: dict Stored automatic random-feature selection report. .. py:method:: calculate(atoms=None, properties=None, system_changes=None) Store the GP prediction for ``atoms`` in ``self.results``. This is the ASE calculator hook behind ``get_potential_energy()`` and ``get_forces()``. It returns the posterior mean (eV and eV/Angstrom); ``properties`` and ``system_changes`` are ignored. Raises ``RuntimeError`` when the GP is not fitted and ``ValueError`` when no atoms are available. .. py:property:: n_observations :type: int Number of stored observations (geometry, energy, forces). .. py:property:: is_fit :type: bool True once :meth:`fit` has run. Observations added afterwards do not clear it, and predictions then ignore them until :meth:`fit` is called again. .. py:class:: NoiseReport Likelihood floor and numerical regularization, in variance units. .. py:attribute:: configured_floor_variance :type: float .. py:attribute:: fitted_likelihood_variance :type: float .. py:attribute:: numerical_jitter_variance :type: float .. py:attribute:: effective_variance :type: float .. py:class:: Prediction Energy/force prediction plus optional uncertainty moments. Forces follow ASE's sign convention. Variance fields use the GP core's predictive variance for energy and force components. .. py:attribute:: energy :type: float .. py:attribute:: forces :type: numpy.ndarray .. py:attribute:: energy_variance :type: float | None :value: None .. py:attribute:: force_variance :type: numpy.ndarray | None :value: None .. py:property:: energy_std :type: float | None Standard deviation of the energy in eV, the square root of ``energy_variance``. ``None`` when no variance was computed. .. py:class:: TrainingSet Owned arrays used to fit a GP surface. .. py:attribute:: positions :type: numpy.ndarray .. py:attribute:: energies :type: numpy.ndarray .. py:attribute:: forces :type: numpy.ndarray