Loading...
Searching...
No Matches
Session.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
28
29#ifndef GPR_NEB_SESSION_H_
30#define GPR_NEB_SESSION_H_
31
32#include <Eigen/Dense>
33#include <algorithm>
34#include <cmath>
35#include <cstddef>
36#include <cstdint>
37#include <exception>
38#include <functional>
39#include <limits>
40#include <memory>
41#include <optional>
42#include <stdexcept>
43#include <utility>
44#include <vector>
45
46#include "EndpointSymmetry.h"
47#include "ObservationArchive.h"
48#include "OieOracleConsensus.h"
56
57namespace gpr {
58namespace neb {
59
62
63namespace detail {
64inline void appendObservationRow(gpr::Observation& obs,
65 const Eigen::VectorXd& positions,
66 double energy, const Eigen::VectorXd& gradient)
67{
68 const Eigen::Index D = positions.size();
69 const Eigen::Index n0 = obs.R.rows();
70 if (n0 == 0) {
71 obs.R.resize(1, D);
72 obs.E.resize(1, 1);
73 obs.G.resize(1, D);
74 } else {
75 obs.R.conservativeResize(n0 + 1, D);
76 obs.E.conservativeResize(n0 + 1, 1);
77 obs.G.conservativeResize(n0 + 1, D);
78 }
79 const Eigen::Index k = obs.R.rows() - 1;
80 for (Eigen::Index j = 0; j < D; ++j)
81 obs.R(k, j) = positions(j);
82 obs.E(k, 0) = energy;
83 for (Eigen::Index j = 0; j < D; ++j)
84 obs.G(k, j) = gradient(j);
85}
86
88inline void insertObservationRow(gpr::Observation& obs, Eigen::Index k,
89 const Eigen::VectorXd& positions,
90 double energy, const Eigen::VectorXd& gradient)
91{
92 appendObservationRow(obs, positions, energy, gradient);
93 for (Eigen::Index r = obs.R.rows() - 1; r > k; --r) {
94 obs.R.row(r).swap(obs.R.row(r - 1));
95 obs.E.row(r).swap(obs.E.row(r - 1));
96 obs.G.row(r).swap(obs.G.row(r - 1));
97 }
98}
99
101inline void eraseObservationRow(gpr::Observation& obs, Eigen::Index k)
102{
103 const Eigen::Index n = obs.R.rows();
104 if (k < 0 || k >= n) return;
105 for (Eigen::Index r = k; r + 1 < n; ++r) {
106 obs.R.row(r) = obs.R.row(r + 1);
107 obs.E.row(r) = obs.E.row(r + 1);
108 obs.G.row(r) = obs.G.row(r + 1);
109 }
110 obs.R.conservativeResize(n - 1, obs.R.cols());
111 obs.E.conservativeResize(n - 1, obs.E.cols());
112 obs.G.conservativeResize(n - 1, obs.G.cols());
113}
114
121inline bool positionsCoincide(const Eigen::VectorXd& a,
122 const Eigen::VectorXd& b)
123{
124 if (a.size() != b.size()) return false;
125 return (a - b).squaredNorm() <= 1e-12;
126}
127
130inline int findPositionRow(const gpr::Observation& obs,
131 const Eigen::VectorXd& pos)
132{
133 for (Eigen::Index r = 0; r < obs.R.rows(); ++r) {
134 const Eigen::VectorXd row = obs.R.row(r).transpose();
135 if (positionsCoincide(pos, row)) return static_cast<int>(r);
136 }
137 return -1;
138}
139
142inline bool hasPosition(const gpr::Observation& obs, const Eigen::VectorXd& pos)
143{
144 for (Eigen::Index r = 0; r < obs.R.rows(); ++r) {
145 const Eigen::VectorXd row = obs.R.row(r).transpose();
146 if (positionsCoincide(row, pos)) return true;
147 }
148 return false;
149}
150
151inline int findPositionIndex(const gpr::Observation& obs,
152 const Eigen::VectorXd& pos)
153{
154 for (Eigen::Index r = 0; r < obs.R.rows(); ++r) {
155 const Eigen::VectorXd row = obs.R.row(r).transpose();
156 if (positionsCoincide(row, pos)) return static_cast<int>(r);
157 }
158 return -1;
159}
160} // namespace detail
161
178
200 int image_index = -1;
201 Eigen::VectorXd positions;
202 double energy = std::numeric_limits<double>::quiet_NaN();
203 Eigen::VectorXd gradient;
204 bool certificate_row = false;
205 };
206
208 int owner = -1;
209 std::uint64_t revision = 0;
210
211 [[nodiscard]] static SurrogateFingerprint global(std::uint64_t revision)
212 {
213 return {-1, revision};
214 }
215
216 [[nodiscard]] static SurrogateFingerprint image(int image_idx,
217 std::uint64_t revision)
218 {
219 return {image_idx, revision};
220 }
221
222 [[nodiscard]] bool operator==(
223 const SurrogateFingerprint& other) const noexcept
224 {
225 return owner == other.owner && revision == other.revision;
226 }
227
228 [[nodiscard]] bool operator!=(
229 const SurrogateFingerprint& other) const noexcept
230 {
231 return !(*this == other);
232 }
233 };
234
235 [[nodiscard]] static int selectMmfModelOwner(bool dimer_use_global_gp,
236 bool image_model_eligible,
237 int image_idx)
238 {
239 return !dimer_use_global_gp && image_model_eligible && image_idx >= 0
240 ? image_idx
241 : -1;
242 }
243
247
254 {
255 // A BFGS seed carries only positive curvature and could replace the
256 // negative mode required by the session's subsequent saddle search.
257 if (config.seed_curvature &&
259 throw std::invalid_argument(
260 "saddle secant curvature seed does not support the BFGS "
261 "method");
262 std::vector<SecantReplaySample> replay;
263 replay.swap(secant_replay_);
264 secant_config_ = config;
265 global_secant_ = optim::SecantHessian(config.method);
266 image_secants_.clear();
267 secant_force_samples_.clear();
268 secant_counts_ = {};
269 secant_pairs_checked_ = 0;
270 if (!config.quadratic_prior_mean) gp.clearSecantQuadraticPrior();
271 // Keep the log while the features are off so a later enable can
272 // restore the per-image warm-start seeds.
273 if (!config.enabled()) {
274 secant_replay_.swap(replay);
275 return;
276 }
277 if (!replay.empty()) {
278 for (const SecantReplaySample& sample: replay)
279 observeSecant(sample.image_idx, sample.position,
280 sample.gradient, sample.energy, sample.accounting,
281 sample.training_row);
282 return;
283 }
284 for (Eigen::Index row = 0; row < training_obs.R.rows(); ++row) {
285 if (row >= training_obs.E.rows() || training_obs.E.cols() < 1 ||
286 row >= training_obs.G.rows() ||
287 training_obs.G.cols() != training_obs.R.cols())
288 throw std::logic_error(
289 "secant replay is missing a retained true force");
290 observeSecant(-1, training_obs.R.row(row).transpose(),
291 training_obs.G.row(row).transpose(),
292 training_obs.E(row, 0),
294 }
295 }
296
302 template <class Measure>
303 bool purchaseSecantConsistencyProbe(Measure&& measure)
304 {
305 if (!secant_config_.consistency_check) return false;
306 if (!global_secant_.available() ||
307 global_secant_.pairs() <= secant_pairs_checked_)
308 return false;
309 const double length = global_secant_.lastDirection().norm();
310 if (!(length > 0.0) || !std::isfinite(length))
311 throw std::runtime_error(
312 "secant consistency requested but the latest step is "
313 "degenerate");
314 const Eigen::VectorXd direction =
315 global_secant_.lastDirection() / length;
316 gpr::Coord at_reference(1, direction.size());
317 at_reference.row(0) = global_secant_.referencePosition().transpose();
318 Eigen::VectorXd posterior_action;
319 if (!gp.isDecomposedSuccessfully() && !gp.hasActivePosterior())
320 return false;
321 if (!gp.calculateMeanHessianVectorDispatched(at_reference, direction,
322 posterior_action))
323 return false;
324 const optim::SecantConsistency consistency = global_secant_.consistency(
325 posterior_action, secant_config_.consistency_relative_tolerance);
326 if (!consistency.available)
327 throw std::runtime_error(
328 "secant consistency requested but comparison is invalid");
329 secant_pairs_checked_ = global_secant_.pairs();
330 if (consistency.trusted) return false;
331 ++secant_counts_.consistency_rejections;
332 if (secant_counts_.hvp_calls != 0) return false;
333 if (!(secant_config_.finite_difference_step > 0.0) ||
334 !std::isfinite(secant_config_.finite_difference_step))
335 throw std::invalid_argument(
336 "secant finite-difference step must be positive");
337 const Eigen::VectorXd probe =
338 global_secant_.referencePosition() +
339 secant_config_.finite_difference_step * consistency.direction;
340 if (!std::forward<Measure>(measure)(probe)) return false;
341 ++secant_counts_.hvp_calls;
342 return true;
343 }
344
346 const noexcept
347 {
348 return global_secant_;
349 }
350
352 int image_idx) const noexcept
353 {
354 if (image_idx < 0 ||
355 image_idx >= static_cast<int>(image_secants_.size()))
356 return nullptr;
357 return &image_secants_[static_cast<std::size_t>(image_idx)];
358 }
359
361 void noteTrueForceSecant(int image_idx, const Eigen::VectorXd& positions,
362 double energy, const Eigen::VectorXd& gradient)
363 {
364 observeSecant(image_idx, positions, gradient, energy,
366 /*training_row=*/false);
367 }
368
370 [[nodiscard]] std::size_t secantReplaySize() const noexcept
371 {
372 return secant_replay_.size();
373 }
374
376 [[nodiscard]] std::size_t secantReplayTrainingRows() const noexcept
377 {
378 std::size_t count = 0;
379 for (const SecantReplaySample& sample: secant_replay_)
380 if (sample.training_row) ++count;
381 return count;
382 }
383
386 const Eigen::VectorXd& position) const
387 {
388 for (const SecantReplaySample& sample: secant_replay_) {
389 if (!sample.training_row) continue;
390 if (detail::positionsCoincide(sample.position, position))
391 return true;
392 }
393 return false;
394 }
395
397 {
398 optim::SecantCurvatureCounts counts = secant_counts_;
399 counts.quadratic_mean_uses += gp.secantQuadraticPriorUses();
400 return counts;
401 }
402
407 {
408 secant_counts_.pairs_accepted += extra.pairs_accepted;
409 secant_counts_.pairs_rejected += extra.pairs_rejected;
410 secant_counts_.hvp_calls += extra.hvp_calls;
411 secant_counts_.consistency_rejections += extra.consistency_rejections;
412 secant_counts_.quadratic_mean_uses += extra.quadratic_mean_uses;
413 }
414
427 std::vector<double> virtual_retire_radii;
436
445
454 bool stagnation_handoff = false;
455
461 std::numeric_limits<double>::quiet_NaN();
462
466 std::vector<IndexedObservation> current_chain_certificates;
467
472
476 struct ImageModel {
477 void setGP(std::unique_ptr<gpr::GaussianProcessRegression> next_gp)
478 {
479 gp_ = std::move(next_gp);
480 ++surrogate_revision_;
481 invalidateMaterialization();
482 }
483
485 {
486 return gp_.get();
487 }
488
489 [[nodiscard]] const gpr::GaussianProcessRegression* gp() const
490 {
491 return gp_.get();
492 }
493
494 [[nodiscard]] const gpr::Observation& observations() const
495 {
496 return observations_;
497 }
498
500 {
501 if (gp_) gp_->updateConfiguration(configuration);
502 ++surrogate_revision_;
503 ++geometry_prior_revision_;
504 invalidateMaterialization();
505 }
506
508 std::shared_ptr<const gpr::geometry::InternalCoordinateChart> chart,
509 double length_scale)
510 {
511 if (!chart || !chart->valid() || !(length_scale > 0.0) ||
512 !std::isfinite(length_scale)) {
513 throw std::invalid_argument(
514 "image GP requires a valid internal-coordinate chart");
515 }
516 if (internal_coordinate_chart_ == chart &&
517 internal_coordinate_length_scale_ == length_scale) {
518 return;
519 }
520 internal_coordinate_chart_ = std::move(chart);
521 internal_coordinate_length_scale_ = length_scale;
522 ++geometry_prior_revision_;
523 ++surrogate_revision_;
524 invalidateMaterialization();
525 }
526
528 {
529 if (!internal_coordinate_chart_) return;
530 internal_coordinate_chart_.reset();
531 internal_coordinate_length_scale_ =
532 std::numeric_limits<double>::quiet_NaN();
533 if (gp_) {
534 gp_->getSexpAtCovarianceFunction().clearManifoldChart();
535 }
536 ++geometry_prior_revision_;
537 ++surrogate_revision_;
538 invalidateMaterialization();
539 }
540
541 [[nodiscard]] const std::shared_ptr<
543 internalCoordinateChart() const noexcept
544 {
545 return internal_coordinate_chart_;
546 }
547
548 [[nodiscard]] double internalCoordinateLengthScale() const noexcept
549 {
550 return internal_coordinate_length_scale_;
551 }
552
554 {
555 if (reference_path.rows() <= 0 || reference_path.cols() <= 0 ||
556 !reference_path.allFinite()) {
557 throw std::invalid_argument(
558 "image GP requires a finite geodesic reference path");
559 }
560 if (geodesic_reference_path_.rows() == reference_path.rows() &&
561 geodesic_reference_path_.cols() == reference_path.cols() &&
562 (geodesic_reference_path_.array() == reference_path.array())
563 .all()) {
564 return;
565 }
566 geodesic_reference_path_ = std::move(reference_path);
567 if (gp_) {
568 gp_->getSexpAtCovarianceFunction().clearGeodesicHeatKernel();
569 }
570 ++geometry_prior_revision_;
571 ++surrogate_revision_;
572 invalidateMaterialization();
573 }
574
576 {
577 if (!hasGeodesicReferencePath()) return;
578 geodesic_reference_path_.resize(0, 0);
579 if (gp_) {
580 gp_->getSexpAtCovarianceFunction().clearGeodesicHeatKernel();
581 }
582 ++geometry_prior_revision_;
583 ++surrogate_revision_;
584 invalidateMaterialization();
585 }
586
587 [[nodiscard]] bool hasGeodesicReferencePath() const noexcept
588 {
589 return geodesic_reference_path_.size() > 0;
590 }
591
592 [[nodiscard]] const gpr::Coord& geodesicReferencePath() const noexcept
593 {
594 return geodesic_reference_path_;
595 }
596
601 [[nodiscard]] std::uint64_t observationRevision() const noexcept
602 {
603 return observation_revision_;
604 }
605
610 [[nodiscard]] std::uint64_t surrogateRevision() const noexcept
611 {
612 return surrogate_revision_;
613 }
614
616 const Eigen::VectorXd& theta_global,
617 double likelihood_noise_floor_sigma2,
618 const SharedParameterState& shared_state = {}) const
619 {
620 if (!surrogate_inputs_initialized_ ||
621 surrogate_shared_state_ != shared_state ||
622 !surrogateInputsMatch(
623 surrogate_theta_, surrogate_noise_floor_sigma2_,
624 theta_global, likelihood_noise_floor_sigma2)) {
625 ++surrogate_revision_;
626 surrogate_theta_ = theta_global;
627 surrogate_noise_floor_sigma2_ = likelihood_noise_floor_sigma2;
628 surrogate_shared_state_ = shared_state;
629 surrogate_inputs_initialized_ = true;
630 }
631 return surrogate_revision_;
632 }
633
639 [[nodiscard]] const std::vector<int>& selectedIndices() const
640 {
641 return selected_indices_;
642 }
643
649 [[nodiscard]] const std::vector<int>& directIndices() const
650 {
651 return direct_indices_;
652 }
653
654 [[nodiscard]] bool hasEnoughRows(int n_min) const
655 {
656 return observations_.E.rows() >= n_min;
657 }
658
659 [[nodiscard]] int directObservationCount() const
660 {
661 return direct_observation_count_;
662 }
663
668 [[nodiscard]] bool hasEnoughDirectRows(int n_min) const
669 {
670 return direct_observation_count_ >= n_min;
671 }
672
673 void appendObservation(const Eigen::VectorXd& positions, double energy,
674 const Eigen::VectorXd& gradient,
675 int global_row_index)
676 {
677 // Drop a row that repeats a configuration already held: a
678 // dimer burst restarting from a stored stop point
679 // re-oracles the same geometry every phase, and a
680 // duplicate row leaves the per-image covariance
681 // rank-deficient -> non-finite Cholesky factor -> NaN
682 // curvature handed back to the dimer.
683 if (detail::hasPosition(observations_, positions)) return;
684 // Row k of the local set is selected_indices_[k]; archived
685 // rows ride behind the selected ones. A row bound to a global
686 // index therefore joins the selected rows, ahead of the
687 // archive, or every later refresh would write it over an
688 // archived row.
689 if (global_row_index >= 0) {
690 detail::insertObservationRow(
691 observations_,
692 static_cast<Eigen::Index>(selected_indices_.size()),
693 positions, energy, gradient);
694 selected_indices_.push_back(global_row_index);
695 direct_indices_.push_back(global_row_index);
696 } else {
697 detail::appendObservationRow(observations_, positions, energy,
698 gradient);
699 }
700 ++direct_observation_count_;
701 recordObservationMutation();
702 }
703
707 void refreshSelectedObservation(int global_row,
708 const gpr::Observation& global)
709 {
710 const auto found = std::find(selected_indices_.begin(),
711 selected_indices_.end(), global_row);
712 if (found == selected_indices_.end()) return;
713 const auto row = static_cast<Eigen::Index>(
714 std::distance(selected_indices_.begin(), found));
715 const bool unchanged =
716 (observations_.R.row(row).array() ==
717 global.R.row(global_row).array())
718 .all() &&
719 observations_.E(row, 0) == global.E(global_row, 0) &&
720 (observations_.G.row(row).array() ==
721 global.G.row(global_row).array())
722 .all();
723 if (unchanged) return;
724 observations_.R.row(row) = global.R.row(global_row);
725 observations_.E.row(row) = global.E.row(global_row);
726 observations_.G.row(row) = global.G.row(global_row);
727 recordObservationMutation();
728 }
729
734 void compactAfterRowRemoval(int removed_row)
735 {
736 const auto selected =
737 std::find(selected_indices_.begin(), selected_indices_.end(),
738 removed_row);
739 const bool selected_observation_removed =
740 selected != selected_indices_.end();
741 if (selected_observation_removed) {
742 // Row k is selected_indices_[k]; archived rows ride behind.
743 const auto position = static_cast<Eigen::Index>(
744 std::distance(selected_indices_.begin(), selected));
745 if (position >= observations_.R.rows()) {
746 throw std::logic_error(
747 "image local set is shorter than its selected rows");
748 }
749 detail::eraseObservationRow(observations_, position);
750 }
751 auto compact = [removed_row](std::vector<int>& indices) {
752 std::size_t w = 0;
753 for (std::size_t r = 0; r < indices.size(); ++r) {
754 if (indices[r] == removed_row) continue;
755 indices[w++] =
756 indices[r] > removed_row ? indices[r] - 1 : indices[r];
757 }
758 indices.resize(w);
759 };
760 const std::size_t direct_before = direct_indices_.size();
761 compact(selected_indices_);
762 compact(direct_indices_);
763 if (direct_indices_.size() < direct_before &&
764 direct_observation_count_ > 0) {
765 --direct_observation_count_;
766 }
767 if (selected_observation_removed) {
768 recordObservationMutation();
769 }
770 }
771
776 void remapGlobalRows(const std::vector<int>& old_to_new,
777 const gpr::Observation& global)
778 {
779 const std::vector<int> previous_selected = selected_indices_;
780 const std::size_t direct_before = direct_indices_.size();
781 auto rewrite = [&old_to_new](std::vector<int>& indices) {
782 std::vector<int> next;
783 next.reserve(indices.size());
784 for (const int old_index: indices) {
785 if (old_index < 0 || static_cast<std::size_t>(old_index) >=
786 old_to_new.size())
787 continue;
788 const int mapped =
789 old_to_new[static_cast<std::size_t>(old_index)];
790 if (mapped >= 0) next.push_back(mapped);
791 }
792 indices.swap(next);
793 };
794 rewrite(selected_indices_);
795 rewrite(direct_indices_);
796 if (direct_indices_.size() < direct_before) {
797 const int removed =
798 static_cast<int>(direct_before - direct_indices_.size());
799 direct_observation_count_ =
800 std::max(0, direct_observation_count_ - removed);
801 }
802 if (selected_indices_ == previous_selected) return;
803 gpr::Observation local;
804 for (const int row: selected_indices_) {
805 if (row < 0 || row >= global.R.rows()) continue;
806 const double energy =
807 row < global.E.rows() ? global.E(row, 0) : 0.0;
808 Eigen::VectorXd gradient(global.R.cols());
809 if (row < global.G.rows())
810 gradient = global.G.row(row).transpose();
811 else
812 gradient.setZero();
813 detail::appendObservationRow(
814 local, global.R.row(row).transpose(), energy, gradient);
815 }
816 observations_ = std::move(local);
817 recordObservationMutation();
818 if (gp_ && observations_.R.rows() > 0 && gp_->hasBeenOptimized()) {
819 const Eigen::VectorXd theta = gp_->packInlaHyperparameters();
820 if (theta.size() > 0) gp_->setParameters(theta);
821 gp_->updateModelWithFullData(observations_);
822 }
823 }
824
836 int pruneAdaptiveAtPoint(const Eigen::VectorXd& band_point)
837 {
838 const Eigen::Index min_rows = 4;
839 if (!gp_ || observations_.R.rows() <= min_rows) return 0;
840 if (selected_indices_.size() !=
841 static_cast<std::size_t>(observations_.R.rows())) {
842 return 0;
843 }
844 gpr::Coord point(1, band_point.size());
845 point.row(0) = band_point.transpose();
846 Eigen::VectorXd influence;
847 if (!gp_->observationBandInfluence(observations_, point,
848 influence)) {
849 return 0;
850 }
851 if (influence.size() != observations_.R.rows()) return 0;
852 const double noise_sigma =
853 std::sqrt(std::max(gp_->getLikGaussian().getSigma2(), 0.0));
854 if (!(noise_sigma > 0.0) || !std::isfinite(noise_sigma)) return 0;
855 Eigen::Index r_min = -1;
856 double v_min = std::numeric_limits<double>::infinity();
857 for (Eigen::Index r = 0; r < influence.size(); ++r) {
858 if (influence(r) < v_min) {
859 v_min = influence(r);
860 r_min = r;
861 }
862 }
863 if (r_min < 0 || !(v_min < noise_sigma)) return 0;
864 const int global_row =
865 selected_indices_[static_cast<std::size_t>(r_min)];
866 detail::eraseObservationRow(observations_, r_min);
867 selected_indices_.erase(selected_indices_.begin() + r_min);
868 const auto direct_it = std::find(direct_indices_.begin(),
869 direct_indices_.end(), global_row);
870 if (direct_it != direct_indices_.end()) {
871 direct_indices_.erase(direct_it);
872 }
873 recordObservationMutation();
874 return 1;
875 }
876
878 std::vector<int> selected_indices,
879 std::vector<uint64_t> archived_keys = {})
880 {
881 observations_ = std::move(observations);
882 selected_indices_ = std::move(selected_indices);
883 archived_keys_ = std::move(archived_keys);
884 recordObservationMutation();
885 }
886
889 [[nodiscard]] const std::vector<uint64_t>& archivedKeys() const noexcept
890 {
891 return archived_keys_;
892 }
893
894 [[nodiscard]] bool materializedFor(
895 const Eigen::VectorXd& theta_global,
896 double likelihood_noise_floor_sigma2,
897 const SharedParameterState& shared_state = {}) const
898 {
899 if (materialized_revision_ != observation_revision_) return false;
900 if (materialized_shared_state_ != shared_state) return false;
901 if (materialized_geometry_prior_revision_ !=
902 geometry_prior_revision_) {
903 return false;
904 }
905 return surrogateInputsMatch(
906 materialized_theta_, materialized_noise_floor_sigma2_,
907 theta_global, likelihood_noise_floor_sigma2);
908 }
909
910 void recordMaterialized(const Eigen::VectorXd& theta_global,
911 double likelihood_noise_floor_sigma2,
912 const SharedParameterState& shared_state = {})
913 {
914 const double effective_noise_sigma2 =
915 gp_ ? gp_->getSigma2() : likelihood_noise_floor_sigma2;
917 theta_global, effective_noise_sigma2, shared_state);
918 materialized_revision_ = observation_revision_;
919 materialized_geometry_prior_revision_ = geometry_prior_revision_;
920 materialized_theta_ = theta_global;
921 materialized_noise_floor_sigma2_ = likelihood_noise_floor_sigma2;
922 materialized_shared_state_ = shared_state;
923 }
924
925 private:
926 [[nodiscard]] static bool surrogateInputsMatch(
927 const Eigen::VectorXd& lhs_theta, double lhs_noise_floor_sigma2,
928 const Eigen::VectorXd& rhs_theta, double rhs_noise_floor_sigma2)
929 {
930 if (lhs_theta.size() != rhs_theta.size()) return false;
931 // Log parameters can represent zero variance or infinite lengths.
932 // Reuse requires identical values, including matching infinities.
933 if (lhs_theta.size() > 0 &&
934 !(lhs_theta.array() == rhs_theta.array()).all()) {
935 return false;
936 }
937 const bool lhs_floor_enabled =
938 std::isfinite(lhs_noise_floor_sigma2) &&
939 lhs_noise_floor_sigma2 > 0.0;
940 const bool rhs_floor_enabled =
941 std::isfinite(rhs_noise_floor_sigma2) &&
942 rhs_noise_floor_sigma2 > 0.0;
943 if (lhs_floor_enabled != rhs_floor_enabled) return false;
944 return !lhs_floor_enabled ||
945 lhs_noise_floor_sigma2 == rhs_noise_floor_sigma2;
946 }
947
948 void recordObservationMutation()
949 {
950 ++observation_revision_;
951 ++surrogate_revision_;
952 invalidateMaterialization();
953 }
954
955 void invalidateMaterialization()
956 {
957 materialized_revision_ = std::numeric_limits<std::uint64_t>::max();
958 materialized_geometry_prior_revision_ =
959 std::numeric_limits<std::uint64_t>::max();
960 materialized_theta_.resize(0);
961 materialized_noise_floor_sigma2_ =
962 std::numeric_limits<double>::quiet_NaN();
963 }
964
965 gpr::Observation observations_;
966 std::unique_ptr<gpr::GaussianProcessRegression> gp_;
967 std::shared_ptr<const gpr::geometry::InternalCoordinateChart>
968 internal_coordinate_chart_;
969 double internal_coordinate_length_scale_ =
970 std::numeric_limits<double>::quiet_NaN();
971 gpr::Coord geodesic_reference_path_;
972 std::vector<int> selected_indices_;
973 std::vector<uint64_t> archived_keys_;
974 std::vector<int> direct_indices_;
975 int direct_observation_count_ = 0;
976 std::uint64_t observation_revision_ = 0;
977 mutable std::uint64_t surrogate_revision_ = 0;
978 std::uint64_t geometry_prior_revision_ = 0;
979 mutable bool surrogate_inputs_initialized_ = false;
980 mutable Eigen::VectorXd surrogate_theta_;
981 mutable SharedParameterState surrogate_shared_state_;
982 mutable double surrogate_noise_floor_sigma2_ =
983 std::numeric_limits<double>::quiet_NaN();
984 std::uint64_t materialized_revision_ =
985 std::numeric_limits<std::uint64_t>::max();
986 std::uint64_t materialized_geometry_prior_revision_ =
987 std::numeric_limits<std::uint64_t>::max();
988 Eigen::VectorXd materialized_theta_;
989 SharedParameterState materialized_shared_state_;
990 double materialized_noise_floor_sigma2_ =
991 std::numeric_limits<double>::quiet_NaN();
992 };
993
997 std::vector<ImageModel> image_models;
998
1000 {
1001 if (!initialised) return {};
1002 return {gp.lengthScaleFitState(),
1003 gp.outputMean(),
1004 gp.outputScale(),
1005 gp.likelihoodNoiseVariance(),
1006 gp.getConstantCovarianceFunction().getConstSigma2(),
1007 gp.outputMeanFrozen(),
1008 gp.getUncertaintyMode(),
1009 integratesHyperparameters(gp) ? training_revision_ : 0,
1010 gp.atomicEnvironmentModelEnabled() ? gp.factorEpoch() : 0};
1011 }
1012
1013 [[nodiscard]] static bool integratesHyperparameters(
1014 const gpr::GaussianProcessRegression& model)
1015 {
1016 const auto mode = model.getUncertaintyMode();
1017 return mode == gpr::UncertaintyMode::EB ||
1019 }
1020
1022 const gpr::GaussianProcessRegression& model) const
1023 {
1024 return integratesHyperparameters(gp) &&
1026 !gp.getSexpAtCovarianceFunction().usesManifoldChart() &&
1028 }
1029
1030 [[nodiscard]] std::uint64_t imageModelSurrogateRevision(int image_idx) const
1031 {
1032 if (image_idx < 0 ||
1033 image_idx >= static_cast<int>(image_models.size())) {
1034 return 0;
1035 }
1036 const double effective_noise_sigma2 = effectiveModelNoiseVariance(
1037 image_models[image_idx].gp(), likelihoodNoiseFloorSigma2());
1038 return image_models[image_idx].synchronizeSurrogateRevision(
1039 gp.packInlaHyperparameters(), effective_noise_sigma2,
1041 }
1042
1043 [[nodiscard]] std::uint64_t trainingRevision() const noexcept
1044 {
1045 return training_revision_;
1046 }
1047
1048 [[nodiscard]] std::uint64_t globalModelSurrogateRevision() const
1049 {
1050 const Eigen::VectorXd theta = gp.packInlaHyperparameters();
1051 const auto shared_state = sharedParameterState();
1052 const double effective_noise_sigma2 =
1053 effectiveModelNoiseVariance(&gp, likelihoodNoiseFloorSigma2());
1054 if (!global_surrogate_inputs_initialized_ ||
1055 global_surrogate_training_revision_ != training_revision_ ||
1056 global_surrogate_shared_state_ != shared_state ||
1057 !surrogateInputsMatch(global_surrogate_theta_,
1058 global_surrogate_noise_sigma2_, theta,
1059 effective_noise_sigma2)) {
1060 ++global_surrogate_revision_;
1061 global_surrogate_training_revision_ = training_revision_;
1062 global_surrogate_theta_ = theta;
1063 global_surrogate_noise_sigma2_ = effective_noise_sigma2;
1064 global_surrogate_shared_state_ = shared_state;
1065 global_surrogate_inputs_initialized_ = true;
1066 }
1067 return global_surrogate_revision_;
1068 }
1069
1070 [[nodiscard]] SurrogateFingerprint surrogateFingerprint(int owner) const
1071 {
1072 if (!gp.atomicEnvironmentModelEnabled() && owner >= 0 &&
1073 owner < static_cast<int>(image_models.size())) {
1075 owner, imageModelSurrogateRevision(owner));
1076 }
1078 }
1079
1080 [[nodiscard]] int mmfModelOwner(int image_idx,
1081 bool dimer_use_global_gp) const
1082 {
1083 const bool image_model_eligible =
1085 if (image_model_eligible &&
1086 image_models[image_idx].internalCoordinateChart()) {
1087 return image_idx;
1088 }
1089 return selectMmfModelOwner(dimer_use_global_gp, image_model_eligible,
1090 image_idx);
1091 }
1092
1094 int image_idx, bool dimer_use_global_gp) const
1095 {
1096 return surrogateFingerprint(
1097 mmfModelOwner(image_idx, dimer_use_global_gp));
1098 }
1099
1105
1115
1126
1130
1135
1140 std::function<void(gpr::InputParameters&, gpr::AtomsConfiguration&)>
1142
1146 double path_energy_ceiling = std::numeric_limits<double>::infinity();
1147
1150 bool initialised = false;
1151
1156 void setLikelihoodNoiseFloorRms(const double* noise_rms) noexcept
1157 {
1158 likelihood_noise_floor_rms_ = noise_rms;
1159 }
1160
1165 void setRefitTrainingRevisions(std::uint64_t revisions) noexcept
1166 {
1167 refit_training_revisions_ = revisions;
1168 }
1169 [[nodiscard]] std::uint64_t refitTrainingRevisions() const noexcept
1170 {
1171 return refit_training_revisions_;
1172 }
1173
1177 [[nodiscard]] std::uint64_t surfaceEpoch() const noexcept
1178 {
1179 return gp.factorEpoch();
1180 }
1181
1182#ifdef USE_READCON_DB
1195 void setObservationArchive(ObservationArchive* archive,
1196 bool adopt_existing = true)
1197 {
1198 observation_archive_ = archive;
1199 archive_pool_.clear();
1200 if (!archive) {
1201 archive_first_row_ = 0;
1202 archive_pool_snapshot_ = 0;
1203 return;
1204 }
1205 if (!adopt_existing) {
1206 archive_first_row_ = archive->size();
1207 archive_pool_snapshot_ = archive_first_row_;
1208 return;
1209 }
1210 const auto rows = archive->fetchAll();
1211 const Eigen::Index preexisting = training_obs.R.rows();
1212 const bool saved_dedup = resolution_dedup_enabled_;
1214 for (const auto& row: rows) {
1215 if (row.positions.size() == 0 ||
1216 row.gradient.size() != row.positions.size() ||
1217 !row.positions.allFinite() || !row.gradient.allFinite() ||
1218 !std::isfinite(row.energy)) {
1219 continue;
1220 }
1221 const int existing =
1222 detail::findPositionRow(training_obs, row.positions);
1223 if (existing >= 0 && existing < preexisting) continue;
1224 appendObservation(row.positions, row.energy, row.gradient,
1226 }
1227 resolution_dedup_enabled_ = saved_dedup;
1228 // The adopted rows are this session's corpus, including after a
1229 // later prune. Snapshot 0 forces the next re-selection to read
1230 // them back; new rows keep appending after them.
1231 archive_first_row_ = 0;
1232 archive_pool_snapshot_ = 0;
1233 }
1234 [[nodiscard]] ObservationArchive* observationArchive() const noexcept
1235 {
1236 return observation_archive_;
1237 }
1238#endif
1239
1246 {
1247 likelihood_noise_floor_sigma2_ = detail::allreduceFinitePositiveMaximum(
1248 localLikelihoodNoiseFloorSigma2());
1249 }
1250
1255 {
1256 if (initialised) return;
1257 if (!gp_setup) return;
1259 gp.initialize(input_parameters, atoms_config);
1260 initialised = true;
1261 }
1262
1268 {
1269 if (!after_initialise_) return false;
1270 const bool installed =
1271 after_initialise_(gp, atoms_config, training_obs);
1272 after_initialise_ = nullptr;
1273 return installed;
1274 }
1275
1277 std::function<bool(GaussianProcessRegression&,
1278 const AtomsConfiguration&, const Observation&)>;
1279
1283 {
1284 after_initialise_ = std::move(hook);
1285 }
1286
1288 [[nodiscard]] int priorObservations() const noexcept
1289 {
1290 return prior_observations_;
1291 }
1292
1293 void notePriorObservations(int count) noexcept
1294 {
1295 prior_observations_ = count;
1296 }
1297
1302 bool present = false;
1303 double signal_variance = 1.0;
1304 double length_scale = 1.0;
1305 };
1306
1307 void noteLocalKernelSeed(double signal_variance,
1308 double length_scale) noexcept
1309 {
1310 if (!(std::isfinite(signal_variance) && signal_variance > 0.0 &&
1311 std::isfinite(length_scale) && length_scale > 0.0))
1312 return;
1313 local_kernel_seed_.present = true;
1314 local_kernel_seed_.signal_variance = signal_variance;
1315 local_kernel_seed_.length_scale = length_scale;
1316 }
1317
1318 [[nodiscard]] const LocalKernelSeed& localKernelSeed() const noexcept
1319 {
1320 return local_kernel_seed_;
1321 }
1322
1326 {
1327 gp_model_ready_ = training_obs.R.rows() > 0;
1328 fitted_training_revision_ = training_revision_;
1329 conditioned_training_revision_ = training_revision_;
1330 kernel_requires_refit_ = false;
1331 }
1332
1336 {
1337 if (!initialised) initialise();
1338 if (!initialised || (atoms_config.atoms_froz_active.type.size() == 0 &&
1339 atoms_config.atoms_froz_inactive.type.size() == 0))
1340 return false;
1341 auto selected = atoms_config;
1342 aux::ProblemSetUp setup;
1343 const bool active_set_changed = setup.activateFrozenAtoms(
1344 band, input_parameters.actdist_fro.value, selected);
1345 // Selection also removes inactive clones of moving atoms. That
1346 // bookkeeping change does not alter GP features, but it must persist
1347 // so the clone cannot re-enter a later nearest-neighbour selection.
1348 atoms_config = std::move(selected);
1349 if (!active_set_changed) return false;
1350 parkActiveModelBeforeSwitch(-1);
1351 gp.updateConfiguration(atoms_config);
1352 for (auto& model: image_models)
1353 model.updateConfiguration(atoms_config);
1354 gp_model_ready_ = false;
1355 kernel_requires_refit_ = true;
1356 ++global_surrogate_revision_;
1357 markActiveModel(-1);
1358 return true;
1359 }
1360
1367 void initializePerImage(int n_images)
1368 {
1369 if (!initialised) initialise();
1370 if (!gp_setup) return;
1371 bool changed = false;
1372 if (static_cast<int>(image_models.size()) != n_images) {
1373 image_models.clear();
1374 image_models.resize(n_images);
1375 changed = true;
1376 }
1377 gpr::Observation seed_obs;
1378 for (auto& model: image_models) {
1379 // The compact atomic posterior is shared by every image. Slots
1380 // retain their measured rows without owning duplicate posteriors.
1381 if (gp.atomicEnvironmentModelEnabled()) {
1382 if (model.gp()) {
1383 model.setGP({});
1384 changed = true;
1385 }
1386 model.clearInternalCoordinateChart();
1387 model.clearGeodesicReferencePath();
1388 continue;
1389 }
1390 if (model.gp()) continue;
1391 auto local = std::make_unique<gpr::GaussianProcessRegression>();
1392 local->initialize(input_parameters, atoms_config);
1393 local->setHyperparameters(seed_obs, atoms_config, true, true, true);
1394 model.setGP(std::move(local));
1395 changed = true;
1396 }
1397 if (changed) markActiveModel(-1);
1398 }
1399
1406 int boundActiveSetToBand(const gpr::Coord& band_positions,
1407 Eigen::Index max_rows)
1408 {
1409 const Eigen::Index rows = training_obs.R.rows();
1410 if (!initialised || max_rows <= 0 || rows <= max_rows) return 0;
1411 const Eigen::Index dimensions = training_obs.R.cols();
1412 if (dimensions <= 0 || band_positions.cols() != dimensions ||
1413 band_positions.rows() == 0)
1414 return 0;
1415
1416 gpr::FieldMatrixd distances;
1417 const auto& covariance = gp.getSexpAtCovarianceFunction();
1418 const auto& scales = covariance.getLengthScaleRef();
1419 if (scales.size() > 0 && scales.allFinite() &&
1420 scales.minCoeff() > 0.0) {
1421 covariance.correlationDistances(band_positions, training_obs.R,
1422 atoms_config, distances);
1423 } else {
1424 aux::Distance metric;
1425 metric.dist_emd(band_positions, training_obs.R, atoms_config,
1426 distances);
1427 }
1428 if (distances.rows() != band_positions.rows() ||
1429 distances.cols() != rows)
1430 return 0;
1431
1432 std::vector<char> protected_row(static_cast<std::size_t>(rows), 0);
1433 const Eigen::Index recent = std::min(
1434 band_positions.rows(), std::max<Eigen::Index>(1, max_rows / 2));
1435 for (Eigen::Index row = rows - recent; row < rows; ++row)
1436 protected_row[static_cast<std::size_t>(row)] = 1;
1437 Eigen::Index protected_count = recent;
1438 for (Eigen::Index image = 0;
1439 image < distances.rows() && protected_count < max_rows; ++image) {
1440 Eigen::Index nearest;
1441 const double distance = distances.row(image).minCoeff(&nearest);
1442 if (std::isfinite(distance) &&
1443 !protected_row[static_cast<std::size_t>(nearest)]) {
1444 protected_row[static_cast<std::size_t>(nearest)] = 1;
1445 ++protected_count;
1446 }
1447 }
1448
1449 const Eigen::Index removed = rows - max_rows;
1450 const auto erase_row = [&](Eigen::Index row) {
1451 detail::eraseObservationRow(training_obs, row);
1452 if (static_cast<std::size_t>(row) < training_multiplicity.size())
1454 row);
1455 for (auto& model: image_models)
1456 model.compactAfterRowRemoval(static_cast<int>(row));
1457 protected_row.erase(protected_row.begin() + row);
1458 };
1459 // The row whose removal changes the posterior mean least in the
1460 // kernel norm goes first. That norm bounds the change at every
1461 // geometry, so a measured row far from the band that still holds
1462 // the band out of the region it left is kept, and a row its
1463 // neighbours reproduce is dropped. One removal changes what every
1464 // remaining row is worth, so the norms are evaluated again before
1465 // the next one.
1466 Eigen::Index pending = removed;
1467 while (pending > 0 && gp_model_ready_ && gp.hasBeenOptimized()) {
1468 Eigen::VectorXd influence, removal_norm;
1469 if (!gp.observationBandInfluence(training_obs, band_positions,
1470 influence, /*collective=*/true,
1471 protected_row, &removal_norm) ||
1472 removal_norm.size() != training_obs.R.rows())
1473 break;
1474 Eigen::Index least = -1;
1475 for (Eigen::Index row = 0; row < removal_norm.size(); ++row) {
1476 if (protected_row[static_cast<std::size_t>(row)] ||
1477 !std::isfinite(removal_norm(row)))
1478 continue;
1479 if (least < 0 || removal_norm(row) < removal_norm(least))
1480 least = row;
1481 }
1482 if (least < 0) break;
1483 erase_row(least);
1484 --pending;
1485 }
1486 if (pending > 0 && training_obs.R.rows() == rows) {
1487 // Without a fitted model the kernel norm is undefined: the rows
1488 // farthest from the band in the prediction metric are dropped.
1489 std::vector<std::pair<double, Eigen::Index>> candidates;
1490 for (Eigen::Index row = 0; row < rows; ++row) {
1491 if (protected_row[static_cast<std::size_t>(row)]) continue;
1492 double distance = distances.col(row).minCoeff();
1493 if (!std::isfinite(distance))
1494 distance = std::numeric_limits<double>::infinity();
1495 candidates.emplace_back(distance, row);
1496 }
1497 std::stable_sort(candidates.begin(), candidates.end(),
1498 [](const auto& left, const auto& right) {
1499 return left.first > right.first;
1500 });
1501 std::vector<Eigen::Index> removed_rows;
1502 for (std::size_t i = 0; i < candidates.size() &&
1503 static_cast<Eigen::Index>(i) < pending;
1504 ++i)
1505 removed_rows.push_back(candidates[i].second);
1506 std::sort(removed_rows.begin(), removed_rows.end(),
1507 std::greater<>());
1508 for (const Eigen::Index row: removed_rows)
1509 erase_row(row);
1510 pending -= static_cast<Eigen::Index>(removed_rows.size());
1511 }
1512 if (pending == removed) return 0;
1513 discardPrunedSecantReplay();
1514 recordTrainingMutation();
1515 return static_cast<int>(removed - pending);
1516 }
1517
1530 [[nodiscard]] double observationResolutionFloor() const
1531 {
1532 if (!initialised) return -1.0;
1533 const auto& cov = gp.getSexpAtCovarianceFunction();
1534 const double magn = cov.getMagnSigma2();
1535 const double noise = gp.getSigma2();
1536 const auto& ls = cov.getLengthScaleRef();
1537 if (ls.size() == 0 || !std::isfinite(magn) || !(magn > 0.0) ||
1538 !std::isfinite(noise) || !(noise > 0.0))
1539 return -1.0;
1540 const double l_min = ls.minCoeff();
1541 if (!std::isfinite(l_min) || !(l_min > 0.0)) return -1.0;
1542 const double d = 0.5 * l_min * std::sqrt(noise / magn);
1543 return std::isfinite(d) ? d : -1.0;
1544 }
1545
1555 [[nodiscard]] double nearestTrainingDistance(
1556 const Eigen::VectorXd& positions) const
1557 {
1558 if (training_obs.R.rows() == 0)
1559 return std::numeric_limits<double>::infinity();
1560 gpr::Coord query(1, positions.size());
1561 query.row(0) = positions.transpose();
1562 aux::Distance distance;
1564 distance.dist_emd(query, training_obs.R, atoms_config, d);
1565 if (d.size() == 0) return std::numeric_limits<double>::infinity();
1566 return d.minCoeff();
1567 }
1568
1574 void appendObservation(const Eigen::VectorXd& positions, double energy,
1575 const Eigen::VectorXd& gradient,
1576 ObservationRetention retention =
1578 optim::SecantAccounting secant_accounting =
1580 {
1581#ifdef USE_READCON_DB
1582 // Every acquisition reaches the ledger, merged draws included.
1583 if (observation_archive_ &&
1585 (void)observation_archive_->append(positions, energy, gradient);
1586#else
1587 (void)retention;
1588#endif
1589 const int row =
1590 admitObservation(positions, energy, gradient, secant_accounting);
1591 if (row >= 0) appendSymmetryImage(row, positions, energy, gradient);
1592 }
1593
1602 {
1603 endpoint_symmetry_ = std::move(symmetry);
1604 if (endpoint_symmetry_.empty()) return;
1605 const Eigen::Index measured = training_obs.R.rows();
1606 for (Eigen::Index r = 0; r < measured; ++r) {
1607 const Eigen::VectorXd x = training_obs.R.row(r).transpose();
1608 const int existing = detail::findPositionRow(
1609 training_obs, endpoint_symmetry_.mapPositions(x));
1610 if (existing >= 0 && existing != static_cast<int>(r)) continue;
1611 appendSymmetryImage(static_cast<int>(r), x, training_obs.E(r, 0),
1612 training_obs.G.row(r).transpose());
1613 }
1614 }
1615
1616 [[nodiscard]] const EndpointSymmetry& endpointSymmetry() const noexcept
1617 {
1618 return endpoint_symmetry_;
1619 }
1620
1624 [[nodiscard]] long symmetryRowsAdmitted() const noexcept
1625 {
1627 }
1628 [[nodiscard]] long symmetryRowsRejected() const noexcept
1629 {
1631 }
1632
1636 void setResolutionDedup(bool on) noexcept
1637 {
1639 }
1640
1648 [[nodiscard]] bool withinTrainingResolution(
1649 const Eigen::VectorXd& positions) const
1650 {
1651 if (!resolution_dedup_enabled_ || training_obs.R.rows() == 0) {
1652 return false;
1653 }
1654 const double floor_d = observationResolutionFloor();
1655 return floor_d > 0.0 && nearestTrainingDistance(positions) < floor_d;
1656 }
1657
1658 [[nodiscard]] long resolutionDedupRejected() const noexcept
1659 {
1661 }
1662
1668
1671 int admitObservation(const Eigen::VectorXd& positions, double energy,
1672 const Eigen::VectorXd& gradient,
1673 optim::SecantAccounting secant_accounting =
1675 {
1676 const int existing = detail::findPositionRow(training_obs, positions);
1677 if (existing >= 0) {
1678 // The geometry is already a training row. This draw updates
1679 // that row; it is another true-force note, not a second seed.
1680 observeSecant(-1, positions, gradient, energy, secant_accounting,
1681 /*training_row=*/false);
1682 mergeRepeatedObservation(existing, energy, gradient);
1683 return existing;
1684 }
1685 // Admission at the model's own resolution. Without this the only
1686 // test is an exact position match, so a band that shifts by a
1687 // hair between outer iterations contributes a full new row every
1688 // time and the training set grows without bound -- which is what
1689 // makes the run cost grow, the kernel order being the row count
1690 // times (1 + 3 natoms).
1692 const double floor_d = observationResolutionFloor();
1693 if (floor_d > 0.0 && training_obs.R.rows() > 0 &&
1694 nearestTrainingDistance(positions) < floor_d) {
1695 // Declined rows never enter ~training_obs~, so they must
1696 // not be exempt from the replay cap.
1697 observeSecant(-1, positions, gradient, energy,
1698 secant_accounting, /*training_row=*/false);
1700 return -1;
1701 }
1702 }
1703 observeSecant(-1, positions, gradient, energy, secant_accounting,
1704 /*training_row=*/true);
1705 detail::appendObservationRow(training_obs, positions, energy, gradient);
1708 recordTrainingMutation();
1709 return static_cast<int>(training_obs.R.rows()) - 1;
1710 }
1711
1718 void appendSymmetryImage(int source_row, const Eigen::VectorXd& positions,
1719 double energy, const Eigen::VectorXd& gradient)
1720 {
1721 if (endpoint_symmetry_.empty()) return;
1722 const Eigen::VectorXd image =
1723 endpoint_symmetry_.mapPositions(positions);
1724 const Eigen::VectorXd image_gradient =
1725 endpoint_symmetry_.mapGradient(gradient);
1726 const int existing = detail::findPositionRow(training_obs, image);
1727 if (existing == source_row) {
1729 return;
1730 }
1731 if (existing >= 0) {
1732 mergeRepeatedObservation(existing, energy, image_gradient);
1733 return;
1734 }
1735 const double floor_d = observationResolutionFloor();
1736 const double nearest = nearestTrainingDistance(image);
1737 if ((floor_d > 0.0 && nearest < floor_d) ||
1738 nearest <= endpoint_symmetry_.resolution()) {
1740 return;
1741 }
1742 detail::appendObservationRow(training_obs, image, energy,
1743 image_gradient);
1746 recordTrainingMutation();
1748 }
1749
1754 {
1755 training_multiplicity.resize(static_cast<size_t>(training_obs.R.rows()),
1756 1);
1757 }
1758
1762 {
1763 recordTrainingMutation();
1764 }
1765
1767 const policy::TrainingPolicy* policy) noexcept
1768 {
1769 policy_retained_owner_ = policy;
1770 policy_retained_training_revision_ = training_revision_;
1771 }
1772
1778 {
1779 const int n = static_cast<int>(training_obs.R.rows());
1780 if (n == 0) {
1782 return false;
1783 }
1784 std::vector<Eigen::VectorXd> rows;
1785 rows.reserve(static_cast<std::size_t>(n));
1786 for (Eigen::Index row = 0; row < training_obs.R.rows(); ++row)
1787 rows.emplace_back(training_obs.R.row(row).transpose());
1788 const std::vector<int> keep =
1790 const std::vector<int> accepted =
1792 if (policy::indexListIsIdentity(accepted, n)) {
1794 return false;
1795 }
1796
1797 std::vector<int> old_to_new(static_cast<std::size_t>(n), -1);
1798 gpr::Observation next;
1799 std::vector<int> next_multiplicity;
1800 next_multiplicity.reserve(accepted.size());
1801 for (std::size_t pos = 0; pos < accepted.size(); ++pos) {
1802 const int index = accepted[pos];
1803 old_to_new[static_cast<std::size_t>(index)] = static_cast<int>(pos);
1804 const Eigen::Index row = index;
1805 const double energy =
1806 row < training_obs.E.rows() ? training_obs.E(row, 0) : 0.0;
1807 Eigen::VectorXd gradient(training_obs.R.cols());
1808 if (row < training_obs.G.rows())
1809 gradient = training_obs.G.row(row).transpose();
1810 else
1811 gradient.setZero();
1812 detail::appendObservationRow(
1813 next, training_obs.R.row(row).transpose(), energy, gradient);
1814 const int count =
1815 static_cast<std::size_t>(index) < training_multiplicity.size()
1816 ? training_multiplicity[static_cast<std::size_t>(index)]
1817 : 1;
1818 next_multiplicity.push_back(count);
1819 }
1820 if (policy::indexListIsIdentity(accepted, n)) {
1822 return false;
1823 }
1824
1825 training_obs = std::move(next);
1826 training_multiplicity = std::move(next_multiplicity);
1827 discardPrunedSecantReplay();
1828 for (auto& model: image_models)
1829 model.remapGlobalRows(old_to_new, training_obs);
1830 recordTrainingMutation();
1832 acquired_evidence_nats_ = 0.0;
1833 if (training_obs.R.rows() == 0) {
1834 gp_model_ready_ = false;
1835 kernel_requires_refit_ = true;
1836 return true;
1837 }
1838 if (initialised && gp_model_ready_) {
1839 parkActiveModelBeforeSwitch(-1);
1840 gp.invalidateTrainingFactorCache();
1842 }
1843 return true;
1844 }
1845
1848 std::vector<int> training_multiplicity;
1849
1860 bool addVirtualObservation(const Eigen::VectorXd& positions,
1861 double retire_radius)
1862 {
1863 if (!(retire_radius > 0.0) || !std::isfinite(retire_radius))
1864 return false;
1865 for (Eigen::Index r = 0; r < training_obs.R.rows(); ++r) {
1866 if ((training_obs.R.row(r).transpose() - positions).norm() <
1867 retire_radius)
1868 return false;
1869 }
1870 for (Eigen::Index r = 0; r < virtual_obs.R.rows(); ++r) {
1871 if ((virtual_obs.R.row(r).transpose() - positions).norm() <
1872 retire_radius)
1873 return false;
1874 }
1875 if (virtual_obs.R.rows() >=
1876 static_cast<Eigen::Index>(kMaxVirtualObservations)) {
1877 detail::eraseObservationRow(virtual_obs, 0);
1879 }
1880 double prior_energy = 0.0;
1881 Eigen::VectorXd prior_gradient;
1882 gp.evaluatePriorMeanTargets(positions, prior_energy, prior_gradient);
1883 detail::appendObservationRow(virtual_obs, positions, prior_energy,
1884 prior_gradient);
1885 virtual_retire_radii.push_back(retire_radius);
1887 return true;
1888 }
1889
1893 void retireVirtualObservationsNear(const Eigen::VectorXd& positions)
1894 {
1895 bool changed = false;
1896 for (Eigen::Index r = virtual_obs.R.rows() - 1; r >= 0; --r) {
1897 const double d =
1898 (virtual_obs.R.row(r).transpose() - positions).norm();
1899 if (d < virtual_retire_radii[static_cast<std::size_t>(r)]) {
1900 detail::eraseObservationRow(virtual_obs, r);
1902 static_cast<std::ptrdiff_t>(r));
1903 changed = true;
1904 }
1905 }
1906 if (changed) syncVirtualNoiseTag();
1907 }
1908
1914 {
1915 gp.getLikGaussian().setVirtualGeometryNoise(virtual_obs.R,
1917 }
1918
1923 {
1924 gpr::Observation composed = training_obs;
1925 for (Eigen::Index r = 0; r < virtual_obs.R.rows(); ++r) {
1926 detail::appendObservationRow(
1927 composed, virtual_obs.R.row(r).transpose(), virtual_obs.E(r, 0),
1928 virtual_obs.G.row(r).transpose());
1929 }
1930 return composed;
1931 }
1932
1941 void appendObservation(int image_idx, const Eigen::VectorXd& positions,
1942 double energy, const Eigen::VectorXd& gradient,
1943 ObservationRetention retention =
1945 optim::SecantAccounting secant_accounting =
1947 {
1948#ifdef USE_READCON_DB
1949 if (observation_archive_ &&
1951 (void)observation_archive_->append(positions, energy, gradient);
1952#else
1953 (void)retention;
1954#endif
1955 int global_row_index =
1956 detail::findPositionIndex(training_obs, positions);
1957 const bool appended = global_row_index < 0;
1958 // A merged draw keeps the admitting sample's image index. The new
1959 // image is a true-force note and stays under the non-training cap.
1960 observeSecant(image_idx, positions, gradient, energy, secant_accounting,
1961 /*training_row=*/appended);
1962 if (appended) {
1963 global_row_index = static_cast<int>(training_obs.R.rows());
1964 detail::appendObservationRow(training_obs, positions, energy,
1965 gradient);
1967 recordTrainingMutation();
1968 } else {
1969 mergeRepeatedObservation(global_row_index, energy, gradient);
1970 }
1971 appendSymmetryImage(global_row_index, positions, energy, gradient);
1972 (void)attachImageObservation(image_idx, global_row_index);
1973 }
1974
1977 [[nodiscard]] bool attachImageObservation(int image_idx,
1978 int global_row_index)
1979 {
1980 if (image_idx < 0 ||
1981 image_idx >= static_cast<int>(image_models.size()) ||
1982 global_row_index < 0 || global_row_index >= training_obs.R.rows())
1983 return false;
1984 image_models[image_idx].appendObservation(
1985 training_obs.R.row(global_row_index).transpose(),
1986 training_obs.E(global_row_index, 0),
1987 training_obs.G.row(global_row_index).transpose(), global_row_index);
1988 return true;
1989 }
1990
1995 int image_idx, const Eigen::VectorXd& positions, double energy,
1996 const Eigen::VectorXd& gradient,
1997 ObservationRetention retention =
1999 optim::SecantAccounting secant_accounting =
2001 {
2002 appendObservation(image_idx, positions, energy, gradient, retention,
2003 secant_accounting);
2004 if (detail::hasPosition(training_obs, positions)) {
2005 recordCurrentChainCertificate(image_idx, positions, energy,
2006 gradient);
2007 }
2008 }
2009
2011 const Eigen::VectorXd& positions)
2012 {
2013 if (image_idx < 0) return;
2014 const auto slot = static_cast<std::size_t>(image_idx);
2015 if (current_chain_certificates.size() <= slot) {
2016 current_chain_certificates.resize(slot + 1);
2017 }
2018 auto& certificate = current_chain_certificates[slot];
2019 if (certificate.image_index == image_idx &&
2020 detail::positionsCoincide(certificate.positions, positions)) {
2021 return;
2022 }
2023 certificate = IndexedObservation{};
2024 certificate.image_index = image_idx;
2025 certificate.positions = positions;
2026 certificate.certificate_row = true;
2027 }
2028
2030 const Eigen::VectorXd& positions,
2031 double energy,
2032 const Eigen::VectorXd& gradient)
2033 {
2034 recordCurrentChainCertificate(image_idx, positions);
2035 if (image_idx < 0 || !std::isfinite(energy) ||
2036 gradient.size() != positions.size() || !gradient.allFinite()) {
2037 return;
2038 }
2039 auto& certificate =
2040 current_chain_certificates[static_cast<std::size_t>(image_idx)];
2041 certificate.energy = energy;
2042 certificate.gradient = gradient;
2043 }
2044
2046 int image_idx, const Eigen::VectorXd& positions) const
2047 {
2048 if (image_idx < 0) return false;
2049 const auto slot = static_cast<std::size_t>(image_idx);
2050 if (slot >= current_chain_certificates.size()) return false;
2051 const auto& certificate = current_chain_certificates[slot];
2052 return certificate.image_index == image_idx &&
2053 detail::positionsCoincide(certificate.positions, positions);
2054 }
2055
2056 [[nodiscard]] std::optional<IndexedObservation> currentChainObservation(
2057 int image_idx, const Eigen::VectorXd& positions) const
2058 {
2059 if (!currentChainCertificateMatchesGeometry(image_idx, positions)) {
2060 return std::nullopt;
2061 }
2062 const auto& certificate =
2063 current_chain_certificates[static_cast<std::size_t>(image_idx)];
2064 if (std::isfinite(certificate.energy) &&
2065 certificate.gradient.size() == positions.size() &&
2066 certificate.gradient.allFinite()) {
2067 return certificate;
2068 }
2069 const int row = detail::findPositionIndex(training_obs, positions);
2070 if (row < 0 || row >= training_obs.E.rows() ||
2071 row >= training_obs.G.rows() || training_obs.E.cols() <= 0 ||
2072 training_obs.G.cols() != positions.size() ||
2073 !std::isfinite(training_obs.E(row, 0)) ||
2074 !training_obs.G.row(row).allFinite()) {
2075 return std::nullopt;
2076 }
2077 return IndexedObservation{image_idx, positions, training_obs.E(row, 0),
2078 training_obs.G.row(row).transpose(), true};
2079 }
2080
2081 [[nodiscard]] bool hasCurrentChainCertificate(
2082 int image_idx, const Eigen::VectorXd& positions) const
2083 {
2084 return currentChainObservation(image_idx, positions).has_value();
2085 }
2086
2110 void setImageNeighborhood(int i, const std::vector<int>& emd_indices,
2111 const Eigen::VectorXd* image_position = nullptr)
2112 {
2113 if (i < 0 || i >= static_cast<int>(image_models.size())) return;
2114 ImageModel& model = image_models[i];
2115
2116 const int n_train = static_cast<int>(training_obs.R.rows());
2117 std::vector<int> indices;
2118 indices.reserve(emd_indices.size() + model.directIndices().size());
2119 for (int src: emd_indices) {
2120 if (src >= 0 && src < n_train) indices.push_back(src);
2121 }
2122 for (int src: model.directIndices()) {
2123 if (src >= 0 && src < n_train) indices.push_back(src);
2124 }
2125 std::sort(indices.begin(), indices.end());
2126 indices.erase(std::unique(indices.begin(), indices.end()),
2127 indices.end());
2128
2129 // Position-dedup: distinct global rows can still sit at the
2130 // same configuration (a dimer burst re-oracling a stored stop
2131 // point). Keep one row per distinct geometry so the per-image
2132 // covariance stays full rank.
2133 const Eigen::Index D = training_obs.R.cols();
2134 std::vector<int> kept;
2135 kept.reserve(indices.size());
2136 for (int src: indices) {
2137 const Eigen::VectorXd pos = training_obs.R.row(src).transpose();
2138 bool dup = false;
2139 for (int k: kept) {
2140 const Eigen::VectorXd kpos = training_obs.R.row(k).transpose();
2141 if (detail::positionsCoincide(pos, kpos)) {
2142 dup = true;
2143 break;
2144 }
2145 }
2146 if (!dup) kept.push_back(src);
2147 }
2148
2149 const std::vector<uint64_t> archived =
2150 selectArchivedNeighbors(kept, image_position, D);
2151
2152 if (model.selectedIndices() == kept &&
2153 model.archivedKeys() == archived) {
2154 return;
2155 }
2156
2157 const Eigen::Index n_sel = static_cast<Eigen::Index>(kept.size());
2158 const Eigen::Index n_arch = static_cast<Eigen::Index>(archived.size());
2159 gpr::Observation neigh;
2160 if (n_sel + n_arch > 0 && D > 0) {
2161 neigh.R.resize(n_sel + n_arch, D);
2162 neigh.E.resize(n_sel + n_arch, 1);
2163 neigh.G.resize(n_sel + n_arch, D);
2164 for (Eigen::Index r = 0; r < n_sel; ++r) {
2165 const int src = kept[static_cast<size_t>(r)];
2166 neigh.R.row(r) = training_obs.R.row(src);
2167 neigh.E(r, 0) = training_obs.E(src, 0);
2168 neigh.G.row(r) = training_obs.G.row(src);
2169 }
2170#ifdef USE_READCON_DB
2171 for (Eigen::Index r = 0; r < n_arch; ++r) {
2172 const auto& row = archive_pool_[static_cast<size_t>(
2173 archived[static_cast<size_t>(r)])];
2174 neigh.R.row(n_sel + r) = row.positions.transpose();
2175 neigh.E(n_sel + r, 0) = row.energy;
2176 neigh.G.row(n_sel + r) = row.gradient.transpose();
2177 }
2178#endif
2179 }
2180 model.replaceNeighborhood(std::move(neigh), std::move(kept), archived);
2181 }
2182
2188 [[nodiscard]] std::vector<uint64_t> selectArchivedNeighbors(
2189 const std::vector<int>& kept, const Eigen::VectorXd* image_position,
2190 Eigen::Index D)
2191 {
2192 std::vector<uint64_t> archived;
2193#ifdef USE_READCON_DB
2194 if (!observation_archive_ || !image_position ||
2195 image_position->size() != D || D <= 0) {
2196 return archived;
2197 }
2198 refreshArchivePool();
2199 if (archive_pool_.empty()) return archived;
2200
2201 aux::Distance distance;
2202 gpr::Coord query(1, D);
2203 for (Eigen::Index c = 0; c < D; ++c) {
2204 query(0, c) = (*image_position)(c);
2205 }
2206
2207 double radius = std::numeric_limits<double>::infinity();
2208 if (!kept.empty()) {
2209 gpr::Coord kept_r(static_cast<Eigen::Index>(kept.size()), D);
2210 for (Eigen::Index r = 0; r < static_cast<Eigen::Index>(kept.size());
2211 ++r) {
2212 kept_r.row(r) =
2213 training_obs.R.row(kept[static_cast<size_t>(r)]);
2214 }
2215 gpr::FieldMatrixd kept_dist;
2216 distance.dist_emd(query, kept_r, atoms_config, kept_dist);
2217 radius = kept_dist.maxCoeff();
2218 }
2219
2220 gpr::Coord pool_r(static_cast<Eigen::Index>(archive_pool_.size()), D);
2221 for (Eigen::Index r = 0;
2222 r < static_cast<Eigen::Index>(archive_pool_.size()); ++r) {
2223 if (archive_pool_[static_cast<size_t>(r)].positions.size() != D) {
2224 return archived; // composition mismatch: archive unusable
2225 }
2226 pool_r.row(r) =
2227 archive_pool_[static_cast<size_t>(r)].positions.transpose();
2228 }
2229 gpr::FieldMatrixd pool_dist;
2230 distance.dist_emd(query, pool_r, atoms_config, pool_dist);
2231
2232 std::vector<uint64_t> order(archive_pool_.size());
2233 for (size_t k = 0; k < order.size(); ++k)
2234 order[k] = k;
2235 std::sort(order.begin(), order.end(), [&](uint64_t a, uint64_t b) {
2236 return pool_dist(static_cast<Eigen::Index>(a)) <
2237 pool_dist(static_cast<Eigen::Index>(b));
2238 });
2239
2240 const int n_train = static_cast<int>(training_obs.R.rows());
2241 for (const uint64_t k: order) {
2242 if (static_cast<int>(archived.size()) >= per_image_knn) break;
2243 const double d = pool_dist(static_cast<Eigen::Index>(k));
2244 if (!std::isfinite(d) || d > radius) break;
2245 const Eigen::VectorXd& pos =
2246 archive_pool_[static_cast<size_t>(k)].positions;
2247 bool active = false;
2248 for (int src = 0; src < n_train; ++src) {
2249 const Eigen::VectorXd row = training_obs.R.row(src).transpose();
2250 if (detail::positionsCoincide(pos, row)) {
2251 active = true;
2252 break;
2253 }
2254 }
2255 if (active) continue;
2256 bool dup = false;
2257 for (const uint64_t chosen: archived) {
2258 if (detail::positionsCoincide(
2259 pos,
2260 archive_pool_[static_cast<size_t>(chosen)].positions)) {
2261 dup = true;
2262 break;
2263 }
2264 }
2265 if (!dup) archived.push_back(k);
2266 }
2267 std::sort(archived.begin(), archived.end());
2268#else
2269 (void)kept;
2270 (void)image_position;
2271 (void)D;
2272#endif
2273 return archived;
2274 }
2275
2276#ifdef USE_READCON_DB
2280 void refreshArchivePool()
2281 {
2282 if (!observation_archive_) return;
2283 const uint64_t size = observation_archive_->size();
2284 if (size == archive_pool_snapshot_) return;
2285 archive_pool_ = observation_archive_->fetchFrom(archive_first_row_);
2286 archive_pool_snapshot_ = size;
2287 }
2288#endif
2289
2295 int i,
2296 std::shared_ptr<const gpr::geometry::InternalCoordinateChart> chart)
2297 {
2298 if (i < 0 || i >= static_cast<int>(image_models.size()) || !chart) {
2299 return false;
2300 }
2301 const std::optional<double> length_scale =
2302 gp.inferInternalCoordinateLengthScale(*chart);
2303 if (!length_scale) {
2304 image_models[i].clearInternalCoordinateChart();
2305 return false;
2306 }
2307 image_models[i].setInternalCoordinateChart(std::move(chart),
2308 *length_scale);
2309 return true;
2310 }
2311
2317 std::shared_ptr<const gpr::geometry::InternalCoordinateChart> chart)
2318 {
2319 if (!chart || !chart->valid()) {
2321 return false;
2322 }
2323 if (global_internal_coordinate_chart_ == chart &&
2324 gp.getSexpAtCovarianceFunction().manifoldChart() == chart) {
2325 return true;
2326 }
2327 const std::optional<double> length_scale =
2328 gp.inferInternalCoordinateLengthScale(*chart);
2329 if (!length_scale) {
2331 return false;
2332 }
2333 kernel_requires_refit_ = true;
2334 global_internal_coordinate_chart_ = std::move(chart);
2335 global_internal_coordinate_length_scale_ = *length_scale;
2336 parkActiveModelBeforeSwitch(-1);
2337 gp.setInternalCoordinateChart(global_internal_coordinate_chart_,
2338 global_internal_coordinate_length_scale_);
2339 if (training_obs.R.rows() > 0) {
2340 materializeWithNoiseFloor(gp, training_obs,
2341 likelihoodNoiseFloorSigma2());
2342 conditioned_training_revision_ = training_revision_;
2343 }
2344 ++global_surrogate_revision_;
2345 markActiveModel(-1);
2346 return true;
2347 }
2348
2350 {
2351 const bool had_chart =
2352 static_cast<bool>(global_internal_coordinate_chart_);
2353 bool gp_uses_chart = false;
2354 if (initialised) {
2355 gp_uses_chart =
2356 gp.getSexpAtCovarianceFunction().usesManifoldChart();
2357 if (gp_uses_chart) {
2358 gp.getSexpAtCovarianceFunction().clearManifoldChart();
2359 }
2360 }
2361 global_internal_coordinate_chart_.reset();
2362 global_internal_coordinate_length_scale_ =
2363 std::numeric_limits<double>::quiet_NaN();
2364 if (had_chart || gp_uses_chart) {
2365 kernel_requires_refit_ = true;
2366 if (initialised && training_obs.R.rows() > 0) {
2367 materializeWithNoiseFloor(gp, training_obs,
2368 likelihoodNoiseFloorSigma2());
2369 }
2370 ++global_surrogate_revision_;
2371 }
2372 }
2373
2374 [[nodiscard]] const std::shared_ptr<
2377 {
2378 return global_internal_coordinate_chart_;
2379 }
2380
2381 [[nodiscard]] double globalInternalCoordinateLengthScale() const noexcept
2382 {
2383 return global_internal_coordinate_length_scale_;
2384 }
2385
2392 bool setBandGeodesicReferencePath(const gpr::Coord& reference_path)
2393 {
2394 if (gp.atomicEnvironmentModelEnabled()) return false;
2395 if (reference_path.rows() <= 0 || reference_path.cols() <= 0 ||
2396 !reference_path.allFinite()) {
2397 return false;
2398 }
2399 if (atoms_config.positions.cols() > 0 &&
2400 reference_path.cols() != atoms_config.positions.cols()) {
2401 return false;
2402 }
2403 setGlobalGeodesicReferencePath(reference_path);
2404 return true;
2405 }
2406
2410 bool setImageGeodesicReferencePath(int i, const gpr::Coord& reference_path)
2411 {
2412 if (gp.atomicEnvironmentModelEnabled()) return false;
2413 if (i < 0 || i >= static_cast<int>(image_models.size()) ||
2414 reference_path.rows() <= 0 || reference_path.cols() <= 0 ||
2415 !reference_path.allFinite()) {
2416 return false;
2417 }
2418 if (atoms_config.positions.cols() > 0 &&
2419 reference_path.cols() != atoms_config.positions.cols()) {
2420 return false;
2421 }
2422 setGlobalGeodesicReferencePath(reference_path);
2423 image_models[i].setGeodesicReferencePath(reference_path);
2424 return true;
2425 }
2426
2432 bool refitImageGP(int i)
2433 {
2434 if (gp.atomicEnvironmentModelEnabled()) return false;
2435 if (i < 0 || i >= static_cast<int>(image_models.size())) return false;
2436 ImageModel& model = image_models[i];
2437 gpr::GaussianProcessRegression* local_gp = model.gp();
2438 if (!local_gp) return false;
2439 const gpr::Observation& local_obs = model.observations();
2440 if (local_obs.R.rows() == 0) return false;
2442 shared_posterior;
2443 if (sharesGlobalHyperparameters(*local_gp)) {
2445 shared_posterior = gp.retainHyperparameterPosterior();
2446 if (shared_posterior.empty()) return false;
2447 }
2448 // No per-image SCG. The local set is a geometric
2449 // neighbourhood of an image that may have been oracled many
2450 // times at nearly the same geometry, so it carries
2451 // near-duplicate rows. A per-image hyperparameter search on
2452 // that ill-conditioned covariance drives theta_i to extremes
2453 // and the per-image variance blows up -- the chain barrier
2454 // then runs away. The local GP instead inherits the global
2455 // MAP theta and only conditions on its local rows. Integrated
2456 // uncertainty uses the global weights without counting this
2457 // subset's likelihood a second time.
2458 const Eigen::VectorXd theta_global = gp.packInlaHyperparameters();
2459 const auto shared_state = sharedParameterState();
2460 const double noise_floor_sigma2 = likelihoodNoiseFloorSigma2();
2461 parkActiveModelBeforeSwitch(i);
2462 local_gp->restoreLengthScaleFitState(shared_state.length_scales);
2463 local_gp->setHyperparameters(local_obs, atoms_config, true, true, true);
2465 auto& local_covariance = local_gp->getSexpAtCovarianceFunction();
2466 const auto& global_covariance = gp.getSexpAtCovarianceFunction();
2467 local_covariance.getAtomisticLengthScaleRef() =
2468 global_covariance.getAtomisticLengthScaleRef();
2469 local_covariance.setMagnSigma2(global_covariance.getMagnSigma2());
2471 gp.getConstantCovarianceFunction().getConstSigma2());
2472 if (model.internalCoordinateChart()) {
2476 }
2477 // Pack this model's parameter domain: the global pair metric can
2478 // have several lengths while a local chart has exactly one.
2479 Eigen::VectorXd local_parameters = local_covariance.combineParameters();
2480 if (theta_global.size() >
2481 global_covariance.getLengthScaleRef().size() + 1) {
2482 const Eigen::Index count = local_parameters.size();
2483 local_parameters.conservativeResize(count + 1);
2484 local_parameters(count) = std::log(gp.likelihoodNoiseVariance());
2485 }
2486 local_gp->setParameters(local_parameters);
2487 // Fixed likelihood noise belongs to the shared model even when its
2488 // variance is absent from the optimized parameter vector.
2489 (void)local_gp->setLikelihoodNoiseVariance(
2490 gp.outputScale() * gp.outputScale() * gp.likelihoodNoiseVariance());
2491 if (model.hasGeodesicReferencePath()) {
2492 (void)local_gp->applyLikelihoodNoiseVarianceFloor(
2493 noise_floor_sigma2, local_obs);
2494 (void)local_gp->fitGeodesicHeatPrior(model.geodesicReferencePath(),
2495 local_obs);
2496 } else {
2497 materializeWithNoiseFloor(*local_gp, local_obs, noise_floor_sigma2);
2498 }
2500 if (!local_gp->activateMaterializedPosterior()) return false;
2501 if (!shared_posterior.empty() &&
2502 !local_gp->conditionOnHyperparameterPosterior(shared_posterior))
2503 return false;
2504 model.recordMaterialized(theta_global, noise_floor_sigma2,
2505 shared_state);
2506 markActiveModel(i);
2507 return true;
2508 }
2509
2516 {
2517 if (training_obs.R.rows() == 0) return;
2518 // Factor ownership does not identify the observations it conditions.
2519 // Appended or corrected canonical rows change the shared posterior
2520 // even while theta and the process-wide factor owner remain fixed.
2521 if (gp_model_ready_ &&
2522 conditioned_training_revision_ != training_revision_) {
2524 return;
2525 }
2526 const double noise_floor_sigma2 = likelihoodNoiseFloorSigma2();
2527 if (activeModelIs(-1)) {
2528 (void)gp.applyLikelihoodNoiseVarianceFloor(noise_floor_sigma2,
2529 training_obs);
2530 if (!gp.activateMaterializedPosterior()) {
2531 materializeWithNoiseFloor(gp, training_obs, noise_floor_sigma2);
2532 }
2533 markActiveModel(-1);
2534 return;
2535 }
2536 parkActiveModelBeforeSwitch(-1);
2537 if (!gp.applyLikelihoodNoiseVarianceFloor(noise_floor_sigma2,
2538 training_obs) &&
2539 gp.activateMaterializedPosterior()) {
2540 markActiveModel(-1);
2541 return;
2542 }
2543 materializeWithNoiseFloor(gp, training_obs, noise_floor_sigma2);
2544 markActiveModel(-1);
2545 }
2546
2551 [[nodiscard]] bool ensureSingletonForImage(int i)
2552 {
2553 if (gp.atomicEnvironmentModelEnabled()) return false;
2554 if (i < 0 || i >= static_cast<int>(image_models.size())) return false;
2555 ImageModel& model = image_models[i];
2556 gpr::GaussianProcessRegression* local_gp = model.gp();
2557 if (!local_gp) return false;
2558 const gpr::Observation& local_obs = model.observations();
2559 if (local_obs.R.rows() == 0) return false;
2560 const Eigen::VectorXd theta_global = gp.packInlaHyperparameters();
2561 const double noise_floor_sigma2 = likelihoodNoiseFloorSigma2();
2562 if (model.materializedFor(theta_global, noise_floor_sigma2,
2564 if (activeModelIs(i)) {
2565 if (!local_gp->activateMaterializedPosterior()) {
2566 if (sharesGlobalHyperparameters(*local_gp))
2567 return refitImageGP(i);
2568 local_gp->updateModelWithFullData(local_obs);
2570 if (!local_gp->activateMaterializedPosterior()) {
2571 return false;
2572 }
2573 markActiveModel(i);
2574 }
2575 return true;
2576 }
2577 parkActiveModelBeforeSwitch(i);
2578 if (local_gp->activateMaterializedPosterior()) {
2579 markActiveModel(i);
2580 return true;
2581 }
2582 if (sharesGlobalHyperparameters(*local_gp)) return refitImageGP(i);
2583 local_gp->updateModelWithFullData(local_obs);
2585 if (!local_gp->activateMaterializedPosterior()) return false;
2586 markActiveModel(i);
2587 return true;
2588 }
2589 return refitImageGP(i);
2590 }
2591
2592 void markModelMaterialized(int owner, const Eigen::VectorXd& theta,
2593 const SharedParameterState& shared_state)
2594 {
2595 const double noise_floor_sigma2 = likelihoodNoiseFloorSigma2();
2596 if (owner >= 0 && owner < static_cast<int>(image_models.size())) {
2597 ImageModel& model = image_models[owner];
2598 if (model.gp() && model.observations().R.rows() > 0) {
2600 noise_floor_sigma2, model.observations());
2601 }
2602 model.recordMaterialized(theta, noise_floor_sigma2, shared_state);
2603 } else if (owner < 0 && training_obs.R.rows() > 0) {
2604 (void)gp.applyLikelihoodNoiseVarianceFloor(noise_floor_sigma2,
2605 training_obs);
2606 conditioned_training_revision_ = training_revision_;
2607 }
2608 markActiveModel(owner);
2609 }
2610
2615 public:
2617 : session_(&session), owner_(owner)
2618 {
2619 if (owner_ < 0) {
2620 session_->ensureSingletonForGlobal();
2621 gp_ = &session_->gp;
2622 observations_ = &session_->training_obs;
2623 return;
2624 }
2625 if (!session_->ensureSingletonForImage(owner_)) {
2626 owner_ = -1;
2627 session_->ensureSingletonForGlobal();
2628 gp_ = &session_->gp;
2629 observations_ = &session_->training_obs;
2630 return;
2631 }
2632 ImageModel& model = session_->image_models[owner_];
2633 gp_ = model.gp();
2634 observations_ = &model.observations();
2635 }
2636
2637 ModelLease(const ModelLease&) = delete;
2641
2642 [[nodiscard]] gpr::GaussianProcessRegression& gp() const
2643 {
2644 return *gp_;
2645 }
2646
2647 [[nodiscard]] const gpr::Observation& observations() const
2648 {
2649 return *observations_;
2650 }
2651
2652 [[nodiscard]] int owner() const
2653 {
2654 return owner_;
2655 }
2656
2658 public:
2660 : lease_(&lease),
2661 theta_(lease.gp().packInlaHyperparameters()),
2662 atomic_parameters_(
2663 lease.gp().atomicEnvironmentParameterState()),
2664 global_theta_(lease.session_->gp.packInlaHyperparameters()),
2665 fit_state_(lease.gp().lengthScaleFitState()),
2666 global_shared_state_(lease.session_->sharedParameterState()),
2667 global_training_revision_(lease.session_->trainingRevision()),
2668 output_mean_(lease.gp().outputMean()),
2669 output_scale_(lease.gp().outputScale()),
2670 output_mean_frozen_(lease.gp().outputMeanFrozen()),
2671 hyperparameter_posterior_(
2672 lease.gp().retainHyperparameterPosterior()),
2673 active_posterior_(lease.gp().retainActivePosterior()),
2674 secant_quadratic_prior_(
2675 lease.gp().retainSecantQuadraticPrior())
2676 {
2677 if (theta_.size() > 0) {
2678 physical_noise_ = output_scale_ * output_scale_ *
2679 lease.gp().likelihoodNoiseVariance();
2680 constant_variance_ = lease.gp()
2681 .getConstantCovarianceFunction()
2682 .getConstSigma2();
2683 heat_kernel_ = lease.gp()
2684 .getSexpAtCovarianceFunction()
2685 .geodesicHeatKernel();
2686 }
2687 }
2688
2691 delete;
2694 delete;
2695
2697 {
2698 try {
2699 restore();
2700 } catch (...) {
2701 std::terminate();
2702 }
2703 }
2704
2705 void restore()
2706 {
2707 if (!lease_) return;
2708 if (lease_->observations().R.rows() > 0) {
2709 // Kernel amplitudes and likelihood noise share the
2710 // output coordinates of the fitted model. Fixed kernel
2711 // components are absent from the optimized theta vector.
2712 if (theta_.size() > 0) {
2713 auto& gp = lease_->gp();
2714 gp.restoreLengthScaleFitState(fit_state_);
2715 gp.restoreOutputTransform(output_mean_, output_scale_,
2716 output_mean_frozen_);
2717 gp.setParameters(theta_);
2718 (void)gp.setLikelihoodNoiseVariance(physical_noise_);
2719 gp.getConstantCovarianceFunction().setConstSigma2(
2720 constant_variance_);
2721 gp.getSexpAtCovarianceFunction().setGeodesicHeatKernel(
2722 heat_kernel_);
2723 }
2724 lease_->gp().restoreAtomicEnvironmentParameterState(
2725 atomic_parameters_);
2726 lease_->gp().restoreSecantQuadraticPrior(
2727 secant_quadratic_prior_);
2728 if (!lease_->gp().restoreActivePosterior(
2729 active_posterior_, lease_->observations())) {
2730 lease_->gp().updateModelWithFullData(
2731 lease_->observations());
2732 }
2733 // A local model restores the parameter domain it entered
2734 // with. A global refit makes that local model stale.
2735 lease_->session_->markModelMaterialized(
2736 lease_->owner_, global_theta_, global_shared_state_);
2737 if (!hyperparameter_posterior_.empty() &&
2738 (lease_->owner_ >= 0 ||
2739 lease_->session_->trainingRevision() ==
2740 global_training_revision_) &&
2741 !lease_->gp().conditionOnHyperparameterPosterior(
2742 hyperparameter_posterior_)) {
2743 throw std::logic_error(
2744 "Image handback changes the shared parameter "
2745 "domain");
2746 }
2747 }
2748 lease_ = nullptr;
2749 }
2750
2751 private:
2752 ModelLease* lease_;
2753 Eigen::VectorXd theta_;
2755 atomic_parameters_;
2756 Eigen::VectorXd global_theta_;
2758 SharedParameterState global_shared_state_;
2759 std::uint64_t global_training_revision_;
2760 double output_mean_;
2761 double output_scale_;
2762 bool output_mean_frozen_;
2763 double physical_noise_ = 0.0;
2764 double constant_variance_ = 0.0;
2765 std::shared_ptr<const gpr::GeodesicHeatEnergyForceKernel>
2766 heat_kernel_;
2768 hyperparameter_posterior_;
2770 active_posterior_;
2772 secant_quadratic_prior_;
2773 };
2774
2776 {
2777 return ScopedParameterRestore(*this);
2778 }
2779
2780 private:
2781 ActiveLearningSession* session_;
2782 int owner_;
2783 gpr::GaussianProcessRegression* gp_ = nullptr;
2784 const gpr::Observation* observations_ = nullptr;
2785 };
2786
2788 {
2789 return ModelLease(*this, -1);
2790 }
2791
2792 [[nodiscard]] ModelLease acquireImageModel(int i)
2793 {
2794 return ModelLease(*this, i);
2795 }
2796
2797 [[nodiscard]] bool imageModelEligibleForPrediction(int i) const
2798 {
2799 return !gp.atomicEnvironmentModelEnabled() && i >= 0 &&
2800 i < static_cast<int>(image_models.size()) &&
2801 image_models[i].gp() &&
2802 image_models[i].hasEnoughRows(min_per_image_n_train);
2803 }
2804
2811 {
2813 gp.calculatePotentialDispatched(probe);
2814 });
2815 }
2816
2820 {
2822 gp.calculateVarianceDispatched(probe);
2823 });
2824 }
2825
2835 template <typename Use>
2836 void withImageChartFallback(int i, Use&& use)
2837 {
2839 withImageModel(i, std::forward<Use>(use));
2840 return;
2841 }
2842 auto model = acquireGlobalModel();
2843 use(model.gp());
2844 }
2845
2848 template <typename Use>
2849 void withImageModel(int i, Use&& use)
2850 {
2851 try {
2852 auto model = acquireImageModel(i);
2853 use(model.gp());
2854 return;
2856 if (!image_models[i].internalCoordinateChart()) throw;
2857 image_models[i].clearInternalCoordinateChart();
2858 }
2859 auto model = acquireImageModel(i);
2860 use(model.gp());
2861 }
2862
2865 void compactAfterRowRemoval(int removed_row)
2866 {
2867 for (auto& model: image_models) {
2868 model.compactAfterRowRemoval(removed_row);
2869 }
2870 }
2871
2874 bool rollbackTrainingObservations(Eigen::Index row_count)
2875 {
2876 if (row_count < 0) return false;
2877 const Eigen::Index current = training_obs.R.rows();
2878 if (row_count >= current) return false;
2879 for (Eigen::Index r = current; r > row_count; --r) {
2880 compactAfterRowRemoval(static_cast<int>(r - 1));
2881 }
2882 training_obs.R.conservativeResize(row_count, training_obs.R.cols());
2883 training_obs.E.conservativeResize(row_count, training_obs.E.cols());
2884 training_obs.G.conservativeResize(row_count, training_obs.G.cols());
2885 if (training_multiplicity.size() > static_cast<size_t>(row_count)) {
2886 training_multiplicity.resize(static_cast<size_t>(row_count));
2887 }
2888 discardPrunedSecantReplay();
2889 gp_model_ready_ = false;
2890 recordTrainingMutation();
2891 markActiveModel(-1);
2892 return true;
2893 }
2894
2896 const std::vector<IndexedObservation>& observations)
2897 {
2898 for (const auto& observation: observations) {
2899 appendObservation(observation.image_index, observation.positions,
2900 observation.energy, observation.gradient);
2901 }
2902 if (!observations.empty()) refreshCovarianceCache();
2903 }
2904
2906 Eigen::Index row_count,
2907 const std::vector<IndexedObservation>& retained_observations)
2908 {
2909 const bool rolled_back = rollbackTrainingObservations(row_count);
2910 if (!retained_observations.empty()) {
2911 appendIndexedObservations(retained_observations);
2912 } else if (rolled_back) {
2914 }
2915 return rolled_back;
2916 }
2917
2936 {
2937 return pruneLeastInfluentialRow(band_positions, /*ignore_noise=*/false);
2938 }
2939
2961 Eigen::Index max_rows)
2962 {
2963 if (!initialised || max_rows <= 0) return 0;
2964 int removed = 0;
2965 while (training_obs.R.rows() > max_rows) {
2966 const int dropped = pruneLeastInfluentialRow(band_positions,
2967 /*ignore_noise=*/true);
2968 if (dropped == 0) break; // floor reached, or no influence
2969 removed += dropped;
2970 }
2971 if (removed > 0) recordTrainingMutation();
2972 return removed;
2973 }
2974
2979 int pruneLeastInfluentialRow(const gpr::Coord& band_positions,
2980 bool ignore_noise)
2981 {
2982 if (!initialised || training_obs.R.rows() == 0) return 0;
2983 // Keep enough rows that the posterior stays determined; the
2984 // floor is the joint block size, not a tuning knob.
2985 const Eigen::Index min_rows = 4;
2986 if (training_obs.R.rows() <= min_rows) return 0;
2987
2988 // Influence belongs to the retained observations, including acquired
2989 // rows. Activate their distributed factor so pruning can stream its
2990 // solves without replicating a full covariance on every rank.
2992 // Rows the band stands on are the support of the region it may
2993 // relax in: an image may step only while it stays within one
2994 // kernel correlation length of some training row (the ARD metric
2995 // r^2 = sum ((1/r_ij - 1/r_ij')/l_ij)^2, r <= 1). Every row within
2996 // that length of a current band image is kept; pruning it shrank
2997 // the support the next step needs, and a point acquired past the
2998 // boundary was dropped in the same outer (irc 11_trans_butadiene
2999 // ocineb: one call per outer for 999 outers).
3000 std::vector<char> protected_row(
3001 static_cast<std::size_t>(training_obs.R.rows()), 0);
3002 if (band_positions.rows() > 0 &&
3003 band_positions.cols() == training_obs.R.cols()) {
3004 gpr::FieldMatrixd kernel_distance_matrix;
3005 gp.getSexpAtCovarianceFunction().correlationDistances(
3006 band_positions, training_obs.R, atoms_config,
3007 kernel_distance_matrix);
3008 for (Eigen::Index b = 0; b < kernel_distance_matrix.rows(); ++b) {
3009 for (Eigen::Index r = 0; r < kernel_distance_matrix.cols();
3010 ++r) {
3011 const double d = kernel_distance_matrix(b, r);
3012 if (std::isfinite(d) && d <= 1.0 &&
3013 r < static_cast<Eigen::Index>(protected_row.size())) {
3014 protected_row[static_cast<std::size_t>(r)] = 1;
3015 }
3016 }
3017 }
3018 }
3019 const Eigen::Index recent =
3020 std::min(band_positions.rows(), training_obs.R.rows());
3021 for (Eigen::Index r = training_obs.R.rows() - recent;
3022 r < training_obs.R.rows(); ++r)
3023 protected_row[static_cast<std::size_t>(r)] = 1;
3024 Eigen::VectorXd influence;
3025 if (!gp.observationBandInfluence(training_obs, band_positions,
3026 influence, /*collective=*/true,
3027 protected_row)) {
3028 return 0;
3029 }
3030 if (influence.size() != training_obs.R.rows()) return 0;
3031 const double noise_sigma =
3032 std::sqrt(std::max(gp.getLikGaussian().getSigma2(), 0.0));
3033 if (!(noise_sigma > 0.0) || !std::isfinite(noise_sigma)) return 0;
3034
3035 // The single-row downdate behind the influence score is exact for
3036 // ONE deletion: removing a row changes every remaining row's
3037 // influence (a near-duplicate of a deleted row becomes essential),
3038 // so batch deletion against a stale influence vector collapses
3039 // correlated groups. Remove only the minimum-influence row per
3040 // prune event; the cadence gate in the caller bounds the rate.
3041 int pruned = 0;
3042 Eigen::Index r_min = -1;
3043 double v_min = std::numeric_limits<double>::infinity();
3044 for (Eigen::Index r = 0; r < influence.size(); ++r) {
3045 if (protected_row[static_cast<std::size_t>(r)]) continue;
3046 if (influence(r) < v_min) {
3047 v_min = influence(r);
3048 r_min = r;
3049 }
3050 }
3051 if (r_min >= 0 && (ignore_noise || v_min < noise_sigma)) {
3052 detail::eraseObservationRow(training_obs, r_min);
3053 if (static_cast<size_t>(r_min) < training_multiplicity.size()) {
3055 r_min);
3056 }
3057 for (auto& model: image_models) {
3058 model.compactAfterRowRemoval(static_cast<int>(r_min));
3059 }
3060 ++pruned;
3061 }
3062 if (pruned > 0) {
3063 discardPrunedSecantReplay();
3064 recordTrainingMutation();
3065 // Row removal changes the design, not the evidence for theta:
3066 // rebuild the posterior on the surviving rows at the CURRENT
3067 // hyperparameters. Running SCG here would also break the
3068 // acquisition bootstrap, which relies on the outer-0
3069 // activation seeing the unfitted prior variance.
3070 parkActiveModelBeforeSwitch(-1);
3071 if (virtual_obs.R.rows() > 0) {
3072 materializeWithNoiseFloor(gp, composedTrainingObs(),
3073 likelihoodNoiseFloorSigma2());
3074 } else {
3075 materializeWithNoiseFloor(gp, training_obs,
3076 likelihoodNoiseFloorSigma2());
3077 }
3078 conditioned_training_revision_ = training_revision_;
3079 markActiveModel(-1);
3080 }
3081 return pruned;
3082 }
3083
3089 int pruneImageModelsAdaptive(const gpr::Coord& band_positions)
3090 {
3091 if (!initialised) return 0;
3092 int pruned = 0;
3093 const Eigen::Index rows = band_positions.rows();
3094 for (std::size_t i = 0; i < image_models.size(); ++i) {
3095 if (static_cast<Eigen::Index>(i) >= rows) break;
3096 auto& model = image_models[i];
3097 if (!model.gp()) continue;
3098 const Eigen::VectorXd point =
3099 band_positions.row(static_cast<Eigen::Index>(i)).transpose();
3100 pruned += model.pruneAdaptiveAtPoint(point);
3101 }
3102 return pruned;
3103 }
3104
3111 bool refitGP(bool reinit_seeds)
3112 {
3113 syncSecantQuadraticPrior();
3114 bool pruned_now = false;
3115 if (policy_context_ != nullptr && policy_context_->policy != nullptr &&
3116 (policy_retained_owner_ != policy_context_->policy ||
3117 policy_retained_training_revision_ != training_revision_)) {
3118 pruned_now = retainTrainingRowsForPolicy(*policy_context_->policy);
3119 }
3120 if (policy_context_ != nullptr && policy_context_->policy != nullptr) {
3121 policy::SearchState state;
3122 state.kind = policy_context_->kind;
3123 state.iteration = policy_context_->iteration;
3124 state.oracle_calls = policy_context_->oracle_calls;
3125 state.training_size = static_cast<int>(training_obs.R.rows());
3126 state.hyperparameter_refits =
3127 policy_context_->hyperparameter_refits;
3128 state.engine_would_retrain = true;
3129 state.engine_would_rebuild_factor = true;
3130 state.gp = &gp;
3131 const policy::TrainingPolicy* policy = policy_context_->policy;
3133 state)) {
3134 const bool rebuild =
3136 gp.clearModeRefitHint();
3137 if (!initialised) initialise();
3138 if (!rebuild && gp_model_ready_ &&
3139 gp.trainingFactorAppendable(training_obs.R.rows())) {
3140 parkActiveModelBeforeSwitch(-1);
3141 gp.updateModelWithFullData(virtual_obs.R.rows() > 0
3143 : training_obs);
3144 conditioned_training_revision_ = training_revision_;
3145 markActiveModel(-1);
3146 } else if (!pruned_now || !gp_model_ready_) {
3147 if (rebuild && gp_model_ready_) {
3148 parkActiveModelBeforeSwitch(-1);
3149 gp.invalidateTrainingFactorCache();
3150 }
3152 } else if (rebuild && gp_model_ready_) {
3153 // retainTrainingRowsForPolicy already invalidated and
3154 // rebuilt the factor on the pruned rows.
3155 }
3156 fitted_training_revision_ = training_revision_;
3157 conditioned_training_revision_ = training_revision_;
3158 kernel_requires_refit_ = false;
3159 gp_model_ready_ = training_obs.R.rows() > 0;
3160 return false;
3161 }
3162 }
3163 if (!initialised) initialise();
3164 parkActiveModelBeforeSwitch(-1);
3165 // Coordinate updates retain the other component in the likelihood.
3166 // The heat amplitude is re-estimated on the supplied path after the
3167 // base parameters have been optimized.
3168 if (global_geodesic_reference_path_.size() == 0)
3169 gp.clearGeodesicHeatPrior();
3170 if (global_internal_coordinate_chart_) {
3171 gp.setInternalCoordinateChart(
3172 global_internal_coordinate_chart_,
3173 global_internal_coordinate_length_scale_);
3174 }
3175 gp.setHyperparameters(training_obs, atoms_config, reinit_seeds,
3176 reinit_seeds, reinit_seeds);
3177 const double noise_floor_sigma2 = likelihoodNoiseFloorSigma2();
3178 (void)gp.applyLikelihoodNoiseVarianceFloor(noise_floor_sigma2,
3179 training_obs);
3180 if (!gp.atomicEnvironmentModelEnabled() &&
3181 global_internal_coordinate_chart_) {
3182 // The charted likelihood uses its analytic parameter gradient.
3183 // The pair-distance stationarity shortcut does not represent
3184 // this covariance and cannot certify its parameter fit.
3185 gp.optimize(training_obs);
3186 (void)gp.applyLikelihoodNoiseVarianceFloor(noise_floor_sigma2,
3187 training_obs);
3188 materializeWithNoiseFloor(gp, training_obs, noise_floor_sigma2);
3189 } else {
3190 // The objective's stationarity test runs first: a stationary
3191 // optimum holds theta, a moved one takes its Newton step at one
3192 // evaluation, and the optimizer runs only when neither applies.
3193 // Per-append SCG at 30 evaluations was the wall of every slow
3194 // cell (Birkholz 11_grignard: 394 s of a 448 s outer).
3195 const bool held_or_stepped =
3196 !reinit_seeds &&
3197 gp.refreshFullDataPosteriorIfObjectiveStationary(training_obs);
3198 if (!held_or_stepped) gp.optimize(training_obs);
3199 (void)gp.applyLikelihoodNoiseVarianceFloor(noise_floor_sigma2,
3200 training_obs);
3201 }
3202 if (!gp.atomicEnvironmentModelEnabled() &&
3203 global_internal_coordinate_chart_) {
3204 global_internal_coordinate_length_scale_ =
3205 gp.getSexpAtCovarianceFunction().getLengthScaleRef()(0, 0);
3206 }
3207 if (!gp.atomicEnvironmentModelEnabled() &&
3208 global_geodesic_reference_path_.size() > 0) {
3209 (void)gp.fitGeodesicHeatPrior(global_geodesic_reference_path_,
3210 training_obs);
3211 }
3212 if (virtual_obs.R.rows() > 0) {
3213 materializeWithNoiseFloor(gp, composedTrainingObs(),
3214 likelihoodNoiseFloorSigma2());
3215 }
3216 gp_model_ready_ = true;
3217 fitted_training_revision_ = training_revision_;
3218 conditioned_training_revision_ = training_revision_;
3219 kernel_requires_refit_ = false;
3220 acquired_evidence_nats_ = 0.0;
3221 markActiveModel(-1);
3222 return true;
3223 }
3224
3229 public:
3233 {
3234 if (session == nullptr || policy == nullptr) return;
3235 session_ = session;
3236 previous_ = std::move(session_->policy_context_);
3237 auto ctx = std::make_shared<policy::PolicyContext>();
3238 ctx->policy = policy;
3239 ctx->kind = kind;
3240 session_->policy_context_ = std::move(ctx);
3241 }
3242
3243 ~PolicyScope() noexcept
3244 {
3245 if (session_ != nullptr) {
3246 session_->policy_context_ = std::move(previous_);
3247 }
3248 }
3249
3250 PolicyScope(const PolicyScope&) = delete;
3252
3253 PolicyScope(PolicyScope&& other) noexcept
3254 : session_(other.session_), previous_(std::move(other.previous_))
3255 {
3256 other.session_ = nullptr;
3257 }
3258
3260
3261 void publishProgress(int iteration, int oracle_calls, int refits,
3262 int training_size) noexcept
3263 {
3264 if (session_ != nullptr) {
3265 session_->publishPolicyProgress(iteration, oracle_calls, refits,
3266 training_size);
3267 }
3268 }
3269
3270 private:
3271 ActiveLearningSession* session_ = nullptr;
3272 std::shared_ptr<policy::PolicyContext> previous_;
3273 };
3274
3276 const noexcept
3277 {
3278 return policy_context_.get();
3279 }
3280
3281 void publishPolicyProgress(int iteration, int oracle_calls, int refits,
3282 int training_size) noexcept
3283 {
3284 policy::publishPolicyProgress(policy_context_.get(), iteration,
3285 oracle_calls, refits, training_size);
3286 }
3287
3292 [[nodiscard]] bool hyperparametersNeedRefit() const noexcept
3293 {
3294 return training_obs.R.rows() > 0 &&
3295 (!gp_model_ready_ || kernel_requires_refit_ ||
3296 fitted_training_revision_ != training_revision_);
3297 }
3298
3301 bool refitGPIfTrainingChanged(bool reinit_seeds)
3302 {
3303 if (!hyperparametersNeedRefit()) return false;
3304 refitGP(reinit_seeds);
3305 return true;
3306 }
3307
3317 [[nodiscard]] bool wouldRefitAtNextRefresh() const noexcept
3318 {
3319 if (!initialised || training_obs.R.rows() == 0) return false;
3320 if (!hyperparametersNeedRefit()) return false;
3321 if (kernel_requires_refit_) return true;
3322 const bool never_fitted = fitted_training_revision_ ==
3323 std::numeric_limits<std::uint64_t>::max();
3324 if (never_fitted) return true;
3325 const std::uint64_t growth =
3326 training_revision_ - fitted_training_revision_;
3327 return growth >= refit_training_revisions_;
3328 }
3329
3345 {
3346 if (!initialised) return;
3347 if (training_obs.R.rows() == 0) return;
3348 // SCG runs on the training-revision cadence for every model
3349 // profile. Measured on the Baker contract
3350 // boards: per-append SCG random-walks the sloppy NLML
3351 // magnitude/lengthscale valley (09/17 barrier flips with 2-3x
3352 // mag2 swings between consecutive outers), an uncapped
3353 // stationarity trigger degenerates to per-append on descending
3354 // runs (06 and 20 timed out on its objective-evaluation cost),
3355 // and even a stationarity SKIP at cadence points costs one
3356 // objective evaluation each -- enough to push a borderline cell
3357 // (03, 127 s) over the 130 s cap for a marginal quiet-stretch
3358 // saving. Plain cadence graded best (21/24).
3360 const bool never_fitted = fitted_training_revision_ ==
3361 std::numeric_limits<std::uint64_t>::max();
3362 const std::uint64_t growth =
3363 never_fitted ? refit_training_revisions_
3364 : (training_revision_ - fitted_training_revision_);
3365 if (kernel_requires_refit_ || never_fitted ||
3366 growth >= refit_training_revisions_) {
3367 refitGP(/*reinit_seeds=*/false);
3368 return;
3369 }
3370 }
3371 if (policy_context_ != nullptr && policy_context_->policy != nullptr) {
3372 bool pruned_now = false;
3373 if (policy_retained_owner_ != policy_context_->policy ||
3374 policy_retained_training_revision_ != training_revision_) {
3375 pruned_now =
3376 retainTrainingRowsForPolicy(*policy_context_->policy);
3377 }
3378 if (training_obs.R.rows() == 0) return;
3379 policy::SearchState state;
3380 state.kind = policy_context_->kind;
3381 state.iteration = policy_context_->iteration;
3382 state.oracle_calls = policy_context_->oracle_calls;
3383 state.training_size = static_cast<int>(training_obs.R.rows());
3384 state.hyperparameter_refits =
3385 policy_context_->hyperparameter_refits;
3386 state.engine_would_retrain = false;
3388 !pruned_now &&
3389 !gp.trainingFactorAppendable(training_obs.R.rows());
3390 state.gp = &gp;
3391 const policy::TrainingPolicy* policy = policy_context_->policy;
3393 refitGP(/*reinit_seeds=*/false);
3394 return;
3395 }
3396 const bool rebuild =
3398 if (pruned_now && gp_model_ready_) return;
3399 if (rebuild && gp_model_ready_) {
3400 parkActiveModelBeforeSwitch(-1);
3401 gp.invalidateTrainingFactorCache();
3402 }
3403 }
3405 }
3406
3412 const gpr::Observation& acquired, ConvergenceNormType force_norm,
3413 Eigen::Index max_rows = 0,
3414 double force_tolerance = std::numeric_limits<double>::infinity(),
3416 nullptr)
3417 {
3418 if (trust_report) *trust_report = {};
3419 if (!initialised || !gp_model_ready_ || kernel_requires_refit_ ||
3420 (max_rows > 0 && training_obs.R.rows() > max_rows) ||
3421 !gp.hasBeenOptimized() || !(force_tolerance > 0.0))
3422 return false;
3423 double force_error = 0.0, force_sd = 0.0, evidence = 0.0;
3424 if (gp.measuredRowsAgreeWithPosterior(acquired, force_norm,
3425 &force_error, &force_sd,
3426 &evidence, 1.0, trust_report) !=
3428 return false;
3429 if (evidence_refit_trigger_) {
3430 // The refit decision weighs the rows by what they say about the
3431 // kernel: the contradiction evidence accumulated since the last
3432 // fit. A broad posterior that explains its rows carries no
3433 // evidence against theta, so its spread alone requests no fit.
3434 if (acquired_evidence_nats_ + evidence >= 1.0) return false;
3435 } else if (std::max(force_error, force_sd) >= force_tolerance) {
3436 // Statistical agreement with a broad posterior cannot certify
3437 // the force resolution. Unresolved rows retain the kernel-refit
3438 // policy.
3439 return false;
3440 }
3441 gp.clearModeRefitHint();
3443 if (!gp.isDecomposedSuccessfully()) return false;
3444 // The batch counts against theta only once it is conditioned: a
3445 // failed conditioning requests a refit, and a retried batch must not
3446 // be counted twice.
3447 if (evidence_refit_trigger_) acquired_evidence_nats_ += evidence;
3448 return true;
3449 }
3450
3453 void setEvidenceRefitTrigger(bool enabled) noexcept
3454 {
3455 evidence_refit_trigger_ = enabled;
3456 }
3457 [[nodiscard]] bool evidenceRefitTrigger() const noexcept
3458 {
3459 return evidence_refit_trigger_;
3460 }
3461
3463 [[nodiscard]] double acquiredEvidenceNats() const noexcept
3464 {
3465 return acquired_evidence_nats_;
3466 }
3467
3470 bool acquiredEvidenceRequestsRefit(double batch_nats) noexcept
3471 {
3472 const double total = acquired_evidence_nats_ + batch_nats;
3473 if (total >= 1.0) return true;
3474 acquired_evidence_nats_ = total;
3475 return false;
3476 }
3477
3484 ConvergenceNormType force_norm,
3485 Eigen::Index max_rows,
3486 double force_tolerance)
3487 {
3488 if (!(std::isfinite(force_tolerance) && force_tolerance > 0.0) ||
3489 !conditionGPOnConsistentRows(acquired, force_norm, max_rows))
3490 return false;
3491 double force_error = 0.0, force_sd = 0.0;
3492 const auto verdict = gp.measuredRowsAgreeWithPosterior(
3493 acquired, force_norm, &force_error, &force_sd);
3494 return verdict == gpr::GaussianProcessRegression::MeasuredRowVerdict::
3495 Consistent &&
3496 std::max(force_error, force_sd) < force_tolerance;
3497 }
3498
3503 {
3504 syncSecantQuadraticPrior();
3505 if (!initialised || training_obs.R.rows() == 0) return;
3506 // Refactorizing the same measured rows does not change p(theta | D).
3507 // Preserve its existing measure while rebuilding conditional factors;
3508 // changed observations or parameter state require a new measure.
3509 const auto posterior =
3510 conditioned_training_revision_ == training_revision_ &&
3511 virtual_obs.R.rows() == 0
3512 ? gp.currentHyperparameterPosterior()
3514 if (!gp_model_ready_) {
3515 gp.setHyperparameters(training_obs, atoms_config, true, true, true);
3516 }
3517 parkActiveModelBeforeSwitch(-1);
3518 if (virtual_obs.R.rows() > 0) {
3519 materializeWithNoiseFloor(gp, composedTrainingObs(),
3520 likelihoodNoiseFloorSigma2());
3521 } else {
3522 materializeWithNoiseFloor(gp, training_obs,
3523 likelihoodNoiseFloorSigma2());
3524 }
3525 gp_model_ready_ = true;
3526 conditioned_training_revision_ = training_revision_;
3527 if (!posterior.empty())
3528 (void)gp.conditionOnHyperparameterPosterior(posterior);
3529 markActiveModel(-1);
3530 }
3531
3532private:
3533 void trimSecantReplayToCap()
3534 {
3535 // The cap applies to true-force notes that never entered
3536 // ~training_obs~. A training-row sample is the reconfigure seed
3537 // for that retained row, image index included, so dropping it
3538 // would rebuild from a suffix and skip the training_obs fallback.
3539 std::size_t non_training = 0;
3540 for (const SecantReplaySample& sample: secant_replay_)
3541 if (!sample.training_row) ++non_training;
3542 if (non_training <= kMaxSecantReplaySamples) return;
3543 const std::size_t drop = non_training - kMaxSecantReplaySamples;
3544 std::vector<SecantReplaySample> kept;
3545 kept.reserve(secant_replay_.size() - drop);
3546 std::size_t dropped = 0;
3547 for (SecantReplaySample& sample: secant_replay_) {
3548 if (!sample.training_row && dropped < drop) {
3549 ++dropped;
3550 continue;
3551 }
3552 kept.push_back(std::move(sample));
3553 }
3554 secant_replay_.swap(kept);
3555 }
3556
3557 // Drop replay samples whose training geometry has been pruned. A
3558 // true-force note that never entered ~training_obs~ stays, subject
3559 // to the cap, because the training set is not its ledger.
3560 void discardPrunedSecantReplay()
3561 {
3562 if (secant_replay_.empty()) return;
3563 std::vector<SecantReplaySample> kept;
3564 kept.reserve(secant_replay_.size());
3565 for (SecantReplaySample& sample: secant_replay_) {
3566 if (!sample.training_row ||
3567 detail::findPositionRow(training_obs, sample.position) >= 0)
3568 kept.push_back(std::move(sample));
3569 }
3570 if (kept.size() != secant_replay_.size()) secant_replay_.swap(kept);
3571 }
3572
3573 void observeSecant(int image_idx, const Eigen::VectorXd& positions,
3574 const Eigen::VectorXd& gradient, double energy,
3575 optim::SecantAccounting accounting,
3576 bool training_row = true)
3577 {
3578 // Keep the measurement even while the features are off. Re-enable
3579 // replays this log, and the training rows alone have no image index.
3580 secant_replay_.push_back(SecantReplaySample{
3581 image_idx, positions, gradient, energy, accounting, training_row});
3582 // Training-row samples are outside the cap, so only a
3583 // non-training note can make the log too long.
3584 if (!training_row) trimSecantReplayToCap();
3585 if (!secant_config_.enabled()) return;
3586 // The global secant is the chronological true-force stream. The
3587 // quadratic mean refits it, residualized when a physical prior is
3588 // active, and the consistency probe reads the same stream. Its pair
3589 // counts are the session's: one per measurement. An image secant is
3590 // that image's own stream of the same measurements, which seeds its
3591 // climbing direction, so it never counts them a second time.
3592 optim::recordSecantObservation(global_secant_, positions, gradient,
3593 energy, secant_counts_, accounting);
3594 rememberSecantForceSample(positions, gradient, energy);
3595 if (image_idx >= 0) {
3596 const auto slot = static_cast<std::size_t>(image_idx);
3597 while (image_secants_.size() <= slot)
3598 image_secants_.emplace_back(secant_config_.method);
3600 image_secants_[slot], positions, gradient, energy,
3602 }
3603 }
3604
3605 void syncSecantQuadraticPrior()
3606 {
3607 if (!secant_config_.quadratic_prior_mean) return;
3608 if (!global_secant_.available() ||
3609 !global_secant_.hasReferenceEnergy()) {
3610 gp.clearSecantQuadraticPrior();
3611 return;
3612 }
3613 if (gp.physicalPriorMeanActive()) {
3614 if (secant_force_samples_.empty())
3615 throw std::logic_error(
3616 "secant quadratic mean has no true-force stream to "
3617 "residualize");
3618 const optim::SecantHessian residual = optim::secantFittedToResidual(
3619 secant_config_.method, secant_force_samples_,
3620 [&](const Eigen::VectorXd& position, double& energy,
3621 Eigen::VectorXd& gradient) {
3622 if (!gp.samplePhysicalPriorMean(position, energy, gradient))
3623 throw std::logic_error(
3624 "secant quadratic mean lost its physical prior");
3625 });
3626 if (!residual.available() || !residual.hasReferenceEnergy()) {
3627 gp.clearSecantQuadraticPrior();
3628 return;
3629 }
3630 gp.setSecantQuadraticPrior(
3631 residual.referencePosition(), residual.referenceGradient(),
3632 residual.hessian(), residual.referenceEnergy());
3633 return;
3634 }
3635 gp.setSecantQuadraticPrior(global_secant_.referencePosition(),
3636 global_secant_.referenceGradient(),
3637 global_secant_.hessian(),
3638 global_secant_.referenceEnergy());
3639 }
3640
3641 void rememberSecantForceSample(const Eigen::VectorXd& position,
3642 const Eigen::VectorXd& gradient,
3643 double energy)
3644 {
3645 if (!secant_config_.quadratic_prior_mean) return;
3646 optim::SecantForceSample sample;
3647 sample.position = position;
3648 sample.gradient = gradient;
3649 sample.energy = energy;
3650 secant_force_samples_.push_back(std::move(sample));
3651 }
3652
3653 // The posterior action excludes only the quadratic installed on the GP.
3654 // That installed model is residualized when a physical prior is active,
3655 // and is still the authoritative trained model without one.
3656 [[nodiscard]] Eigen::VectorXd secantQuadraticHessianAction(
3657 const Eigen::VectorXd& direction) const
3658 {
3659 if (!gp.secantQuadraticPriorActive())
3660 return Eigen::VectorXd::Zero(direction.size());
3661 return gp.secantQuadraticHessian() * direction;
3662 }
3663
3664 // One consumed true-force geometry, including the image that owned it.
3665 // Training rows do not store that index, so reconfigure replays this log
3666 // rather than the merged training matrix.
3667 struct SecantReplaySample {
3668 int image_idx = -1;
3669 Eigen::VectorXd position;
3670 Eigen::VectorXd gradient;
3671 double energy = 0.0;
3673 // False for a true-force note that did not append a training row.
3674 bool training_row = true;
3675 };
3676
3677 optim::SecantHessianConfig secant_config_;
3678 optim::SecantHessian global_secant_;
3679 std::vector<optim::SecantForceSample> secant_force_samples_;
3680 std::vector<optim::SecantHessian> image_secants_;
3681 // Cap on true-force notes that never entered ~training_obs~.
3682 // Training-row samples are exempt: they carry the image index the
3683 // training matrix does not, and ~discardPrunedSecantReplay~ drops
3684 // one whose geometry has left the retained rows.
3685 static constexpr std::size_t kMaxSecantReplaySamples = 256;
3686 std::vector<SecantReplaySample> secant_replay_;
3687 optim::SecantCurvatureCounts secant_counts_;
3688 std::size_t secant_pairs_checked_ = 0;
3689
3690 void mergeRepeatedObservation(int row, double energy,
3691 const Eigen::VectorXd& gradient)
3692 {
3693 // One covariance row represents all repeated draws at its geometry.
3694 // Every image selecting that row uses the same count-weighted target.
3696 auto& count = training_multiplicity[static_cast<std::size_t>(row)];
3697 const double weight = static_cast<double>(count);
3698 training_obs.E(row, 0) =
3699 (weight * training_obs.E(row, 0) + energy) / (weight + 1.0);
3700 training_obs.G.row(row) =
3701 (weight * training_obs.G.row(row) + gradient.transpose()) /
3702 (weight + 1.0);
3703 ++count;
3704 recordTrainingMutation();
3705 for (auto& model: image_models)
3706 model.refreshSelectedObservation(row, training_obs);
3707 }
3708
3709 // SCG frequency cap: full refits are considered only every this
3710 // many training-set appends, regardless of model profile.
3711 std::uint64_t refit_training_revisions_ = 5;
3712
3713 // Bound on live virtual observations. Each pin suppresses one
3714 // extrapolation fantasy; the band has at most nimages-2 interior
3715 // images, and stale pins retire on nearby real data, so a small
3716 // FIFO suffices.
3717 static constexpr std::size_t kMaxVirtualObservations = 8;
3718
3719 const double* likelihood_noise_floor_rms_ = nullptr;
3720#ifdef USE_READCON_DB
3721 ObservationArchive* observation_archive_ = nullptr;
3723 std::vector<ObservationArchive::ArchivedRow> archive_pool_;
3724 uint64_t archive_pool_snapshot_ = 0;
3727 uint64_t archive_first_row_ = 0;
3728#endif
3729 bool gp_model_ready_ = false;
3730 // A changed coordinate map needs its own fit even at unchanged data.
3731 bool kernel_requires_refit_ = false;
3732 // Refit on accumulated contradiction evidence instead of force
3733 // resolution; the sum is cleared by every hyperparameter fit.
3734 bool evidence_refit_trigger_ = false;
3735 double acquired_evidence_nats_ = 0.0;
3736 std::uint64_t training_revision_ = 0;
3737 std::uint64_t conditioned_training_revision_ =
3738 std::numeric_limits<std::uint64_t>::max();
3739 std::uint64_t fitted_training_revision_ =
3740 std::numeric_limits<std::uint64_t>::max();
3741 std::uint64_t policy_retained_training_revision_ =
3742 std::numeric_limits<std::uint64_t>::max();
3743 const policy::TrainingPolicy* policy_retained_owner_ = nullptr;
3744 std::shared_ptr<policy::PolicyContext> policy_context_;
3745 mutable std::uint64_t global_surrogate_revision_ = 0;
3746 mutable std::uint64_t global_surrogate_training_revision_ =
3747 std::numeric_limits<std::uint64_t>::max();
3748 mutable bool global_surrogate_inputs_initialized_ = false;
3749 mutable Eigen::VectorXd global_surrogate_theta_;
3750 mutable SharedParameterState global_surrogate_shared_state_;
3751 mutable double global_surrogate_noise_sigma2_ =
3752 std::numeric_limits<double>::quiet_NaN();
3753 gpr::Coord global_geodesic_reference_path_;
3754 std::shared_ptr<const gpr::geometry::InternalCoordinateChart>
3755 global_internal_coordinate_chart_;
3756 double global_internal_coordinate_length_scale_ =
3757 std::numeric_limits<double>::quiet_NaN();
3758
3759 void setGlobalGeodesicReferencePath(const gpr::Coord& reference_path)
3760 {
3761 if (global_geodesic_reference_path_.rows() == reference_path.rows() &&
3762 global_geodesic_reference_path_.cols() == reference_path.cols() &&
3763 (global_geodesic_reference_path_.array() == reference_path.array())
3764 .all()) {
3765 return;
3766 }
3767 global_geodesic_reference_path_ = reference_path;
3768 }
3769
3770 void recordTrainingMutation() noexcept
3771 {
3772 ++training_revision_;
3773 }
3774
3775 static void materializeWithNoiseFloor(gpr::GaussianProcessRegression& model,
3776 const gpr::Observation& observations,
3777 double noise_floor_sigma2)
3778 {
3779 if (!model.applyLikelihoodNoiseVarianceFloor(noise_floor_sigma2,
3780 observations) &&
3781 !model.refreshActivePosterior(observations)) {
3782 model.updateModelWithFullData(observations);
3783 }
3784 }
3785
3786 [[nodiscard]] static double effectiveModelNoiseVariance(
3787 const gpr::GaussianProcessRegression* model, double floor_sigma2)
3788 {
3789 const double fitted_sigma2 =
3790 model != nullptr ? model->getSigma2()
3791 : std::numeric_limits<double>::quiet_NaN();
3792 const bool fitted_valid =
3793 std::isfinite(fitted_sigma2) && fitted_sigma2 > 0.0;
3794 const bool floor_valid =
3795 std::isfinite(floor_sigma2) && floor_sigma2 > 0.0;
3796 if (!floor_valid) return fitted_sigma2;
3797 if (!fitted_valid) return floor_sigma2;
3798 return std::max(fitted_sigma2, floor_sigma2);
3799 }
3800
3801 [[nodiscard]] static bool surrogateInputsMatch(
3802 const Eigen::VectorXd& lhs_theta, double lhs_noise_sigma2,
3803 const Eigen::VectorXd& rhs_theta, double rhs_noise_sigma2)
3804 {
3805 if (lhs_theta.size() != rhs_theta.size()) return false;
3806 if (lhs_theta.size() > 0 &&
3807 !(lhs_theta.array() == rhs_theta.array()).all()) {
3808 return false;
3809 }
3810 const bool lhs_noise_valid =
3811 std::isfinite(lhs_noise_sigma2) && lhs_noise_sigma2 > 0.0;
3812 const bool rhs_noise_valid =
3813 std::isfinite(rhs_noise_sigma2) && rhs_noise_sigma2 > 0.0;
3814 if (lhs_noise_valid != rhs_noise_valid) return false;
3815 return !lhs_noise_valid || lhs_noise_sigma2 == rhs_noise_sigma2;
3816 }
3817
3821 [[nodiscard]] double localLikelihoodNoiseFloorSigma2() const noexcept
3822 {
3823 if (likelihood_noise_floor_rms_ != nullptr) {
3824 const double rms = *likelihood_noise_floor_rms_;
3825 if (std::isfinite(rms) && rms > 0.0) return rms * rms;
3826 }
3827 // A deterministic oracle reports no noise, and a learned
3828 // likelihood noise then falls without bound: the resolution
3829 // floor d = l sqrt(noise / magn) / 2 collapses with it, every
3830 // acquisition is admitted, and the training set grows until the
3831 // factorisation dominates the run. The profile's own sigma2 is
3832 // the floor that survives: it is set from the force criterion
3833 // (see the GPRD_ZBL block in main_neb.cpp), so learning may raise
3834 // the noise above it but not lower it beneath the resolution the
3835 // problem asks for.
3836 const double profile_sigma2 = input_parameters.gp_sigma2.value;
3837 if (std::isfinite(profile_sigma2) && profile_sigma2 > 0.0)
3838 return profile_sigma2;
3839 return std::numeric_limits<double>::quiet_NaN();
3840 }
3841
3851 [[nodiscard]] double likelihoodNoiseFloorSigma2() const noexcept
3852 {
3853 return likelihood_noise_floor_sigma2_;
3854 }
3855
3856 double likelihood_noise_floor_sigma2_ =
3857 std::numeric_limits<double>::quiet_NaN();
3858
3859 AfterInitialise after_initialise_;
3860 int prior_observations_ = 0;
3861 LocalKernelSeed local_kernel_seed_{};
3862
3863 int active_model_owner_ = -1;
3864
3865 [[nodiscard]] bool activeModelIs(int owner) const noexcept
3866 {
3867 return active_model_owner_ == owner;
3868 }
3869
3870 void markActiveModel(int owner) noexcept
3871 {
3872 active_model_owner_ = owner;
3873 if (owner >= 0 && owner < static_cast<int>(image_models.size())) {
3874 if (image_models[owner].gp()) {
3875 image_models[owner].gp()->claimActiveTrainingCholeskyFactor();
3876 }
3877 } else if (owner < 0) {
3878 gp.claimActiveTrainingCholeskyFactor();
3879 }
3880 }
3881
3882 void parkActiveModelBeforeSwitch(int next_owner)
3883 {
3884 if (active_model_owner_ == next_owner) return;
3885 if (active_model_owner_ >= 0 &&
3886 active_model_owner_ < static_cast<int>(image_models.size())) {
3887 if (auto* active_gp = image_models[active_model_owner_].gp()) {
3888 (void)active_gp->parkTrainingCholeskyFactor();
3889 }
3890 return;
3891 }
3892 if (active_model_owner_ < 0) {
3893 (void)gp.parkTrainingCholeskyFactor();
3894 }
3895 }
3896};
3897
3898} // namespace neb
3899} // namespace gpr
3900
3901#endif // GPR_NEB_SESSION_H_
@ x
Definition Enums.h:28
ConvergenceNormType
Definition Enums.h:48
Decisions a search asks before it calls the oracle, admits a row, refits hyperparameters,...
Methods to calculate distances between atoms.
Definition Distance.h:154
void dist_emd(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Calculates the Earth Mover's Distance between sets of configurations.
Set up the GP-dimer problem.
bool activateFrozenAtoms(const gpr::Coord &R, const double activation_distance, gpr::AtomsConfiguration &atoms_config)
Update the active frozen-atom set for one or more configurations.
void setConstSigma2(const double _constSigma2)
Set the constSigma2 value.
LikelihoodNoiseVarianceUpdate setLikelihoodNoiseVariance(double physical_sigma2, const Observation *full_observation=nullptr)
Set the likelihood noise variance in physical output units.
bool conditionOnHyperparameterPosterior(const HyperparameterPosterior &posterior)
void setParameters(const GPRSetup &parameters)
Set parameters of the GPR model.
void claimActiveTrainingCholeskyFactor()
Associate the live ScaLAPACK factor with this GP after a materialize.
void setInternalCoordinateChart(std::shared_ptr< const geometry::InternalCoordinateChart > chart, double length_scale)
void synchronizeOutputTransformFrom(const GaussianProcessRegression &source)
bool refreshActivePosterior(const Observation &full_observation)
double fitGeodesicHeatPrior(const Coord &reference_path, const Observation &training_data)
void updateModelWithFullData(const Observation &full_observation)
void setHyperparameters(const Observation &all_obs, const AtomsConfiguration &conf_info, const bool update_sexpat_cf_param=true, const bool update_const_cf_param=true, const bool update_sqrt_prior_param=true)
Set up hyperparameters for GPR.
bool applyLikelihoodNoiseVarianceFloor(double floor_sigma2, const Observation &full_observation)
Raise the Gaussian likelihood noise variance to a floor.
void restoreLengthScaleFitState(const LengthScaleFitState &state)
bool usesManifoldChart() const noexcept
Definition SexpatCF.h:616
ScopedParameterRestore(const ScopedParameterRestore &)=delete
ScopedParameterRestore & operator=(ScopedParameterRestore &&)=delete
ScopedParameterRestore & operator=(const ScopedParameterRestore &)=delete
ModelLease & operator=(const ModelLease &)=delete
ScopedParameterRestore scopedParameterRestore() &
Definition Session.h:2775
gpr::GaussianProcessRegression & gp() const
Definition Session.h:2642
ModelLease(const ModelLease &)=delete
ModelLease(ActiveLearningSession &session, int owner)
Definition Session.h:2616
const gpr::Observation & observations() const
Definition Session.h:2647
ModelLease & operator=(ModelLease &&)=default
PolicyScope(ActiveLearningSession *session, const policy::TrainingPolicy *policy, policy::SearchKind kind=policy::SearchKind::Neb)
Definition Session.h:3230
PolicyScope(const PolicyScope &)=delete
PolicyScope(PolicyScope &&other) noexcept
Definition Session.h:3253
void publishProgress(int iteration, int oracle_calls, int refits, int training_size) noexcept
Definition Session.h:3261
PolicyScope & operator=(PolicyScope &&)=delete
PolicyScope & operator=(const PolicyScope &)=delete
eon_relax_band_t * band
The nudged elastic band: path, GP-NEB driver, configuration and result, acquisition,...
ObservationRetention
Whether an acquisition still needs a ledger entry when admitted to a model.
Definition Session.h:61
SecantHessian secantFittedToResidual(SecantHessianMethod method, const std::vector< SecantForceSample > &samples, Prior &&prior)
void recordSecantObservation(SecantHessian &secant, const Eigen::VectorXd &position, const Eigen::VectorXd &gradient, double energy, SecantCurvatureCounts &counts, SecantAccounting accounting=SecantAccounting::Count)
std::vector< int > canonicalizeRetainedIndices(const std::vector< int > &keep, int n)
std::vector< int > consensusRetainTrainingRows(const TrainingPolicy &policy, const std::vector< Eigen::VectorXd > &rows)
bool indexListIsIdentity(const std::vector< int > &indices, int n)
void publishPolicyProgress(PolicyContext *context, int iteration, int oracle_calls, int refits, int training_size) noexcept
bool consensusShouldRebuildFactor(const TrainingPolicy &policy, const SearchState &state)
bool consensusShouldRetrainHyperparameters(const TrainingPolicy &policy, const SearchState &state)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
FieldMatrixd Coord
Definition Macros.h:35
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
UncertaintyMode
Definition Structures.h:177
Stores configurations of all atoms in the system.
Definition Structures.h:832
Structure of the input parameters. All input parameters are pairs of string names and values.
Definition Structures.h:370
Observation data: energy, gradient and positions.
FieldMatrixd E
void remapGlobalRows(const std::vector< int > &old_to_new, const gpr::Observation &global)
Definition Session.h:776
gpr::GaussianProcessRegression * gp()
Definition Session.h:484
bool hasEnoughDirectRows(int n_min) const
Definition Session.h:668
int pruneAdaptiveAtPoint(const Eigen::VectorXd &band_point)
Definition Session.h:836
bool materializedFor(const Eigen::VectorXd &theta_global, double likelihood_noise_floor_sigma2, const SharedParameterState &shared_state={}) const
Definition Session.h:894
void recordMaterialized(const Eigen::VectorXd &theta_global, double likelihood_noise_floor_sigma2, const SharedParameterState &shared_state={})
Definition Session.h:910
void setInternalCoordinateChart(std::shared_ptr< const gpr::geometry::InternalCoordinateChart > chart, double length_scale)
Definition Session.h:507
std::uint64_t surrogateRevision() const noexcept
Definition Session.h:610
const std::vector< uint64_t > & archivedKeys() const noexcept
Definition Session.h:889
const std::vector< int > & selectedIndices() const
Definition Session.h:639
std::uint64_t observationRevision() const noexcept
Definition Session.h:601
std::uint64_t synchronizeSurrogateRevision(const Eigen::VectorXd &theta_global, double likelihood_noise_floor_sigma2, const SharedParameterState &shared_state={}) const
Definition Session.h:615
const std::shared_ptr< const gpr::geometry::InternalCoordinateChart > & internalCoordinateChart() const noexcept
Definition Session.h:543
void updateConfiguration(const gpr::AtomsConfiguration &configuration)
Definition Session.h:499
void replaceNeighborhood(gpr::Observation observations, std::vector< int > selected_indices, std::vector< uint64_t > archived_keys={})
Definition Session.h:877
void appendObservation(const Eigen::VectorXd &positions, double energy, const Eigen::VectorXd &gradient, int global_row_index)
Definition Session.h:673
const gpr::Coord & geodesicReferencePath() const noexcept
Definition Session.h:592
const gpr::GaussianProcessRegression * gp() const
Definition Session.h:489
bool hasGeodesicReferencePath() const noexcept
Definition Session.h:587
void refreshSelectedObservation(int global_row, const gpr::Observation &global)
Definition Session.h:707
void compactAfterRowRemoval(int removed_row)
Definition Session.h:734
double internalCoordinateLengthScale() const noexcept
Definition Session.h:548
void setGeodesicReferencePath(gpr::Coord reference_path)
Definition Session.h:553
const gpr::Observation & observations() const
Definition Session.h:494
const std::vector< int > & directIndices() const
Definition Session.h:649
void setGP(std::unique_ptr< gpr::GaussianProcessRegression > next_gp)
Definition Session.h:477
bool operator!=(const SurrogateFingerprint &other) const noexcept
Definition Session.h:228
static SurrogateFingerprint global(std::uint64_t revision)
Definition Session.h:211
static SurrogateFingerprint image(int image_idx, std::uint64_t revision)
Definition Session.h:216
bool operator==(const SurrogateFingerprint &other) const noexcept
Definition Session.h:222
gpr::Observation composedTrainingObs() const
Definition Session.h:1922
const optim::SecantHessian & globalSecantHessian() const noexcept
Definition Session.h:345
int mmfModelOwner(int image_idx, bool dimer_use_global_gp) const
Definition Session.h:1080
std::size_t secantReplaySize() const noexcept
Samples kept so reconfigure can rebuild per-image secant seeds.
Definition Session.h:370
void setSecantHessianConfig(const optim::SecantHessianConfig &config)
Definition Session.h:253
bool setImageInternalCoordinateChart(int i, std::shared_ptr< const gpr::geometry::InternalCoordinateChart > chart)
Definition Session.h:2294
double acquiredEvidenceNats() const noexcept
Definition Session.h:3463
SurrogateFingerprint surrogateFingerprint(int owner) const
Definition Session.h:1070
void setLikelihoodNoiseFloorRms(const double *noise_rms) noexcept
Definition Session.h:1156
bool setBandGeodesicReferencePath(const gpr::Coord &reference_path)
Definition Session.h:2392
bool hasCurrentChainCertificate(int image_idx, const Eigen::VectorXd &positions) const
Definition Session.h:2081
void observationVarianceAtImage(int i, gpr::Observation &probe)
Definition Session.h:2819
SharedParameterState sharedParameterState() const
Definition Session.h:999
void markCurrentTrainingRevisionRetainedByPolicy(const policy::TrainingPolicy *policy) noexcept
Definition Session.h:1766
void setEvidenceRefitTrigger(bool enabled) noexcept
Definition Session.h:3453
void withImageModel(int i, Use &&use)
Definition Session.h:2849
std::uint64_t imageModelSurrogateRevision(int image_idx) const
Definition Session.h:1030
bool wouldRefitAtNextRefresh() const noexcept
Definition Session.h:3317
bool purchaseSecantConsistencyProbe(Measure &&measure)
Definition Session.h:303
bool acquiredEvidenceRequestsRefit(double batch_nats) noexcept
Definition Session.h:3470
std::function< bool(GaussianProcessRegression &, const AtomsConfiguration &, const Observation &)> AfterInitialise
Definition Session.h:1276
long resolutionDedupRejected() const noexcept
Definition Session.h:1658
std::vector< double > virtual_retire_radii
Per-row coordinate-norm retire radii, aligned with ~virtual_obs~.
Definition Session.h:427
const std::shared_ptr< const gpr::geometry::InternalCoordinateChart > & globalInternalCoordinateChart() const noexcept
Definition Session.h:2376
bool rollbackTrainingObservations(Eigen::Index row_count)
Definition Session.h:2874
std::uint64_t globalModelSurrogateRevision() const
Definition Session.h:1048
ModelLease acquireImageModel(int i)
Definition Session.h:2792
void setAfterInitialise(AfterInitialise hook)
Definition Session.h:1282
int boundActiveSetToBand(const gpr::Coord &band_positions, Eigen::Index max_rows)
Definition Session.h:1406
void notePriorObservations(int count) noexcept
Definition Session.h:1293
gpr::InputParameters input_parameters
Definition Session.h:1134
int pruneTrainingObservationsToBudget(const gpr::Coord &band_positions, Eigen::Index max_rows)
Definition Session.h:2960
void recordCurrentChainCertificate(int image_idx, const Eigen::VectorXd &positions, double energy, const Eigen::VectorXd &gradient)
Definition Session.h:2029
std::uint64_t refitTrainingRevisions() const noexcept
Definition Session.h:1169
void appendCurrentChainObservation(int image_idx, const Eigen::VectorXd &positions, double energy, const Eigen::VectorXd &gradient, ObservationRetention retention=ObservationRetention::RecordAcquisition, optim::SecantAccounting secant_accounting=optim::SecantAccounting::Count)
Definition Session.h:1994
bool sharesGlobalHyperparameters(const gpr::GaussianProcessRegression &model) const
Definition Session.h:1021
void noteExternalHyperparameterFit() noexcept
Definition Session.h:1325
int pruneImageModelsAdaptive(const gpr::Coord &band_positions)
Definition Session.h:3089
void appendObservation(int image_idx, const Eigen::VectorXd &positions, double energy, const Eigen::VectorXd &gradient, ObservationRetention retention=ObservationRetention::RecordAcquisition, optim::SecantAccounting secant_accounting=optim::SecantAccounting::Count)
Definition Session.h:1941
std::function< void(gpr::InputParameters &, gpr::AtomsConfiguration &)> gp_setup
Definition Session.h:1141
static bool integratesHyperparameters(const gpr::GaussianProcessRegression &model)
Definition Session.h:1013
void recordCurrentChainCertificate(int image_idx, const Eigen::VectorXd &positions)
Definition Session.h:2010
const policy::PolicyContext * activePolicyContext() const noexcept
Definition Session.h:3275
const EndpointSymmetry & endpointSymmetry() const noexcept
Definition Session.h:1616
bool imageModelEligibleForPrediction(int i) const
Definition Session.h:2797
bool hyperparametersNeedRefit() const noexcept
Definition Session.h:3292
bool updateFrozenEnvironment(const gpr::Coord &band)
Definition Session.h:1335
void compactAfterRowRemoval(int removed_row)
Definition Session.h:2865
int priorObservations() const noexcept
Rows loaded from a seed file. Not an oracle-call count.
Definition Session.h:1288
void predictAtImage(int i, gpr::Observation &probe)
Definition Session.h:2810
void setEndpointSymmetry(EndpointSymmetry symmetry)
Definition Session.h:1601
std::uint64_t surfaceEpoch() const noexcept
Definition Session.h:1177
std::vector< ImageModel > image_models
Definition Session.h:997
double globalInternalCoordinateLengthScale() const noexcept
Definition Session.h:2381
void appendSymmetryImage(int source_row, const Eigen::VectorXd &positions, double energy, const Eigen::VectorXd &gradient)
Definition Session.h:1718
void withImageChartFallback(int i, Use &&use)
Definition Session.h:2836
bool addVirtualObservation(const Eigen::VectorXd &positions, double retire_radius)
Definition Session.h:1860
void noteTrueForceSecant(int image_idx, const Eigen::VectorXd &positions, double energy, const Eigen::VectorXd &gradient)
True-force secant only. Training retention is unchanged.
Definition Session.h:361
const LocalKernelSeed & localKernelSeed() const noexcept
Definition Session.h:1318
bool setImageGeodesicReferencePath(int i, const gpr::Coord &reference_path)
Definition Session.h:2410
gpr::Observation training_obs
Definition Session.h:246
void appendIndexedObservations(const std::vector< IndexedObservation > &observations)
Definition Session.h:2895
bool retainTrainingRowsForPolicy(const policy::TrainingPolicy &policy)
Definition Session.h:1777
bool conditionGPOnConsistentRows(const gpr::Observation &acquired, ConvergenceNormType force_norm, Eigen::Index max_rows=0, double force_tolerance=std::numeric_limits< double >::infinity(), gpr::GaussianProcessRegression::RefitTrustReport *trust_report=nullptr)
Definition Session.h:3411
void noteLocalKernelSeed(double signal_variance, double length_scale) noexcept
Definition Session.h:1307
std::uint64_t trainingRevision() const noexcept
Definition Session.h:1043
bool refitGP(bool reinit_seeds)
Definition Session.h:3111
bool secantReplayHoldsTrainingRow(const Eigen::VectorXd &position) const
True when an admitted-row sample still holds ~position~.
Definition Session.h:385
void setResolutionDedup(bool on) noexcept
Definition Session.h:1636
void addSecantCounts(const optim::SecantCurvatureCounts &extra)
Definition Session.h:406
double nearestTrainingDistance(const Eigen::VectorXd &positions) const
Definition Session.h:1555
int admitObservation(const Eigen::VectorXd &positions, double energy, const Eigen::VectorXd &gradient, optim::SecantAccounting secant_accounting=optim::SecantAccounting::Count)
Definition Session.h:1671
bool evidenceRefitTrigger() const noexcept
Definition Session.h:3457
void markModelMaterialized(int owner, const Eigen::VectorXd &theta, const SharedParameterState &shared_state)
Definition Session.h:2592
std::size_t secantReplayTrainingRows() const noexcept
Replay samples that record an admitted training row.
Definition Session.h:376
bool rollbackTrainingObservationsRetaining(Eigen::Index row_count, const std::vector< IndexedObservation > &retained_observations)
Definition Session.h:2905
bool refitGPIfTrainingChanged(bool reinit_seeds)
Definition Session.h:3301
SurrogateFingerprint mmfSurrogateFingerprint(int image_idx, bool dimer_use_global_gp) const
Definition Session.h:1093
bool withinTrainingResolution(const Eigen::VectorXd &positions) const
Definition Session.h:1648
void publishPolicyProgress(int iteration, int oracle_calls, int refits, int training_size) noexcept
Definition Session.h:3281
int pruneLeastInfluentialRow(const gpr::Coord &band_positions, bool ignore_noise)
Definition Session.h:2979
gpr::GaussianProcessRegression gp
Definition Session.h:471
double observationResolutionFloor() const
Definition Session.h:1530
std::vector< int > training_multiplicity
Definition Session.h:1848
void setRefitTrainingRevisions(std::uint64_t revisions) noexcept
Definition Session.h:1165
gpr::AtomsConfiguration atoms_config
Definition Session.h:1129
void retireVirtualObservationsNear(const Eigen::VectorXd &positions)
Definition Session.h:1893
int pruneTrainingObservationsAdaptive(const gpr::Coord &band_positions)
Definition Session.h:2935
gpr::Observation virtual_obs
Definition Session.h:425
void setImageNeighborhood(int i, const std::vector< int > &emd_indices, const Eigen::VectorXd *image_position=nullptr)
Definition Session.h:2110
static int selectMmfModelOwner(bool dimer_use_global_gp, bool image_model_eligible, int image_idx)
Definition Session.h:235
void initializePerImage(int n_images)
Definition Session.h:1367
bool setGlobalInternalCoordinateChart(std::shared_ptr< const gpr::geometry::InternalCoordinateChart > chart)
Definition Session.h:2316
bool conditionGPOnResolvedRows(const gpr::Observation &acquired, ConvergenceNormType force_norm, Eigen::Index max_rows, double force_tolerance)
Definition Session.h:3483
long symmetryRowsRejected() const noexcept
Definition Session.h:1628
void noteExternalTrainingEdit() noexcept
Definition Session.h:1761
void appendObservation(const Eigen::VectorXd &positions, double energy, const Eigen::VectorXd &gradient, ObservationRetention retention=ObservationRetention::RecordAcquisition, optim::SecantAccounting secant_accounting=optim::SecantAccounting::Count)
Definition Session.h:1574
std::vector< uint64_t > selectArchivedNeighbors(const std::vector< int > &kept, const Eigen::VectorXd *image_position, Eigen::Index D)
Definition Session.h:2188
long symmetryRowsAdmitted() const noexcept
Definition Session.h:1624
std::optional< IndexedObservation > currentChainObservation(int image_idx, const Eigen::VectorXd &positions) const
Definition Session.h:2056
optim::SecantCurvatureCounts secantCounts() const
Definition Session.h:396
bool currentChainCertificateMatchesGeometry(int image_idx, const Eigen::VectorXd &positions) const
Definition Session.h:2045
EndpointSymmetry endpoint_symmetry_
Definition Session.h:1665
std::vector< IndexedObservation > current_chain_certificates
Definition Session.h:466
const optim::SecantHessian * imageSecantHessian(int image_idx) const noexcept
Definition Session.h:351
bool attachImageObservation(int image_idx, int global_row_index)
Definition Session.h:1977
bool operator==(const SharedParameterState &) const =default
gpr::GaussianProcessRegression::LengthScaleFitState length_scales
Definition Session.h:166
std::uint64_t atomic_posterior_revision
Definition Session.h:174
std::uint64_t hyperparameter_observation_revision
Definition Session.h:173
gpr::UncertaintyMode uncertainty_mode
Definition Session.h:172
bool enabled() const noexcept
Read-only view of one decision. Pointers are valid only for the call.
const GaussianProcessRegression * gp