Loading...
Searching...
No Matches
ActivePosterior.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#include <algorithm>
6#include <cmath>
7#include <cstdio>
8#include <limits>
9#include <mutex>
10#include <numeric>
11#include <optional>
12#include <stdexcept>
13#include <utility>
14
22#ifdef GPR_USE_FEATOMIC
24#endif
28#include "../JointObservation.h"
29#include "../PhaseTimers.h"
30#include "../RgminOpt.h"
32#include "OptimizerState.h"
33
34namespace gpr {
35namespace {
36
37class VarianceSubsetScope {
38public:
39 VarianceSubsetScope(int& count, std::vector<int>& ids,
40 const std::vector<int>& selected)
41 : count_(count), ids_(ids), saved_count_(count), saved_ids_(selected)
42 {
43 count_ = 0;
44 ids_.swap(saved_ids_);
45 }
46
47 ~VarianceSubsetScope()
48 {
49 count_ = saved_count_;
50 ids_.swap(saved_ids_);
51 }
52
53 VarianceSubsetScope(const VarianceSubsetScope&) = delete;
54 VarianceSubsetScope& operator=(const VarianceSubsetScope&) = delete;
55
56private:
57 int& count_;
58 std::vector<int>& ids_;
59 int saved_count_;
60 std::vector<int> saved_ids_;
61};
62
63Eigen::VectorXd observationChannels(const Observation& observation)
64{
65 Eigen::VectorXd values;
66 aux::AuxiliaryFunctionality{}.assembleVectorFromEnergyAndGradient(
67 observation, values);
68 return values;
69}
70
71void assignObservationChannels(const Eigen::VectorXd& values,
72 Observation& observation)
73{
74 const Eigen::Index n = observation.R.rows();
75 observation.E.resize(1, n);
76 observation.E.row(0) = values.head(n).transpose();
77 observation.G.resize(n, observation.R.cols());
78 for (Eigen::Index d = 0; d < observation.R.cols(); ++d)
79 observation.G.col(d) = values.segment((d + 1) * n, n);
80}
81
82bool hasFullFitPrefix(const Observation& full, const Observation& background)
83{
84 const Eigen::Index n = background.R.rows();
85 if (n == 0 || full.R.rows() <= n || full.R.cols() != background.R.cols())
86 return false;
87 if (!(full.R.topRows(n).array() == background.R.array()).all() ||
88 !(full.G.topRows(n).array() == background.G.array()).all())
89 return false;
90 for (Eigen::Index row = 0; row < n; ++row)
91 if (full.E.data()[row] != background.E.data()[row]) return false;
92 return true;
93}
94
96struct ActiveObjectiveTimer {
97 ScopedPhaseTimer timer{PhaseTimers::objective_seconds};
98
99 ActiveObjectiveTimer(Eigen::Index rows, Eigen::Index targets)
100 {
104 }
105};
106
107struct ResidualFitConditioning {
108 Coord anchors;
109 Eigen::VectorXd noise;
110 linalg::LocalExecutor execution;
111 std::shared_ptr<linalg::DistributedState> factor_execution;
112 // Anchors the candidate objectives condition on: the background rows
113 // closest to the added observations under the correction kernel, as
114 // many as the background's own hyperparameter fit uses. Every objective
115 // evaluation factorises this block, so its size is the fit's cost. Empty
116 // keeps every anchor. Final conditioning expands this set using the
117 // selected covariance and checks the correction at omitted anchors.
118 std::vector<Eigen::Index> fit_anchor_rows;
119
120 [[nodiscard]] bool subsetActive() const noexcept
121 {
122 return !fit_anchor_rows.empty() &&
123 static_cast<Eigen::Index>(fit_anchor_rows.size()) <
124 anchors.rows();
125 }
126
127 [[nodiscard]] Eigen::Index fitAnchorCount() const noexcept
128 {
129 return subsetActive()
130 ? static_cast<Eigen::Index>(fit_anchor_rows.size())
131 : anchors.rows();
132 }
133
134 [[nodiscard]] Coord fitAnchors() const
135 {
136 if (!subsetActive()) return anchors;
137 Coord result(fitAnchorCount(), anchors.cols());
138 for (Eigen::Index i = 0; i < result.rows(); ++i)
139 result.row(i) =
140 anchors.row(fit_anchor_rows[static_cast<std::size_t>(i)]);
141 return result;
142 }
143
144 [[nodiscard]] Eigen::VectorXd fitNoise() const
145 {
146 if (!subsetActive()) return noise;
147 const Eigen::Index channels = anchors.cols() + 1;
148 const Eigen::Index count = fitAnchorCount();
149 Eigen::VectorXd result(count * channels);
150 for (Eigen::Index c = 0; c < channels; ++c)
151 for (Eigen::Index i = 0; i < count; ++i)
152 result(c * count + i) =
153 noise(c * anchors.rows() +
154 fit_anchor_rows[static_cast<std::size_t>(i)]);
155 return result;
156 }
157
158 void includeCovarianceSupport(const KernelOperator& kernel,
159 const Coord& added)
160 {
161 if (!subsetActive()) return;
162 const EigenMatrix cross =
163 kernel.covarianceBlock(added, anchors, -1, -1);
164 if (cross.rows() != added.rows() || cross.cols() != anchors.rows() ||
165 !cross.allFinite())
166 throw std::invalid_argument("invalid residual support covariance");
167 for (Eigen::Index row = 0; row < anchors.rows(); ++row)
168 if (cross.col(row).cwiseAbs().maxCoeff() > noise(row))
169 fit_anchor_rows.push_back(row);
170 std::sort(fit_anchor_rows.begin(), fit_anchor_rows.end());
171 fit_anchor_rows.erase(
172 std::unique(fit_anchor_rows.begin(), fit_anchor_rows.end()),
173 fit_anchor_rows.end());
174 }
175
176 bool includeChangedAnchors(const Eigen::VectorXd& correction)
177 {
178 if (correction.size() != noise.size() || !correction.allFinite())
179 throw std::invalid_argument("invalid residual anchor correction");
180 if (!subsetActive()) return false;
181 const auto previous_size = fit_anchor_rows.size();
182 for (Eigen::Index row = 0; row < anchors.rows(); ++row) {
183 if (std::binary_search(fit_anchor_rows.begin(),
184 fit_anchor_rows.begin() + previous_size,
185 row))
186 continue;
187 for (Eigen::Index channel = 0; channel <= anchors.cols();
188 ++channel) {
189 const auto index = channel * anchors.rows() + row;
190 if (std::abs(correction(index)) > std::sqrt(noise(index))) {
191 fit_anchor_rows.push_back(row);
192 break;
193 }
194 }
195 }
196 std::sort(fit_anchor_rows.begin(), fit_anchor_rows.end());
197 return fit_anchor_rows.size() != previous_size;
198 }
199
202 Coord positions(const Coord& added) const
203 {
204 return stack(fitAnchors(), added);
205 }
206
209 Coord allPositions(const Coord& added) const
210 {
211 return stack(anchors, added);
212 }
213
214 bool prepare(const EigenMatrix& joint,
215 ConditionalKernelProjection& projection,
216 EigenMatrix& covariance, const EigenMatrix& fixed = {}) const
217 {
218 return prepareWith(fitAnchorCount(), fitNoise(), joint, projection,
219 covariance, factor_execution, fixed);
220 }
221
225 bool prepareAll(const EigenMatrix& joint,
226 ConditionalKernelProjection& projection,
227 EigenMatrix& covariance) const
228 {
229 return prepareWith(anchors.rows(), noise, joint, projection, covariance,
230 nullptr);
231 }
232
233 bool prepareKernel(const KernelOperator& kernel, const Coord& added,
234 ConditionalKernelProjection& projection,
235 EigenMatrix& covariance) const
236 {
237 ScopedPhaseTimer timer(PhaseTimers::factorization_seconds);
240 fitAnchorCount() * (anchors.cols() + 1);
241 std::shared_ptr<linalg::DistributedState> owned_execution;
242#ifdef GPR_LINALG_SCALAPACK
243 if (factor_execution) {
244 owned_execution = std::make_shared<linalg::DistributedState>(
245 factor_execution->communication());
246 owned_execution->configure(factor_execution->block_size(),
247 factor_execution->nprow());
248 }
249#endif
250 return projection.prepare(kernel, fitAnchors(), added, fitNoise(),
251 covariance, owned_execution);
252 }
253
254 static Coord stack(const Coord& top, const Coord& bottom)
255 {
256 Coord result(top.rows() + bottom.rows(), bottom.cols());
257 result.topRows(top.rows()) = top;
258 result.bottomRows(bottom.rows()) = bottom;
259 return result;
260 }
261
262 bool prepareWith(Eigen::Index anchor_count,
263 const Eigen::VectorXd& anchor_noise,
264 const EigenMatrix& joint,
265 ConditionalKernelProjection& projection,
266 EigenMatrix& covariance) const
267 {
268 return prepareWith(anchor_count, anchor_noise, joint, projection,
269 covariance, factor_execution);
270 }
271
272 bool prepareWith(Eigen::Index anchor_count,
273 const Eigen::VectorXd& anchor_noise,
274 const EigenMatrix& joint,
275 ConditionalKernelProjection& projection,
276 EigenMatrix& covariance,
277 const std::shared_ptr<linalg::DistributedState>& execution,
278 const EigenMatrix& fixed = {}) const
279 {
280 const Eigen::Index channels = anchors.cols() + 1;
281 ScopedPhaseTimer timer(PhaseTimers::factorization_seconds);
283 PhaseTimers::factorization_rows += anchor_count * channels;
284 return projection.prepare(
285 joint, fixed, anchor_count, joint.rows() / channels - anchor_count,
286 anchors.cols(), anchor_noise, covariance, execution);
287 }
288
289 bool condition(ConditionalPosterior& posterior,
290 const EigenMatrix& covariance) const
291 {
292 ScopedPhaseTimer timer(PhaseTimers::factorization_seconds);
294 PhaseTimers::factorization_rows += covariance.rows();
295 return posterior.conditionForLikelihood(covariance);
296 }
297
298 Eigen::VectorXd gradient(const ConditionalPosterior& posterior,
299 const ConditionalKernelProjection& projection,
300 const std::vector<EigenMatrix>& derivatives) const
301 {
302 ScopedPhaseTimer timer(PhaseTimers::gradient_seconds);
304 const EigenMatrix weight = projection.adjoint(
305 posterior.negativeLogLikelihoodWeight().transpose());
306 Eigen::VectorXd result(derivatives.size());
307 execution.forEach(derivatives.size(), [&](std::size_t index) {
308 result(index) =
309 0.5 * (weight.array() * derivatives[index].array()).sum();
310 });
311 return result;
312 }
313};
314
315template <typename Evaluate>
316bool improveMapStart(Eigen::VectorXd warm,
317 const funcmin::MapObjectiveConfig& config,
318 const Evaluate& evaluate, Eigen::VectorXd& theta,
319 double& value, Eigen::VectorXd& gradient)
320{
321 if (warm.size() != theta.size() || !warm.allFinite()) return false;
322 if (config.parameter_lower.size() == warm.size())
323 warm = warm.cwiseMax(config.parameter_lower);
324 if (config.parameter_upper.size() == warm.size())
325 warm = warm.cwiseMin(config.parameter_upper);
327 if (!funcmin::mapParametersInDomain(warm, config)) return false;
328 double trial = 0.0;
329 Eigen::VectorXd trial_gradient;
330 evaluate(warm, trial, trial_gradient);
331 if (std::isfinite(trial) && trial_gradient.allFinite() &&
332 (!std::isfinite(value) || trial < value)) {
333 theta = std::move(warm);
334 value = trial;
335 gradient = std::move(trial_gradient);
336 return true;
337 }
338 // The objective also owns its factorized posterior. Restore the selected
339 // point when the retained parameters do not improve the starting value.
340 evaluate(theta, value, gradient);
341 return false;
342}
343
349bool warmStartStationary(const Eigen::VectorXd& start,
350 const Eigen::VectorXd& start_gradient,
351 const Eigen::VectorXd& warm,
352 const Eigen::VectorXd& warm_gradient,
353 double tolerance_sol, double* step_out = nullptr)
354{
355 if (step_out) *step_out = std::numeric_limits<double>::infinity();
356 if (start.size() != warm.size() || start_gradient.size() != warm.size() ||
357 warm_gradient.size() != warm.size() || !start.allFinite() ||
358 !start_gradient.allFinite() || !warm.allFinite() ||
359 !warm_gradient.allFinite())
360 return false;
361 const Eigen::VectorXd s = warm - start;
362 const Eigen::VectorXd y = warm_gradient - start_gradient;
363 const double sy = s.dot(y);
364 if (!(sy > 0.0) || !std::isfinite(sy)) return false;
365 const double step = s.squaredNorm() / sy * warm_gradient.norm();
366 if (step_out) *step_out = step;
367 const double threshold = tolerance_sol * (1.0 + warm.norm());
368 return std::isfinite(step) && threshold > 0.0 && step < threshold;
369}
370
371struct ChartFitObjective {
372 ConditionalPosterior& posterior;
373 const ResidualFitConditioning& conditioning;
374 const EigenMatrix& positions;
375 std::shared_ptr<const KernelOperator> fixed_kernel;
376 std::shared_ptr<const geometry::CoordinateChart> chart;
377 double log_output_variance;
378 linalg::MpiContext communication;
379 const linalg::LocalExecutor& execution;
380 std::size_t evaluations = 0;
381 ConditionalKernelProjection projection;
382 Eigen::VectorXd cached_theta;
383 Eigen::VectorXd cached_gradient;
384 double cached_energy = std::numeric_limits<double>::quiet_NaN();
385
386 // Each cache miss owns one ActiveObjectiveTimer increment.
387 static constexpr std::size_t objective_cache_miss_work = 1;
388
389 const Eigen::VectorXd* cachedObjectiveParameters() const
390 {
391 return std::isfinite(cached_energy) && posterior.valid() ? &cached_theta
392 : nullptr;
393 }
394
395 void evaluate(const Eigen::VectorXd& theta, const EigenMatrix&,
396 const Eigen::VectorXd&, const Eigen::VectorXd&,
397 EnergyAndGradient& result)
398 {
399 // The projection and posterior belong to the most recently evaluated
400 // point. Repeated optimizer callbacks can reuse them exactly; a
401 // different point invalidates the cache before changing either state.
402 if (cached_theta.size() == theta.size() &&
403 std::isfinite(cached_energy) && posterior.valid() &&
404 (cached_theta.array() == theta.array()).all()) {
405 result.energy = cached_energy;
406 result.gradient = cached_gradient;
407 return;
408 }
409 cached_energy = std::numeric_limits<double>::quiet_NaN();
410 ActiveObjectiveTimer objective_timer(
411 positions.rows() * (positions.cols() + 1), posterior.channels());
412 ScopedPhaseTimer chart_timer(PhaseTimers::chart_objective_seconds,
413 "chart objective");
417 static_cast<long>(positions.rows() * (positions.cols() + 1)));
418 ++evaluations;
419 result.energy = std::numeric_limits<double>::infinity();
420 result.gradient = Eigen::VectorXd::Constant(
421 2, std::numeric_limits<double>::quiet_NaN());
422 const double magnitude = std::exp(theta(0) + log_output_variance);
423 const double length = std::exp(theta(1));
424 if (!theta.allFinite() || !(magnitude > 0.0) ||
425 !std::isfinite(magnitude) || !(length > 0.0) ||
426 !std::isfinite(length) || !std::isfinite(1.0 / (length * length)))
427 return;
428 auto kernel = std::make_shared<ManifoldEnergyForceKernel>(
429 chart, magnitude, length);
430 std::shared_ptr<const KernelOperator> covariance_kernel =
431 std::make_shared<Pullback>(kernel);
432 if (fixed_kernel)
433 covariance_kernel = std::make_shared<Sum>(
434 std::vector<std::shared_ptr<const KernelOperator>>{
435 fixed_kernel, covariance_kernel});
436 const Coord added = positions.bottomRows(positions.rows() -
437 conditioning.fitAnchorCount());
438 EigenMatrix covariance;
439 if (!conditioning.prepareKernel(*covariance_kernel, added, projection,
440 covariance) ||
441 !conditioning.condition(posterior, covariance))
442 return;
443 result.energy = posterior.negativeLogLikelihood();
444 covariance.resize(0, 0);
445 ScopedPhaseTimer timer(PhaseTimers::gradient_seconds);
447 const EigenMatrix conditional_weight =
448 posterior.negativeLogLikelihoodWeight().transpose();
449 // The expensive conditional adjoint follows the kernel row ownership.
450 // Each rank forms and contracts only its share of the joint weights.
451 if (dynamic_cast<const geometry::AffineCoordinateChart*>(chart.get())) {
452 const EigenMatrix weight =
453 0.5 * (conditional_weight + conditional_weight.transpose());
454 result.gradient =
455 0.5 *
456 kernel->contractJointLogHyperparameterDerivatives(
457 positions,
458 [&](Eigen::Index first, Eigen::Index count) -> EigenMatrix {
459 return projection.observationLiftRows(first, count) *
460 weight;
461 },
462 [&](Eigen::Index first, Eigen::Index count) {
463 return projection.observationLiftRows(first, count);
464 },
465 communication, execution);
466 } else {
467 result.gradient =
468 0.5 * kernel->contractJointLogHyperparameterDerivatives(
469 positions,
470 [&](Eigen::Index first, Eigen::Index count) {
471 return projection.adjointRows(conditional_weight,
472 first, count);
473 },
474 communication, execution);
475 }
476 if (std::isfinite(result.energy) && result.gradient.allFinite()) {
477 cached_theta = theta;
478 cached_gradient = result.gradient;
479 cached_energy = result.energy;
480 }
481 }
482};
483
484struct ActiveFitObjective {
485 GaussianProcessRegression& model;
486 ConditionalPosterior& posterior;
487 const TrainingKernelGeometry& geometry;
488 const Eigen::VectorXd& geometry_indices;
489 const ResidualFitConditioning& conditioning;
490 const EigenMatrix& fixed_covariance;
491 const std::vector<bool>& active;
492 Eigen::VectorXd background_theta;
493 double log_output_variance;
494 std::vector<Eigen::Index> parameters;
495 std::vector<std::vector<Eigen::Index>> parameter_groups;
496 std::size_t evaluations = 0;
497 ConditionalKernelProjection projection;
498 Eigen::VectorXd cached_parameters;
499 Eigen::VectorXd cached_gradient;
500 double cached_energy = std::numeric_limits<double>::quiet_NaN();
501
502 // Each cache miss owns one ActiveObjectiveTimer increment.
503 static constexpr std::size_t objective_cache_miss_work = 1;
504
505 const Eigen::VectorXd* cachedObjectiveParameters() const
506 {
507 return std::isfinite(cached_energy) && posterior.valid()
508 ? &cached_parameters
509 : nullptr;
510 }
511
512 void selectParameters()
513 {
514 parameters = {0};
515 parameter_groups = {{0}};
516 std::vector<Eigen::Index> groups(active.size(), -1);
517 const bool tied = model.lengthScaleTiesActive(active.size());
518 for (std::size_t i = 0; i < active.size(); ++i) {
519 if (!active[i]) continue;
520 const auto leader = tied ? model.lengthScaleTies().leader[i] : i;
521 auto& group = groups[leader];
522 if (group < 0) {
523 group = static_cast<Eigen::Index>(parameters.size());
524 parameters.push_back(static_cast<Eigen::Index>(i + 1));
525 parameter_groups.emplace_back();
526 }
527 parameter_groups[group].push_back(static_cast<Eigen::Index>(i + 1));
528 }
529 }
530
531 Eigen::VectorXd physicalParameters(const Eigen::VectorXd& reduced) const
532 {
533 Eigen::VectorXd theta = background_theta;
534 for (std::size_t i = 0; i < parameter_groups.size(); ++i)
535 for (const auto parameter: parameter_groups[i])
536 theta(parameter) = reduced(static_cast<Eigen::Index>(i));
537 theta(0) += log_output_variance;
538 return theta;
539 }
540
541 void evaluate(const Eigen::VectorXd& reduced, const EigenMatrix&,
542 const Eigen::VectorXd&, const Eigen::VectorXd&,
543 EnergyAndGradient& result)
544 {
545 if (cached_parameters.size() == reduced.size() &&
546 std::isfinite(cached_energy) && posterior.valid() &&
547 (cached_parameters.array() == reduced.array()).all()) {
548 result.energy = cached_energy;
549 result.gradient = cached_gradient;
550 return;
551 }
552 cached_energy = std::numeric_limits<double>::quiet_NaN();
553 ActiveObjectiveTimer objective_timer(geometry_indices.size(),
554 posterior.channels());
555 ScopedPhaseTimer pair_timer(PhaseTimers::pair_objective_seconds,
556 "pair objective");
560 static_cast<long>(geometry_indices.size()));
561 ++evaluations;
562 result.energy = std::numeric_limits<double>::infinity();
563 result.gradient = Eigen::VectorXd::Constant(
564 reduced.size(), std::numeric_limits<double>::quiet_NaN());
565 const Eigen::VectorXd theta = physicalParameters(reduced);
566 const auto assemble = [&](EigenMatrix& covariance) {
567 ScopedPhaseTimer timer(PhaseTimers::assembly_seconds);
568 ScopedPhaseTimer pair_timer(PhaseTimers::pair_covariance_seconds,
569 "pair covariance");
570 return model.evaluateActiveCovarianceFromGeometry(
571 geometry, geometry_indices, theta, active, covariance, false);
572 };
573 EigenMatrix covariance;
574 if (!assemble(covariance)) return;
575 if (fixed_covariance.size()) covariance += fixed_covariance;
576 EigenMatrix projected_covariance;
577 if (!conditioning.prepare(covariance, projection,
578 projected_covariance) ||
579 !conditioning.condition(posterior, projected_covariance))
580 return;
581 ScopedPhaseTimer gradient_timer(PhaseTimers::gradient_seconds);
583 const EigenMatrix weight = projection.adjoint(
584 posterior.negativeLogLikelihoodWeight().transpose());
585 covariance.resize(0, 0);
586 std::vector<Eigen::Index> selected;
587 for (std::size_t i = 1; i < parameter_groups.size(); ++i)
588 selected.insert(selected.end(), parameter_groups[i].begin(),
589 parameter_groups[i].end());
590 Eigen::VectorXd products;
591 {
592 ScopedPhaseTimer timer(PhaseTimers::assembly_seconds);
593 ScopedPhaseTimer contraction_timer(
594 PhaseTimers::pair_contraction_seconds, "pair contraction");
595 if (!model.contractActiveCovarianceDerivatives(
596 geometry, geometry_indices, theta, active, weight, selected,
597 products))
598 return;
599 }
600 // Each independent log length moves every active member of its
601 // chemical tie group. The chain rule sums their fine derivatives;
602 // the MAP prior is applied once per independent parameter.
603 result.gradient.setZero(reduced.size());
604 Eigen::Index product = 0;
605 for (std::size_t i = 0; i < parameter_groups.size(); ++i)
606 for (std::size_t j = 0; j < parameter_groups[i].size(); ++j)
607 result.gradient(static_cast<Eigen::Index>(i)) +=
608 0.5 * products(product++);
609 result.energy = posterior.negativeLogLikelihood();
610 if (std::isfinite(result.energy) && result.gradient.allFinite()) {
611 cached_parameters = reduced;
612 cached_gradient = result.gradient;
613 cached_energy = result.energy;
614 }
615 }
616};
617
621struct AdditivePairFitObjective {
622 ConditionalPosterior& posterior;
623 const ResidualFitConditioning& conditioning;
624 const std::vector<AdditivePairKernel::PairFeatures>& features;
625 const std::vector<AdditivePairKernel::Pair>& pairs;
626 Eigen::Index dimensions;
627 Eigen::Index length_count;
628 const EigenMatrix& fixed_covariance;
629 std::vector<Eigen::Index> types;
630 double log_output_variance;
631 linalg::MpiContext communication;
632 const linalg::LocalExecutor& execution;
633 std::size_t evaluations = 0;
634 ConditionalKernelProjection projection;
635 Eigen::VectorXd lengths(const Eigen::VectorXd& theta) const
636 {
637 Eigen::VectorXd result = Eigen::VectorXd::Ones(length_count);
638 for (std::size_t index = 0; index < types.size(); ++index)
639 result(types[index]) =
640 std::exp(theta(static_cast<Eigen::Index>(index) + 1));
641 return result;
642 }
643 void evaluate(const Eigen::VectorXd& theta, const EigenMatrix&,
644 const Eigen::VectorXd&, const Eigen::VectorXd&,
645 EnergyAndGradient& result)
646 {
647 ActiveObjectiveTimer objective_timer(
648 static_cast<Eigen::Index>(features.size()) * (dimensions + 1),
649 posterior.channels());
650 ++evaluations;
651 result.energy = std::numeric_limits<double>::infinity();
652 result.gradient = Eigen::VectorXd::Constant(
653 theta.size(), std::numeric_limits<double>::quiet_NaN());
654 if (!theta.allFinite()) return;
655 const double magnitude = std::exp(theta(0) + log_output_variance);
656 const Eigen::VectorXd scales = lengths(theta);
657 if (!(magnitude > 0.0) || !std::isfinite(magnitude) ||
658 !scales.allFinite() || !(scales.array() > 0.0).all())
659 return;
660 const EigenMatrix joint = [&] {
661 ScopedPhaseTimer assembly_timer(PhaseTimers::assembly_seconds);
663 features, pairs, dimensions, scales, magnitude, {},
664 communication, execution)
665 .front();
666 }();
667 EigenMatrix covariance;
668 if (!conditioning.prepare(joint, projection, covariance,
669 fixed_covariance) ||
670 !conditioning.condition(posterior, covariance))
671 return;
672 result.energy = posterior.negativeLogLikelihood();
673 ScopedPhaseTimer gradient_timer(PhaseTimers::gradient_seconds);
675 const EigenMatrix weight = projection.adjoint(
676 posterior.negativeLogLikelihoodWeight().transpose());
677 result.gradient =
679 features, pairs, dimensions, scales, magnitude, types,
680 weight, communication, execution);
681 }
682};
683
684#if defined(GPR_USE_FEATOMIC)
685struct EnvironmentFitObjective {
686 ConditionalPosterior& posterior;
687 const ResidualFitConditioning& conditioning;
688 const std::vector<AtomicEnvironments>& environments;
689 const EigenMatrix& fixed_pair_covariance;
694 const std::vector<Eigen::Index>& inducing;
695 std::vector<int> species;
696 double log_output_variance;
697 linalg::MpiContext communication;
698 const linalg::LocalExecutor& execution;
699 std::shared_ptr<const linalg::EnvironmentGpuExecutor> device;
700 std::size_t evaluations = 0;
701 ConditionalKernelProjection projection;
702
703 SpeciesEnvironmentKernel::LengthScales lengths(
704 const Eigen::VectorXd& theta) const
705 {
706 SpeciesEnvironmentKernel::LengthScales result;
707 for (std::size_t index = 0; index < species.size(); ++index)
708 result[species[index]] = std::exp(theta(index + 1));
709 return result;
710 }
711
712 void evaluate(const Eigen::VectorXd& theta, const EigenMatrix&,
713 const Eigen::VectorXd&, const Eigen::VectorXd&,
714 EnergyAndGradient& result)
715 {
716 ActiveObjectiveTimer objective_timer(
717 static_cast<Eigen::Index>(environments.size()) *
718 (conditioning.anchors.cols() + 1),
719 posterior.channels());
720 ++evaluations;
721 result.energy = std::numeric_limits<double>::infinity();
722 result.gradient = Eigen::VectorXd::Constant(
723 theta.size(), std::numeric_limits<double>::quiet_NaN());
724 const double magnitude = std::exp(theta(0) + log_output_variance);
725 const auto scales = lengths(theta);
726 if (!theta.allFinite() || !(magnitude > 0.0) ||
727 !std::isfinite(magnitude))
728 return;
729 for (const auto& [number, length]: scales)
730 if (!(length > 0.0) || !std::isfinite(length) ||
731 !std::isfinite(1.0 / (length * length)))
732 return;
733 const auto derivatives = [&] {
734 ScopedPhaseTimer assembly_timer(PhaseTimers::assembly_seconds);
735 return SpeciesEnvironmentKernel::
736 sparseJointWithLogLengthDerivatives(
737 environments, inducing, scales, magnitude, species,
738 communication, execution, device);
739 }();
740 EigenMatrix covariance;
741 if (!conditioning.prepare(derivatives.front(), projection, covariance,
742 fixed_pair_covariance) ||
743 !conditioning.condition(posterior, covariance))
744 return;
745 result.energy = posterior.negativeLogLikelihood();
746 result.gradient =
747 conditioning.gradient(posterior, projection, derivatives);
748 }
749};
750
755SpeciesEnvironmentKernel::LengthScales environmentSpacingFloors(
756 const std::vector<AtomicEnvironments>& environments)
757{
758 std::map<int, std::vector<Eigen::VectorXd>> rows;
759 for (const auto& environment: environments)
760 for (Eigen::Index atom = 0; atom < environment.values.rows(); ++atom)
761 rows[environment.atomic_numbers[atom]].push_back(
762 environment.values.row(atom).transpose());
764 for (const auto& [number, values]: rows) {
765 double spacing = std::numeric_limits<double>::infinity();
766 for (std::size_t i = 0; i < values.size(); ++i)
767 for (std::size_t j = i + 1; j < values.size(); ++j) {
768 const double d = (values[i] - values[j]).norm();
769 if (d > 0.0) spacing = std::min(spacing, d);
770 }
771 floors[number] = std::isfinite(spacing) ? spacing : 0.0;
772 }
773 return floors;
774}
775
776SpeciesEnvironmentKernel::LengthScales environmentMotionScales(
777 const std::vector<AtomicEnvironments>& environments)
778{
779 struct Moment {
780 Eigen::VectorXd mean;
781 double squared_deviation = 0.0;
782 std::size_t count = 0;
783 };
784 std::map<int, Moment> moments;
785 for (const auto& environment: environments) {
786 for (Eigen::Index atom = 0; atom < environment.values.rows(); ++atom) {
787 auto& moment = moments[environment.atomic_numbers[atom]];
788 const Eigen::VectorXd value =
789 environment.values.row(atom).transpose();
790 if (moment.count++ == 0) {
791 moment.mean = value;
792 } else {
793 const Eigen::VectorXd difference = value - moment.mean;
794 moment.mean += difference / static_cast<double>(moment.count);
795 moment.squared_deviation += difference.dot(value - moment.mean);
796 }
797 }
798 }
800 for (const auto& [number, moment]: moments) {
801 const double variance = moment.squared_deviation / moment.count;
802 scales[number] = variance > 0.0 ? std::sqrt(2.0 * variance) : 1.0;
803 }
804 return scales;
805}
806#endif
807
808void subtractCholeskyCross(linalg::BackendContext& execution,
809 const EigenMatrix& factor, const EigenMatrix& left,
810 const EigenMatrix& right, EigenMatrix& covariance)
811{
812 if (right.cols() < left.cols()) {
813 EigenMatrix solved = execution.forward_solve_mat(factor, right);
814 solved = execution.back_solve_mat(factor, solved);
815 covariance.noalias() -= left.transpose() * solved;
816 } else if (left.cols() < right.cols()) {
817 EigenMatrix solved = execution.forward_solve_mat(factor, left);
818 solved = execution.back_solve_mat(factor, solved);
819 covariance.noalias() -= solved.transpose() * right;
820 } else {
821 EigenMatrix joined(left.rows(), left.cols() + right.cols());
822 joined.leftCols(left.cols()) = left;
823 joined.rightCols(right.cols()) = right;
824 const EigenMatrix solved = execution.forward_solve_mat(factor, joined);
825 covariance.noalias() -= solved.leftCols(left.cols()).transpose() *
826 solved.rightCols(right.cols());
827 }
828}
829
830} // namespace
831
835 std::vector<int> background_subset_ids;
836 std::shared_ptr<const KernelOperator> kernel;
837 std::shared_ptr<const SpeciesEnvironmentKernel> environment_kernel;
838 std::shared_ptr<const ManifoldEnergyForceKernel> cartesian_kernel;
839 std::shared_ptr<const AdditivePairKernel> additive_kernel;
840 bool includes_pair = true;
841 std::string kernel_name = "pair";
843 ResidualFitConditioning conditioning;
845 Eigen::VectorXd fitted_lengths;
846 Eigen::VectorXd fitted_theta;
848 Eigen::VectorXd mean_weights;
858 // True when the residual kernel implements a Hessian. A kernel whose
859 // contraction is the unsupported default is not a refusal: the
860 // Cartesian difference of the dispatched mean remains the derivative.
861 // Written again when a Hessian is requested. The stored posterior is
862 // const, so the deferred probe updates these through that const view.
863 // Copies of the model share this state, so the probe runs once under
864 // residual_hessian_probe_once; the flags are read only after it returns.
865 mutable bool residual_hessian_analytic = false;
866 // The meanHessianVector probe is deferred until a Hessian is requested.
867 // Conditioning must not evaluate chart curvature.
869 mutable std::once_flag residual_hessian_probe_once;
870 // A chart without directionalJacobian refuses the product; it is not
871 // left for the Cartesian difference. The kernel and its components fix
872 // this, so it is read from them and never recorded.
873 [[nodiscard]] bool residualCurvatureRefused() const noexcept
874 {
875 return kernel && kernel->meanCurvature() ==
877 }
884 bool hssvd;
885
887 std::shared_ptr<const KernelOperator> active_kernel,
889 LaplacePosteriorStamp background_stamp, double mean,
890 double scale, bool use_hssvd)
891 : observations(std::move(data)),
892 kernel(std::move(active_kernel)),
893 posterior(std::move(fitted)),
894 background(std::move(background_stamp)),
895 output_mean(mean),
896 output_scale(scale),
897 hssvd(use_hssvd)
898 {
899 }
900};
901
907
910{
912 if (active_posterior_) {
913 point.state_ = std::make_shared<ActivePosteriorRestorePoint::State>(
914 ActivePosteriorRestorePoint::State{this, full_fit_observations_,
915 active_posterior_});
916 }
917 return point;
918}
919
921 const ActivePosteriorRestorePoint& point,
922 const Observation& full_observation)
923{
924 if (!point.state_) return false;
925 const auto& saved = *point.state_;
926 if (saved.owner != this || saved.posterior->output_mean != y_mean_ ||
927 saved.posterior->output_scale != y_scale_ ||
928 saved.posterior->hssvd != use_hssvd_backend_ ||
929 !hasFullFitPrefix(full_observation, saved.background)) {
930 throw std::invalid_argument(
931 "active posterior restoration requires its owning model, output "
932 "coordinates, and full-fit prefix");
933 }
934 updateModelWithFullData(saved.background);
935 if (!reconditionActivePosterior(full_observation, *saved.posterior)) {
936 throw std::runtime_error(
937 "retained active posterior could not be conditioned");
938 }
939 return true;
940}
941
943{
944#if !defined(GPR_USE_FEATOMIC)
945 if (enabled)
946 throw std::invalid_argument(
947 "environment residual fitting requires featomic and rgmin");
948#endif
949 if (enabled != environment_residuals_) {
950 active_posterior_.reset();
951 active_kernel_evidence_.clear();
952 ++factor_epoch_;
953 }
954 environment_residuals_ = enabled;
955 if (enabled) active_posterior_refits_ = true;
956}
957
959 const noexcept
960{
961 return active_posterior_ ? active_posterior_->observations.R.rows() : 0;
962}
963
964std::shared_ptr<const KernelOperator>
966 const Eigen::VectorXd& theta, const std::vector<bool>& active_lengths) const
967{
968 if (!sexpat_cov_func || sexpat_cov_func->usesManifoldChart() ||
969 theta.size() != sexpat_cov_func->getLengthScaleRef().size() + 1 ||
970 active_lengths.size() + 1 != static_cast<std::size_t>(theta.size()) ||
971 !theta.allFinite())
972 throw std::invalid_argument("invalid active pair-kernel parameters");
973 for (Eigen::Index i = 0; i < theta.size(); ++i) {
974 if (i > 0 && !active_lengths[static_cast<std::size_t>(i - 1)]) continue;
975 const double value = std::exp(theta(i));
976 if (!(value > 0.0) || !std::isfinite(value))
977 throw std::invalid_argument("invalid active pair-kernel scale");
978 }
979 auto primitive = std::make_shared<SexpatCF>(*sexpat_cov_func);
980 primitive->clearDistanceCache();
981 primitive->setParameters(theta);
982 for (std::size_t i = 0; i < active_lengths.size(); ++i)
983 if (!active_lengths[i])
984 primitive->getLengthScaleRef().data()[i] =
985 std::numeric_limits<double>::infinity();
986 return std::make_shared<Sexpat>(std::move(primitive));
987}
988
989void GaussianProcessRegression::requireActivePosteriorBackground() const
990{
991 if (!active_posterior_ || !is_decomposed_succesfully ||
992 uncertainty_mode_ != UncertaintyMode::MAP ||
993 !active_posterior_->background.matches(
994 currentLaplacePosteriorStamp()) ||
995 active_posterior_->output_mean != y_mean_ ||
996 active_posterior_->output_scale != y_scale_ ||
997 active_posterior_->hssvd != use_hssvd_backend_)
998 throw std::logic_error(
999 "active posterior requires its unchanged fitted background");
1000}
1001
1002std::shared_ptr<GaussianProcessRegression::ActivePosteriorState>
1003GaussianProcessRegression::prepareActivePosterior(
1004 const Observation& full_observation)
1005{
1006 detail::requireJointTrainingObservation(
1007 full_observation,
1008 "GaussianProcessRegression::conditionActivePosterior");
1009 if (!canConditionActivePosterior(full_observation)) return {};
1010
1011 const Eigen::Index n =
1012 full_observation.R.rows() - full_fit_observations_.R.rows();
1013 Observation added;
1014 added.R = full_observation.R.bottomRows(n);
1015 added.G = full_observation.G.bottomRows(n);
1016 added.E = Eigen::Map<const Eigen::VectorXd>(full_observation.E.data(),
1017 full_observation.E.size())
1018 .tail(n);
1019 std::vector<int> background_subset_ids;
1020 if (!canUseHssvdVariance() && hasTrainingCholeskyFactor(R_matrix.rows()) &&
1021 prepareVarianceSubset(added.R))
1022 background_subset_ids = variance_subset_ids_;
1023 Eigen::VectorXd background_mean;
1024 EigenMatrix background_covariance;
1025 const auto retained = active_posterior_;
1026 const Eigen::Index prefix = retained ? retained->observations.R.rows() : 0;
1027 const bool extend_background =
1028 prefix > 0 && prefix <= n && hssvd_local_active_set_size_ <= 0 &&
1029 variance_subset_configurations_ <= 0 &&
1030 variance_subset_forced_ids_.empty() && !variance_subset_footprint_ &&
1031 retained->background_subset_ids.empty() &&
1032 retained->observation_background_mean.size() ==
1033 prefix * (added.R.cols() + 1) &&
1034 retained->observations.R.cols() == added.R.cols() &&
1035 (retained->observations.R.array() == added.R.topRows(prefix).array())
1036 .all();
1037 if (extend_background) {
1038 // canConditionActivePosterior fixes the background parameter frame.
1039 // Its covariance and mean on a retained geometry therefore stay
1040 // unchanged as the independent correction acquires observations.
1041 const Eigen::Index channels = added.R.cols() + 1;
1042 const Eigen::Index appended = n - prefix;
1043 const Eigen::VectorXd& prefix_mean =
1044 retained->observation_background_mean;
1045 if (appended == 0) {
1046 background_mean = prefix_mean;
1047 background_covariance = retained->posterior.backgroundCovariance();
1048 } else {
1049 Observation new_mean;
1050 new_mean.R = added.R.bottomRows(appended);
1051 calculateBackgroundPotentialDispatched(new_mean);
1052 const Eigen::VectorXd new_mean_channels =
1053 observationChannels(new_mean);
1054 EigenMatrix cross, diagonal;
1056 retained->observations.R, new_mean.R, cross);
1057 calculateBackgroundObservationPosteriorCovariance(new_mean.R,
1058 diagonal, false);
1059 background_mean.resize(n * channels);
1060 background_covariance.resize(n * channels, n * channels);
1061 const auto& previous = retained->posterior.backgroundCovariance();
1062 for (Eigen::Index left = 0; left < channels; ++left) {
1063 background_mean.segment(left * n, prefix) =
1064 prefix_mean.segment(left * prefix, prefix);
1065 background_mean.segment(left * n + prefix, appended) =
1066 new_mean_channels.segment(left * appended, appended);
1067 for (Eigen::Index right = 0; right < channels; ++right) {
1068 background_covariance.block(left * n, right * n, prefix,
1069 prefix) =
1070 previous.block(left * prefix, right * prefix, prefix,
1071 prefix);
1072 background_covariance.block(left * n, right * n + prefix,
1073 prefix, appended) =
1074 cross.block(left * prefix, right * appended, prefix,
1075 appended);
1076 background_covariance.block(left * n + prefix, right * n,
1077 appended, prefix) =
1078 cross
1079 .block(right * prefix, left * appended, prefix,
1080 appended)
1081 .transpose();
1082 background_covariance.block(left * n + prefix,
1083 right * n + prefix, appended,
1084 appended) =
1085 diagonal.block(left * appended, right * appended,
1086 appended, appended);
1087 }
1088 }
1089 }
1090 } else {
1091 Observation mean;
1092 mean.R = added.R;
1093 calculateBackgroundPotentialDispatched(mean);
1094 background_mean = observationChannels(mean);
1095 calculateBackgroundObservationPosteriorCovariance(
1096 added.R, background_covariance, false);
1097 }
1098
1099 Eigen::VectorXd physical_noise = calculateObservationNoiseDiagonal(added.R);
1100 std::shared_ptr<linalg::DistributedState> factor_execution;
1101#ifdef GPR_LINALG_SCALAPACK
1102 auto& background_execution = backend().distributed();
1103 factor_execution = std::make_shared<linalg::DistributedState>(
1104 background_execution.communication());
1105 factor_execution->configure(background_execution.block_size(),
1106 background_execution.nprow());
1107#endif
1108 ConditionalPosterior posterior(std::move(background_covariance),
1109 observationChannels(added) - background_mean,
1110 std::move(physical_noise), factor_execution);
1111 auto state = std::make_shared<ActivePosteriorState>(
1112 std::move(added), nullptr, std::move(posterior),
1113 currentLaplacePosteriorStamp(), y_mean_, y_scale_, use_hssvd_backend_);
1114 state->observation_background_mean = std::move(background_mean);
1115 state->background_subset_ids = std::move(background_subset_ids);
1116 state->conditioning.factor_execution = std::move(factor_execution);
1117 return state;
1118}
1119
1120void GaussianProcessRegression::advanceActivePosteriorEpoch()
1121{
1122 requireActivePosteriorBackground();
1123 // Conditioning the active correction leaves the fitted background and
1124 // its subset covariance unchanged. Preserve only a factor that belongs
1125 // to that background; selection changes still miss the subset-ID key.
1126 if (variance_subset_epoch_ == factor_epoch_) ++variance_subset_epoch_;
1127 ++factor_epoch_;
1128}
1129
1130bool GaussianProcessRegression::canConditionActivePosterior(
1131 const Observation& full_observation) const
1132{
1133 if (atomic_environment_model_) return false;
1135 uncertainty_mode_ != UncertaintyMode::MAP || rff_replaces_exact_ ||
1136 !lik_gaussian ||
1137 !hasFullFitPrefix(full_observation, full_fit_observations_))
1138 return false;
1139 return !active_posterior_ ||
1140 (active_posterior_->background.matches(
1141 currentLaplacePosteriorStamp()) &&
1142 active_posterior_->output_mean == y_mean_ &&
1143 active_posterior_->output_scale == y_scale_ &&
1144 active_posterior_->hssvd == use_hssvd_backend_);
1145}
1146
1148 const Observation& full_observation,
1149 std::shared_ptr<const KernelOperator> active_kernel)
1150{
1151 auto state = prepareActivePosterior(full_observation);
1152 if (!state) return false;
1153 const Eigen::Index n = state->posterior.channels();
1154 EigenMatrix active = EigenMatrix::Zero(n, n);
1155 if (active_kernel)
1156 active =
1157 active_kernel->jointEnergyGradientCovariance(state->observations.R);
1158 if (!state->posterior.condition(active)) return false;
1159 state->kernel = std::move(active_kernel);
1160 state->includes_pair = false;
1161 state->kernel_name = state->kernel ? "fixed" : "background";
1162 prepareActivePosteriorMeanExpansion(*state);
1163 active_posterior_ = std::move(state);
1164 advanceActivePosteriorEpoch();
1165 return true;
1166}
1167
1169 const Observation& full_observation,
1170 const std::vector<bool>& active_lengths, bool compare_cartesian_residual)
1171{
1172 return fitActivePosteriorImpl(full_observation, active_lengths,
1173 compare_cartesian_residual, true);
1174}
1175
1176std::vector<Eigen::Index> GaussianProcessRegression::selectActiveFitAnchors(
1177 const Coord& added, const Coord& anchors,
1178 const std::vector<bool>& active_lengths) const
1179{
1180 // The background fits its hyperparameters on fps_options.history rows;
1181 // the correction fits on as many anchors, the ones nearest the added
1182 // rows in the pair-distance metric of the current length scales (the
1183 // metric the admission rules use). Fewer anchors than that keep every
1184 // anchor, which leaves the small fixtures and the early outers exactly
1185 // as before.
1186 (void)active_lengths;
1187 std::vector<Eigen::Index> selected;
1188 const Eigen::Index limit = static_cast<Eigen::Index>(std::max(
1189 1, std::min(fps_options.history, std::numeric_limits<int>::max() / 2)));
1190 if (anchors.rows() <= limit || added.rows() <= 0 || !sexpat_cov_func)
1191 return selected;
1192 aux::Distance distance;
1193 FieldMatrixd dist;
1194 distance.dist_at(added, anchors, atoms_config,
1195 sexpat_cov_func->getLengthScaleRef(), dist);
1196 if (dist.rows() != added.rows() || dist.cols() != anchors.rows() ||
1197 !dist.allFinite())
1198 return selected;
1199 const Eigen::VectorXd score = dist.colwise().minCoeff();
1200 std::vector<Eigen::Index> order(static_cast<std::size_t>(anchors.rows()));
1201 std::iota(order.begin(), order.end(), Eigen::Index{0});
1202 std::stable_sort(
1203 order.begin(), order.end(),
1204 [&](Eigen::Index a, Eigen::Index b) { return score(a) < score(b); });
1205 selected.assign(order.begin(), order.begin() + limit);
1206 std::sort(selected.begin(), selected.end());
1207 return selected;
1208}
1209
1210bool GaussianProcessRegression::fitActivePosteriorImpl(
1211 const Observation& full_observation,
1212 const std::vector<bool>& active_lengths, bool compare_cartesian_residual,
1213 bool select_components)
1214{
1215 // The residual is conditioned near zero at the background's measured
1216 // rows, then fitted to the added observations with the background fixed.
1217 ScopedPhaseTimer correction_timer(PhaseTimers::correction_seconds);
1218 // Phase accumulators at entry; the fit reports their growth.
1219 const auto fit_started = std::chrono::steady_clock::now();
1220 const double entry_objective = PhaseTimers::objective_seconds;
1221 const double entry_assembly = PhaseTimers::assembly_seconds;
1222 const double entry_gradient = PhaseTimers::gradient_seconds;
1223 const double entry_pair = PhaseTimers::pair_objective_seconds;
1224 const double entry_chart = PhaseTimers::chart_objective_seconds;
1225 const double entry_support = PhaseTimers::support_seconds;
1226 const double entry_support_refit = PhaseTimers::support_refit_seconds;
1227 const double entry_factor = PhaseTimers::projection_factor_seconds;
1228 const double entry_solve = PhaseTimers::projection_solve_seconds;
1229 const double entry_residual = PhaseTimers::residual_seconds;
1230 const int entry_evaluations = PhaseTimers::objective_count;
1231 active_kernel_evidence_.clear();
1232 if (!sexpat_cov_func || sexpat_cov_func->usesManifoldChart() ||
1233 active_lengths.size() !=
1234 static_cast<std::size_t>(
1235 sexpat_cov_func->getLengthScaleRef().size()) ||
1236 std::none_of(active_lengths.begin(), active_lengths.end(),
1237 [](bool active) { return active; }))
1238 return false;
1239 // Trusted updates optimize the active pair parameters inside the selected
1240 // model. Other components retain their fitted parameters. A model without
1241 // a pair component only needs conditioning on the extended suffix.
1242 const bool retain_components = !select_components && active_posterior_;
1243 if (retain_components && !active_posterior_->includes_pair) {
1244 if (!refreshActivePosterior(full_observation)) return false;
1245 active_kernel_evidence_.push_back(
1246 {active_posterior_->kernel_name,
1247 active_posterior_->posterior.negativeLogLikelihood(),
1248 active_posterior_->posterior.negativeLogLeaveOneGeometryOut(
1249 active_posterior_->observations.R.rows()),
1250 false, true});
1251 failedOptimizer = false;
1252 return true;
1253 }
1254 auto state = prepareActivePosterior(full_observation);
1255 if (!state) return false;
1256
1257 EigenMatrix rows;
1258 Eigen::VectorXd indices;
1259 aux::AuxiliaryFunctionality{}.assembleMatrixOfRepetitiveCoordinates(
1260 state->observations.R, rows, indices);
1261 state->conditioning.anchors = full_fit_observations_.R;
1262 state->conditioning.execution = backend().local();
1263 EigenMatrix anchor_rows;
1264 Eigen::VectorXd anchor_indices;
1265 aux::AuxiliaryFunctionality{}.assembleMatrixOfRepetitiveCoordinates(
1266 state->conditioning.anchors, anchor_rows, anchor_indices);
1267 state->conditioning.noise = likelihoodDiagonal(anchor_rows);
1268 state->conditioning.noise.array() += jitter_sigma2;
1269 state->conditioning.noise *= outputVarianceScaleSquared();
1270 state->conditioning.fit_anchor_rows = selectActiveFitAnchors(
1271 state->observations.R, state->conditioning.anchors, active_lengths);
1272 last_active_fit_anchor_count_ = state->conditioning.fitAnchorCount();
1273 EigenMatrix fit_rows;
1274 Eigen::VectorXd fit_indices;
1275 aux::AuxiliaryFunctionality{}.assembleMatrixOfRepetitiveCoordinates(
1276 state->conditioning.positions(state->observations.R), fit_rows,
1277 fit_indices);
1278 TrainingKernelGeometry geometry;
1279 if (!prepareTrainingKernelGeometry(fit_rows, fit_indices, geometry))
1280 return false;
1281 std::vector<std::shared_ptr<const KernelOperator>> retained_components;
1282 EigenMatrix fixed_covariance;
1283 if (retain_components) {
1284 state->environment_kernel = active_posterior_->environment_kernel;
1285 state->cartesian_kernel = active_posterior_->cartesian_kernel;
1286 state->additive_kernel = active_posterior_->additive_kernel;
1287 state->kernel_name = active_posterior_->kernel_name;
1288 if (state->environment_kernel)
1289 retained_components.push_back(state->environment_kernel);
1290 if (state->cartesian_kernel)
1291 retained_components.push_back(
1292 std::make_shared<Pullback>(state->cartesian_kernel));
1293 if (state->additive_kernel)
1294 retained_components.push_back(state->additive_kernel);
1295 if (!retained_components.empty()) {
1296 ScopedPhaseTimer timer(PhaseTimers::assembly_seconds);
1297 fixed_covariance =
1298 Sum(retained_components)
1299 .jointEnergyGradientCovariance(
1300 state->conditioning.positions(state->observations.R));
1301 }
1302 }
1303 ActiveFitObjective objective{*this,
1304 state->posterior,
1305 geometry,
1306 fit_indices,
1307 state->conditioning,
1308 fixed_covariance,
1309 active_lengths,
1310 sexpat_cov_func->combineParameters(),
1311 std::log(outputVarianceScaleSquared())};
1312 objective.selectParameters();
1313 Eigen::VectorXd reduced(objective.parameters.size());
1314 for (Eigen::Index i = 0; i < reduced.size(); ++i)
1315 reduced(i) = objective.background_theta(
1316 objective.parameters[static_cast<std::size_t>(i)]);
1317
1318 // MAP amplitudes use the background's training units. The likelihood
1319 // uses physical units; its constant Jacobian does not alter the gradient.
1320 const Eigen::VectorXd targets = state->posterior.residual() / y_scale_;
1321 Eigen::VectorXd rho0(reduced.size() - 1);
1322 for (Eigen::Index i = 1; i < reduced.size(); ++i)
1323 rho0(i - 1) = std::exp(reduced(i));
1324 ScgOptimizationSettings settings = scg_opt_settings;
1325 settings.active_parameters.clear();
1326 settings.use_tail_lower_barrier = false;
1327 const double strength = 1e-4 + 1e-3 * state->observations.R.rows();
1328 auto config = funcmin::makeMapObjectiveConfig(rows, targets, reduced,
1329 strength, rho0, settings);
1330 Eigen::VectorXd lower = Eigen::VectorXd::Constant(
1331 reduced.size(), -std::numeric_limits<double>::infinity());
1332 Eigen::VectorXd upper = -lower;
1333 aux::Distance distance;
1334 FieldMatrixd distances;
1335 distance.dist_at(state->observations.R, state->observations.R, atoms_config,
1336 FieldMatrixd::Ones(1, 1), distances);
1337 if (!distances.allFinite()) return false;
1338 const double floor = lengthscaleProjectionFloor(
1339 distances.size() ? distances.maxCoeff() : 0.0, lengthscale_floor_);
1340 if (floor > 0.0 && std::isfinite(floor))
1341 lower.tail(reduced.size() - 1).setConstant(std::log(floor));
1342 reduced = reduced.cwiseMax(lower);
1343 config.parameter_lower = lower;
1344 config.parameter_upper = upper;
1346 const auto evaluate_map = [&](const Eigen::VectorXd& point, double& value,
1347 Eigen::VectorXd& gradient) {
1348 EnergyAndGradient result(value, gradient);
1349 objective.evaluate(point, rows, indices, targets, result);
1350 funcmin::applyMapPenalty(point, config, value, &gradient);
1351 };
1352 double initial_value = 0.0;
1353 Eigen::VectorXd gradient;
1354 evaluate_map(reduced, initial_value, gradient);
1355 if (!std::isfinite(initial_value) || !gradient.allFinite()) return false;
1356 const double default_initial_value = initial_value;
1357 const Eigen::VectorXd background_start = reduced;
1358 const Eigen::VectorXd background_gradient = gradient;
1359 bool warm_start_used = false;
1360
1361 // The correction kernel is refitted on every outer against the same
1362 // frozen background with a superset of the corrected observations, so
1363 // the previous fit's optimum is the warm start of that objective. The
1364 // background parameters remain the start whenever they sit lower; the
1365 // comparison costs one objective evaluation.
1366 if (active_posterior_ && active_posterior_->fitted_theta.size() ==
1367 objective.background_theta.size()) {
1368 Eigen::VectorXd warm = reduced;
1369 for (Eigen::Index i = 0; i < warm.size(); ++i) {
1370 const double value = active_posterior_->fitted_theta(
1371 objective.parameters[static_cast<std::size_t>(i)]);
1372 if (std::isfinite(value))
1373 warm(i) =
1374 i == 0 ? value - objective.log_output_variance : value;
1375 }
1376 warm = warm.cwiseMax(lower);
1378 double warm_value = 0.0;
1379 Eigen::VectorXd warm_gradient;
1380 evaluate_map(warm, warm_value, warm_gradient);
1381 if (std::isfinite(warm_value) && warm_gradient.allFinite() &&
1382 warm_value < initial_value) {
1383 reduced = warm;
1384 initial_value = warm_value;
1385 gradient = warm_gradient;
1386 warm_start_used = true;
1387 }
1388 }
1389
1390 active_fit_start_for_testing_ = initial_value;
1391
1392 // The two evaluations already made, at the background parameters and
1393 // at the warm start, are a secant of this objective. Its
1394 // Barzilai-Borwein scale gives the step the optimizer would take
1395 // first; when that step is below the optimizer's own solution
1396 // tolerance, its stopping rule would end the fit after that step, so
1397 // the fit is skipped and the warm start is conditioned as it stands
1398 // (scripts/derive_bb_stationarity.py).
1399 double secant_step = std::numeric_limits<double>::infinity();
1400 const bool stationary_warm_start =
1401 warm_start_used &&
1402 warmStartStationary(background_start, background_gradient, reduced,
1403 gradient, settings.common.tolerance_sol,
1404 &secant_step);
1405 if (report_level >= 1 && stationary_warm_start)
1406 log_man << "Active correction: warm start stationary (secant step "
1407 << secant_step << "); conditioning without a fit.\n";
1408
1409 funcmin::RgminOpt optimizer;
1410 optimizer.setBox(lower, upper);
1411 optimizer.setMethod(rgmin_method_set_
1412 ? static_cast<rgmin_method_t>(rgmin_method_)
1413 : RGMIN_LBFGS);
1414 optimizer.setAlgorithmSettings(settings);
1415 const Eigen::VectorXd initial_reduced = reduced;
1416 if (!stationary_warm_start)
1417 optimizer.optimize(rows, indices, targets, reduced,
1418 &ActiveFitObjective::evaluate, objective, strength,
1419 rho0, &config);
1420 bool pair_optimized = stationary_warm_start || !optimizer.failedOptim;
1421 double value = initial_value;
1422 // The posterior is conditioned at the last evaluated point: the warm
1423 // start when the fit was skipped.
1424 if (!stationary_warm_start) evaluate_map(reduced, value, gradient);
1425 if (!std::isfinite(value) || !gradient.allFinite() ||
1426 value > initial_value || !state->posterior.valid()) {
1427 pair_optimized = false;
1428 reduced = initial_reduced;
1429 evaluate_map(reduced, value, gradient);
1430 }
1431 if (!state->posterior.valid()) return false;
1432 state->posterior.prepareLocalPrediction();
1433 state->kernel_projection = std::move(objective.projection);
1434 state->kernel = makeActiveCovarianceOperator(
1435 objective.physicalParameters(reduced), active_lengths);
1436 if (!retained_components.empty()) {
1437 retained_components.insert(retained_components.begin(), state->kernel);
1438 state->kernel = std::make_shared<Sum>(std::move(retained_components));
1439 }
1440 state->fitted_theta = objective.physicalParameters(reduced);
1441 state->fitted_lengths =
1442 state->fitted_theta.tail(active_lengths.size()).array().exp();
1443 for (std::size_t i = 0; i < active_lengths.size(); ++i)
1444 if (!active_lengths[i])
1445 state->fitted_lengths(static_cast<Eigen::Index>(i)) =
1446 std::numeric_limits<double>::infinity();
1447 active_kernel_evidence_.push_back(
1448 {state->kernel_name, state->posterior.negativeLogLikelihood(),
1449 state->posterior.negativeLogLeaveOneGeometryOut(
1450 state->observations.R.rows()),
1451 pair_optimized, true, default_initial_value, initial_value, value,
1452 warm_start_used, objective.evaluations});
1453 {
1454 ScopedPhaseTimer residual_timer(PhaseTimers::residual_seconds);
1455 if (select_components && environment_residuals_)
1456 selectEnvironmentResidual(*state);
1457 if (select_components && compare_cartesian_residual) {
1458 const auto selected_kernel = state->kernel;
1459 selectCartesianResidual(*state, selected_kernel);
1460 }
1461 if (select_components && additive_pair_residuals_)
1462 selectAdditivePairResidual(*state);
1463 }
1464 if (std::none_of(active_kernel_evidence_.begin(),
1465 active_kernel_evidence_.end(),
1466 [](const auto& evidence) { return evidence.selected; }))
1467 return false;
1468 if (state->conditioning.subsetActive()) {
1469 // Energy covariance gives a cheap initial support set for the
1470 // selected kernel, including all its components. Derivative means
1471 // also depend on the fitted coefficients, so they require their own
1472 // check against the observation noise at every omitted anchor.
1473 ScopedPhaseTimer timer(PhaseTimers::assembly_seconds);
1474 ScopedPhaseTimer support_timer(PhaseTimers::support_seconds,
1475 "support expansion");
1476 state->conditioning.includeCovarianceSupport(*state->kernel,
1477 state->observations.R);
1478 auto unconditioned = state->kernel;
1479 Eigen::Index fitted_anchor_count = last_active_fit_anchor_count_;
1480 bool expand = true;
1481 while (expand) {
1483 const Coord final_anchors = state->conditioning.fitAnchors();
1484 ConditionalKernelProjection projection;
1485 EigenMatrix covariance;
1486 if (!state->conditioning.prepareKernel(*unconditioned,
1487 state->observations.R,
1488 projection, covariance))
1489 return false;
1490 if (!state->conditioning.condition(state->posterior, covariance) ||
1491 !state->posterior.valid())
1492 return false;
1493 state->posterior.prepareLocalPrediction();
1494 state->kernel_projection = std::move(projection);
1495 state->kernel = unconditioned;
1496 if (select_components && state->cartesian_kernel &&
1497 final_anchors.rows() > fitted_anchor_count) {
1498 // A wider conditioning set changes the conditional
1499 // likelihood. Refit the selected chart against that set,
1500 // keeping every other fitted component fixed. A trusted
1501 // pair update retains all other component parameters.
1502 std::vector<std::shared_ptr<const KernelOperator>> fixed;
1503 if (state->includes_pair)
1504 fixed.push_back(makeActiveCovarianceOperator(
1505 state->fitted_theta, active_lengths));
1506 if (state->environment_kernel)
1507 fixed.push_back(state->environment_kernel);
1508 if (state->additive_kernel)
1509 fixed.push_back(state->additive_kernel);
1510 const std::shared_ptr<const KernelOperator> other =
1511 fixed.empty() ? nullptr
1512 : std::make_shared<Sum>(std::move(fixed));
1513 {
1514 ScopedPhaseTimer refit_timer(
1516 "support chart refit");
1518 selectCartesianResidual(*state, other, true);
1519 }
1520 fitted_anchor_count = final_anchors.rows();
1521 unconditioned = state->kernel;
1522 }
1523 state->kernel = std::move(state->kernel_projection)
1524 .intoKernel(unconditioned, final_anchors);
1525 expand = false;
1526 if (state->conditioning.subsetActive()) {
1527 const auto correction =
1528 makeKernelMean(state->kernel, state->observations.R,
1529 state->posterior.weights());
1530 expand = state->conditioning.includeChangedAnchors(
1531 correction(state->conditioning.anchors));
1532 }
1533 }
1534 } else {
1535 state->kernel =
1536 std::move(state->kernel_projection)
1537 .intoKernel(state->kernel, state->conditioning.anchors);
1538 }
1539 last_active_fit_support_count_ = state->conditioning.fitAnchorCount();
1540 state->conditioning.fit_anchor_rows.clear();
1541 prepareActivePosteriorMeanExpansion(*state);
1542 const Eigen::Index fit_anchor_count = last_active_fit_anchor_count_;
1543 const Eigen::Index anchor_count = state->conditioning.anchors.rows();
1544 active_posterior_ = std::move(state);
1545 advanceActivePosteriorEpoch();
1546 failedOptimizer = false;
1547 has_been_optimized_ = true;
1548 if (report_level >= 1)
1549 log_man << "Active posterior fit: " << reduced.size() << " parameters, "
1551 << " new configurations, fit anchors " << fit_anchor_count
1552 << " of " << anchor_count << ", support "
1553 << last_active_fit_support_count_ << ", MAP " << initial_value
1554 << " -> " << value << ", gradient norm " << gradient.norm()
1555 << "\n";
1556 if (report_level >= 1)
1557 log_man << "Active posterior fit time: wall "
1558 << std::chrono::duration<double>(
1559 std::chrono::steady_clock::now() - fit_started)
1560 .count()
1561 << " s, evaluations "
1562 << PhaseTimers::objective_count - entry_evaluations
1563 << ", objective "
1564 << PhaseTimers::objective_seconds - entry_objective
1565 << " s, assembly "
1566 << PhaseTimers::assembly_seconds - entry_assembly
1567 << " s, gradient "
1568 << PhaseTimers::gradient_seconds - entry_gradient << " s, pair "
1570 << " s, chart "
1572 << " s, residual selection "
1573 << PhaseTimers::residual_seconds - entry_residual
1574 << " s, support "
1575 << PhaseTimers::support_seconds - entry_support << " s (refit "
1576 << PhaseTimers::support_refit_seconds - entry_support_refit
1577 << " s), anchor factor "
1579 << " s, anchor solve "
1581 << " s.\n";
1582 return true;
1583}
1584
1585void GaussianProcessRegression::selectCartesianResidual(
1586 ActivePosteriorState& state,
1587 const std::shared_ptr<const KernelOperator>& pair_kernel,
1588 bool selected_component_only)
1589{
1590 const Eigen::Index count = state.observations.R.rows();
1591 const Eigen::Index dimension = state.observations.R.cols();
1592 if (dimension % 3 != 0 || dimension <= 0) return;
1593 const bool has_frozen_atoms =
1594 atoms_config.atoms_froz_active.positions.size() > 0 ||
1595 atoms_config.atoms_froz_inactive.positions.size() > 0 ||
1596 (atoms_config.is_frozen.size() > 0 &&
1597 (atoms_config.is_frozen.array() != MOVING_ATOM).any());
1598 EigenMatrix constraints =
1599 EigenMatrix::Zero(has_frozen_atoms ? 0 : 3, dimension);
1600 if (!has_frozen_atoms)
1601 for (Eigen::Index atom = 0; atom < dimension / 3; ++atom)
1602 constraints.middleCols(3 * atom, 3).setIdentity();
1603 const auto chart = std::make_shared<geometry::AffineCoordinateChart>(
1604 state.observations.R.colwise().mean().transpose(), constraints);
1605 if (!chart->valid()) return;
1606
1607 double squared_motion = 0.0;
1608 std::vector<Eigen::VectorXd> chart_rows;
1609 chart_rows.reserve(static_cast<std::size_t>(count) + 1);
1610 for (Eigen::Index row = 0; row < count; ++row) {
1611 chart_rows.push_back(
1612 chart->coordinates(state.observations.R.row(row).transpose()));
1613 squared_motion += chart_rows.back().squaredNorm();
1614 }
1615 chart_rows.push_back(
1616 chart->coordinates(full_fit_observations_.R.bottomRows(1).transpose()));
1617 squared_motion += chart_rows.back().squaredNorm();
1618 const double motion =
1619 std::sqrt(2.0 * squared_motion / ((count + 1) * chart->rank()));
1620 const double initial_length = motion > 0.0 ? motion : 1.0;
1621 // Use the closest distinct chart rows as a smoothness floor for this
1622 // candidate's length scale.
1623 double chart_spacing = std::numeric_limits<double>::infinity();
1624 for (std::size_t i = 0; i < chart_rows.size(); ++i)
1625 for (std::size_t j = i + 1; j < chart_rows.size(); ++j) {
1626 const double d = (chart_rows[i] - chart_rows[j]).norm();
1627 if (d > 0.0) chart_spacing = std::min(chart_spacing, d);
1628 }
1629 const double chart_log_floor =
1630 std::isfinite(chart_spacing) && chart_spacing > 0.0
1631 ? std::log(chart_spacing)
1632 : -std::numeric_limits<double>::infinity();
1633 const Coord fit_positions =
1634 state.conditioning.positions(state.observations.R);
1635 const auto background = state.posterior;
1636 const double baseline_loo =
1637 selected_component_only
1638 ? state.posterior.negativeLogLeaveOneGeometryOut(count)
1639 : active_kernel_evidence_.front().geometry_loo;
1640 double best_nlml = state.posterior.negativeLogLikelihood();
1641 EigenMatrix rows;
1642 Eigen::VectorXd indices;
1643 aux::AuxiliaryFunctionality{}.assembleMatrixOfRepetitiveCoordinates(
1644 state.observations.R, rows, indices);
1645 const Eigen::VectorXd targets = state.posterior.residual() / y_scale_;
1646 const double residual_amplitude_floor =
1647 std::log(likelihoodDiagonal(rows).mean() + jitter_sigma2);
1648 EigenMatrix residual_gradient(count, dimension);
1649 for (Eigen::Index channel = 0; channel < dimension; ++channel)
1650 residual_gradient.col(channel) =
1651 targets.segment((channel + 1) * count, count);
1652 const double gradient_magnitude =
1653 initial_length * initial_length *
1654 (residual_gradient * chart->tangentBasis()).squaredNorm() /
1655 (count * chart->rank());
1656 const double residual_magnitude =
1657 std::max(targets.head(count).squaredNorm() / count, gradient_magnitude);
1658 const double initial_log_magnitude =
1659 residual_magnitude > 0.0 ? std::log(residual_magnitude)
1660 : sexpat_cov_func->combineParameters()(0);
1661 const auto retained_environment = state.environment_kernel;
1662 const auto retained_additive = state.additive_kernel;
1663 const auto retained_cartesian = state.cartesian_kernel;
1664 const bool retained_pair = state.includes_pair;
1665 std::string retained_name = "pair";
1666 for (const auto& evidence: active_kernel_evidence_)
1667 if (evidence.selected) retained_name = evidence.kernel;
1668 ScgOptimizationSettings settings = scg_opt_settings;
1669 settings.active_parameters.clear();
1670 settings.use_tail_lower_barrier = false;
1671 const double log_output_variance = std::log(outputVarianceScaleSquared());
1672 Eigen::VectorXd standalone_start;
1673 bool selected_projection = false;
1674 for (const bool include_pairs: {false, true}) {
1675 if (selected_component_only && include_pairs != bool(pair_kernel))
1676 continue;
1677 ConditionalPosterior posterior = background;
1678 ChartFitObjective objective{
1679 posterior, state.conditioning,
1680 fit_positions, include_pairs ? pair_kernel : nullptr,
1681 chart, log_output_variance,
1682 backend().mpi(), backend().local()};
1683 // A component refit retains the baseline parameters and posterior.
1684 // Its trial owns the factor workspace; a rejected trial reconstructs
1685 // the baseline projection once, without overlapping two anchor factors.
1686 if (selected_component_only)
1687 objective.projection = std::move(state.kernel_projection);
1688 Eigen::VectorXd theta(2), rho0(1);
1689 theta << initial_log_magnitude, std::log(initial_length);
1690 rho0 << initial_length;
1691 const double strength = 1e-4 + 1e-3 * count;
1692 auto config = funcmin::makeMapObjectiveConfig(rows, targets, theta,
1693 strength, rho0, settings);
1694 config.parameter_lower = Eigen::VectorXd::Constant(
1695 2, -std::numeric_limits<double>::infinity());
1696 config.parameter_lower(1) =
1697 std::max(std::log(initial_length) +
1698 0.5 * std::log(std::numeric_limits<double>::epsilon()),
1699 chart_log_floor);
1700 theta(1) = std::max(theta(1), config.parameter_lower(1));
1701 // A candidate whose amplitude falls below the observation noise
1702 // explains nothing, and below it the objective is flat in the
1703 // length scales: the fit walked that valley for hundreds of steps
1704 // (17_oxycope: amplitude to e^-85, one log length to 242). The
1705 // noise is the floor.
1706 config.parameter_lower(0) = residual_amplitude_floor;
1707 theta(0) = std::max(theta(0), residual_amplitude_floor);
1709 double initial = 0.0;
1710 Eigen::VectorXd gradient;
1711 const auto evaluate_map = [&](const Eigen::VectorXd& point,
1712 double& value,
1713 Eigen::VectorXd& derivative) {
1714 EnergyAndGradient result(value, derivative);
1715 objective.evaluate(point, rows, indices, targets, result);
1716 funcmin::applyMapPenalty(point, config, value, &derivative);
1717 };
1718 evaluate_map(theta, initial, gradient);
1719 const double default_initial = initial;
1720 const Eigen::VectorXd fit_start = theta;
1721 const Eigen::VectorXd fit_start_gradient = gradient;
1722 bool warm_start_used = false;
1723 if (selected_component_only && retained_cartesian) {
1724 Eigen::VectorXd warm(2);
1725 warm << std::log(retained_cartesian->magnitudeVariance()) -
1726 log_output_variance,
1727 std::log(retained_cartesian->lengthScale());
1728 warm_start_used =
1729 improveMapStart(std::move(warm), config, evaluate_map, theta,
1730 initial, gradient);
1731 }
1732 if (active_posterior_ && active_posterior_->cartesian_kernel) {
1733 const auto& retained = *active_posterior_->cartesian_kernel;
1734 Eigen::VectorXd warm(2);
1735 warm << std::log(retained.magnitudeVariance()) -
1736 log_output_variance,
1737 std::log(retained.lengthScale());
1738 warm_start_used =
1739 warm_start_used ||
1740 improveMapStart(std::move(warm), config, evaluate_map, theta,
1741 initial, gradient);
1742 }
1743 // The standalone optimum seeds the sum only when it improves the
1744 // sum's own MAP objective. Its covariance changes in the sum, so
1745 // this start still goes through the composite optimizer.
1746 const bool component_start_used =
1747 include_pairs &&
1748 improveMapStart(standalone_start, config, evaluate_map, theta,
1749 initial, gradient);
1750 warm_start_used = warm_start_used || component_start_used;
1751 // A stationary warm start keeps the retained candidate as it is.
1752 const bool stationary_warm_start =
1753 warm_start_used && !component_start_used &&
1754 !selected_component_only &&
1755 warmStartStationary(fit_start, fit_start_gradient, theta, gradient,
1756 settings.common.tolerance_sol);
1757 bool optimized = std::isfinite(initial) && gradient.allFinite();
1758 if (optimized && !stationary_warm_start) {
1759 funcmin::RgminOpt optimizer;
1760 optimizer.setAlgorithmSettings(settings);
1761 optimizer.setMethod(rgmin_method_set_
1762 ? static_cast<rgmin_method_t>(rgmin_method_)
1763 : RGMIN_LBFGS);
1764 optimizer.optimize(rows, indices, targets, theta,
1765 &ChartFitObjective::evaluate, objective,
1766 strength, rho0, &config);
1767 optimized = !optimizer.failedOptim;
1768 }
1769 double value = initial;
1770 if (!stationary_warm_start) {
1771 EnergyAndGradient final_result(value, gradient);
1772 objective.evaluate(theta, rows, indices, targets, final_result);
1773 funcmin::applyMapPenalty(theta, config, value, &gradient);
1774 }
1775 optimized = optimized && std::isfinite(value) && value <= initial &&
1776 gradient.allFinite() && posterior.valid();
1777 const bool feasible = std::isfinite(value) && value <= initial &&
1778 gradient.allFinite() && posterior.valid();
1779 if (!include_pairs && feasible) standalone_start = theta;
1780 if (feasible) posterior.prepareLocalPrediction();
1781 const double nlml = feasible ? posterior.negativeLogLikelihood()
1782 : std::numeric_limits<double>::infinity();
1783 const double loo = feasible
1784 ? posterior.negativeLogLeaveOneGeometryOut(count)
1785 : std::numeric_limits<double>::infinity();
1786 // Model evidence compares feasible candidates. Optimizer stationarity
1787 // is reported separately from the value of the fitted posterior.
1788 const bool selected =
1789 feasible && nlml < best_nlml && loo < baseline_loo;
1790 if (selected) {
1791 for (auto& evidence: active_kernel_evidence_)
1792 evidence.selected = false;
1793 state.posterior = std::move(posterior);
1794 state.kernel_projection = std::move(objective.projection);
1795 selected_projection = true;
1796 state.environment_kernel =
1797 include_pairs ? retained_environment : nullptr;
1798 state.additive_kernel = include_pairs ? retained_additive : nullptr;
1799 state.includes_pair = include_pairs && retained_pair;
1800 state.kernel_name =
1801 selected_component_only
1802 ? retained_name
1803 : (include_pairs ? retained_name + "+cartesian"
1804 : "cartesian");
1805 state.cartesian_kernel =
1806 std::make_shared<ManifoldEnergyForceKernel>(
1807 chart, std::exp(theta(0) + log_output_variance),
1808 std::exp(theta(1)));
1809 const auto cartesian =
1810 std::make_shared<Pullback>(state.cartesian_kernel);
1811 state.kernel =
1812 include_pairs
1813 ? std::make_shared<Sum>(
1814 std::vector<std::shared_ptr<const KernelOperator>>{
1815 pair_kernel, cartesian})
1816 : std::shared_ptr<const KernelOperator>(cartesian);
1817 best_nlml = nlml;
1818 }
1819 active_kernel_evidence_.push_back(
1820 {selected_component_only
1821 ? retained_name
1822 : (include_pairs ? retained_name + "+cartesian" : "cartesian"),
1823 nlml, loo, optimized, selected, default_initial, initial, value,
1824 warm_start_used, objective.evaluations});
1825 }
1826 if (selected_component_only && !selected_projection) {
1827 EigenMatrix covariance;
1828 if (!state.conditioning.prepareKernel(
1829 *state.kernel, state.observations.R, state.kernel_projection,
1830 covariance))
1831 throw std::runtime_error("selected residual projection is invalid");
1832 }
1833 if (report_level >= 1)
1834 for (const auto& evidence: active_kernel_evidence_)
1835 log_man << "Active kernel evidence: " << evidence.kernel << " NLML "
1836 << evidence.nlml << " geometry_LOO "
1837 << evidence.geometry_loo << " optimized "
1838 << evidence.optimized << " selected " << evidence.selected
1839 << " initial_MAP " << evidence.initial_map
1840 << " default_initial_MAP " << evidence.default_initial_map
1841 << " final_MAP " << evidence.final_map << " warm_start "
1842 << evidence.warm_start_used << " evaluations "
1843 << evidence.objective_evaluations << "\n";
1844}
1845
1846void GaussianProcessRegression::selectEnvironmentResidual(
1847 ActivePosteriorState& state)
1848{
1849#if defined(GPR_USE_FEATOMIC)
1850 const auto pair_kernel = state.kernel;
1851 const Eigen::Index count = state.observations.R.rows();
1852 const double baseline_nlml = state.posterior.negativeLogLikelihood();
1853 const double baseline_loo =
1854 state.posterior.negativeLogLeaveOneGeometryOut(count);
1855 const auto descriptor =
1857 const Coord fit_positions =
1858 state.conditioning.positions(state.observations.R);
1859 std::vector<AtomicEnvironments> environments;
1860 environments.reserve(fit_positions.rows());
1861 for (Eigen::Index row = 0; row < fit_positions.rows(); ++row)
1862 environments.push_back(descriptor(fit_positions.row(row).transpose()));
1863 const auto motion_scales = environmentMotionScales(environments);
1864 const auto spacing_floors = environmentSpacingFloors(environments);
1865 const EigenMatrix pair_covariance =
1866 pair_kernel->jointEnergyGradientCovariance(fit_positions);
1867 EigenMatrix rows;
1868 Eigen::VectorXd indices;
1869 aux::AuxiliaryFunctionality{}.assembleMatrixOfRepetitiveCoordinates(
1870 state.observations.R, rows, indices);
1871 const Eigen::VectorXd targets = state.posterior.residual() / y_scale_;
1872 const double residual_amplitude_floor =
1873 std::log(likelihoodDiagonal(rows).mean() + jitter_sigma2);
1874 const ConditionalPosterior background = state.posterior;
1875 // Configurations that carry the residual process. Every conditioning
1876 // anchor is one of them, so the residual still vanishes exactly at the
1877 // background's own rows and the anchor solve is the exact one; the added
1878 // rows contribute the same farthest-point subset the background's
1879 // hyperparameter fit uses, so no new size enters the model. Assembly
1880 // then costs one configuration pair per (configuration, inducing
1881 // configuration) rather than one per configuration pair.
1882 const Eigen::Index anchor_count = state.conditioning.fitAnchorCount();
1883 std::vector<Eigen::Index> inducing;
1884 inducing.reserve(static_cast<std::size_t>(anchor_count) +
1885 static_cast<std::size_t>(count));
1886 for (Eigen::Index row = 0; row < anchor_count; ++row)
1887 inducing.push_back(row);
1888 for (const int row: selectOptimizationSubsetRows(state.observations))
1889 inducing.push_back(anchor_count + row);
1890 last_residual_inducing_count_ =
1891 static_cast<Eigen::Index>(inducing.size()) >= fit_positions.rows()
1892 ? fit_positions.rows()
1893 : static_cast<Eigen::Index>(inducing.size());
1894 last_residual_configuration_count_ = fit_positions.rows();
1895 if (report_level >= 1)
1896 log_man << "Environment residual: " << last_residual_inducing_count_
1897 << " inducing of " << last_residual_configuration_count_
1898 << " configurations; reported residual variance is the "
1899 "sparse posterior's, exact per configuration.\n";
1900 double best_nlml = baseline_nlml;
1901 ScgOptimizationSettings settings = scg_opt_settings;
1902 settings.active_parameters.clear();
1903 settings.use_tail_lower_barrier = false;
1904 Eigen::VectorXd standalone_start;
1905 for (const bool include_pairs: {false, true}) {
1906 ConditionalPosterior posterior = background;
1907 const EigenMatrix fixed =
1908 include_pairs ? pair_covariance
1909 : EigenMatrix::Zero(pair_covariance.rows(),
1910 pair_covariance.cols());
1911 EnvironmentFitObjective objective{
1912 posterior,
1913 state.conditioning,
1914 environments,
1915 fixed,
1916 inducing,
1917 {},
1918 std::log(outputVarianceScaleSquared()),
1919 backend().mpi(),
1920 backend().local(),
1922 Eigen::VectorXd theta(1 + motion_scales.size()),
1923 rho0(motion_scales.size());
1924 const double atoms =
1925 static_cast<double>(environments.front().values.rows());
1926 theta(0) =
1927 sexpat_cov_func->combineParameters()(0) - 2.0 * std::log(atoms);
1928 for (const auto& [number, scale]: motion_scales) {
1929 const Eigen::Index index = objective.species.size();
1930 objective.species.push_back(number);
1931 rho0(index) = scale;
1932 theta(index + 1) = std::log(scale);
1933 }
1934 const double strength = 1e-4 + 1e-3 * count;
1935 auto config = funcmin::makeMapObjectiveConfig(rows, targets, theta,
1936 strength, rho0, settings);
1937 config.parameter_lower = Eigen::VectorXd::Constant(
1938 theta.size(), -std::numeric_limits<double>::infinity());
1939 config.parameter_lower.tail(rho0.size()) =
1940 rho0.array().log() +
1941 0.5 * std::log(std::numeric_limits<double>::epsilon());
1942 // Length scales no shorter than the data's own spacing per species.
1943 for (Eigen::Index index = 0; index < rho0.size(); ++index) {
1944 const auto floor_it = spacing_floors.find(
1945 objective.species[static_cast<std::size_t>(index)]);
1946 if (floor_it == spacing_floors.end() || !(floor_it->second > 0.0))
1947 continue;
1948 const double log_floor = std::log(floor_it->second);
1949 config.parameter_lower(index + 1) =
1950 std::max(config.parameter_lower(index + 1), log_floor);
1951 theta(index + 1) = std::max(theta(index + 1), log_floor);
1952 }
1953 config.parameter_lower(0) = residual_amplitude_floor;
1954 theta(0) = std::max(theta(0), residual_amplitude_floor);
1956 double initial = 0.0;
1957 Eigen::VectorXd gradient;
1958 const auto evaluate_map = [&](const Eigen::VectorXd& point,
1959 double& value,
1960 Eigen::VectorXd& derivative) {
1961 EnergyAndGradient result(value, derivative);
1962 objective.evaluate(point, rows, indices, targets, result);
1963 funcmin::applyMapPenalty(point, config, value, &derivative);
1964 };
1965 evaluate_map(theta, initial, gradient);
1966 const double default_initial = initial;
1967 const Eigen::VectorXd fit_start = theta;
1968 const Eigen::VectorXd fit_start_gradient = gradient;
1969 bool warm_start_used = false;
1970 if (active_posterior_ && active_posterior_->environment_kernel) {
1971 const auto& retained = *active_posterior_->environment_kernel;
1972 Eigen::VectorXd warm = theta;
1973 warm(0) = std::log(retained.magnitudeVariance()) -
1974 objective.log_output_variance;
1975 for (std::size_t i = 0; i < objective.species.size(); ++i) {
1976 const auto found =
1977 retained.lengthScales().find(objective.species[i]);
1978 if (found != retained.lengthScales().end())
1979 warm(i + 1) = std::log(found->second);
1980 }
1981 warm_start_used = improveMapStart(warm, config, evaluate_map, theta,
1982 initial, gradient);
1983 }
1984 // The standalone optimum seeds the sum only when it improves the
1985 // sum's own MAP objective. Its covariance changes in the sum, so
1986 // this start still goes through the composite optimizer.
1987 const bool component_start_used =
1988 include_pairs &&
1989 improveMapStart(standalone_start, config, evaluate_map, theta,
1990 initial, gradient);
1991 warm_start_used = warm_start_used || component_start_used;
1992 // A stationary warm start keeps the retained candidate as it is.
1993 const bool stationary_warm_start =
1994 warm_start_used && !component_start_used &&
1995 warmStartStationary(fit_start, fit_start_gradient, theta, gradient,
1996 settings.common.tolerance_sol);
1997 bool optimized = std::isfinite(initial) && gradient.allFinite();
1998 if (optimized && !stationary_warm_start) {
1999 funcmin::RgminOpt optimizer;
2000 optimizer.setAlgorithmSettings(settings);
2001 optimizer.setMethod(rgmin_method_set_
2002 ? static_cast<rgmin_method_t>(rgmin_method_)
2003 : RGMIN_LBFGS);
2004 optimizer.optimize(rows, indices, targets, theta,
2005 &EnvironmentFitObjective::evaluate, objective,
2006 strength, rho0, &config);
2007 optimized = !optimizer.failedOptim;
2008 }
2009 double value = initial;
2010 if (!stationary_warm_start) {
2011 EnergyAndGradient final_result(value, gradient);
2012 objective.evaluate(theta, rows, indices, targets, final_result);
2013 funcmin::applyMapPenalty(theta, config, value, &gradient);
2014 }
2015 optimized = optimized && std::isfinite(value) && value <= initial &&
2016 gradient.allFinite() && posterior.valid();
2017 const bool feasible = std::isfinite(value) && value <= initial &&
2018 gradient.allFinite() && posterior.valid();
2019 if (!include_pairs && feasible) standalone_start = theta;
2020 if (settings.common.report_level >= 2) {
2021 for (Eigen::Index i = 0; i < theta.size(); ++i)
2022 std::fprintf(stderr,
2023 "[environment-fit] parameter=%lld theta=%.17g "
2024 "gradient=%.17g lower=%.17g upper=%.17g\n",
2025 static_cast<long long>(i), theta(i), gradient(i),
2026 config.parameter_lower.size()
2027 ? config.parameter_lower(i)
2028 : -std::numeric_limits<double>::infinity(),
2029 config.parameter_upper.size()
2030 ? config.parameter_upper(i)
2031 : std::numeric_limits<double>::infinity());
2032 }
2033 if (settings.common.check_derivative) {
2034 const Eigen::VectorXd analytical = gradient;
2035 const double center = value;
2036 for (Eigen::Index i = 0; i < theta.size(); ++i) {
2037 for (const double step: {1e-4, 1e-5, 1e-6}) {
2038 const bool central =
2039 theta(i) - step >= config.parameter_lower(i);
2040 Eigen::VectorXd point = theta, ignored;
2041 double first = 0.0, second = 0.0;
2042 point(i) += step;
2043 evaluate_map(point, first, ignored);
2044 point(i) = theta(i) + (central ? -step : 2.0 * step);
2045 evaluate_map(point, second, ignored);
2046 const double numerical =
2047 central ? (first - second) / (2.0 * step)
2048 : (-3.0 * center + 4.0 * first - second) /
2049 (2.0 * step);
2050 std::fprintf(
2051 stderr,
2052 "[environment-derivative] parameter=%lld "
2053 "step=%.17g analytical=%.17g numerical=%.17g\n",
2054 static_cast<long long>(i), step, analytical(i),
2055 numerical);
2056 }
2057 }
2058 evaluate_map(theta, value, gradient);
2059 }
2060 if (feasible) posterior.prepareLocalPrediction();
2061 const double nlml = feasible ? posterior.negativeLogLikelihood()
2062 : std::numeric_limits<double>::infinity();
2063 const double loo = feasible
2064 ? posterior.negativeLogLeaveOneGeometryOut(count)
2065 : std::numeric_limits<double>::infinity();
2066 // Model evidence compares feasible candidates. Optimizer stationarity
2067 // is reported separately from the value of the fitted posterior.
2068 const bool selected =
2069 feasible && nlml < best_nlml && loo < baseline_loo;
2070 if (selected) {
2071 for (auto& evidence: active_kernel_evidence_)
2072 evidence.selected = false;
2073 state.posterior = std::move(posterior);
2074 state.kernel_projection = std::move(objective.projection);
2075 state.includes_pair = include_pairs;
2076 state.kernel_name = include_pairs ? "pair+soap" : "soap";
2077 state.environment_kernel =
2078 std::make_shared<SpeciesEnvironmentKernel>(
2079 descriptor, objective.lengths(theta),
2080 std::exp(theta(0) + objective.log_output_variance),
2081 backend().local(), backend().environmentGpu());
2082 state.kernel =
2083 include_pairs
2084 ? std::make_shared<Sum>(
2085 std::vector<std::shared_ptr<const KernelOperator>>{
2086 pair_kernel, state.environment_kernel})
2087 : std::shared_ptr<const KernelOperator>(
2088 state.environment_kernel);
2089 best_nlml = nlml;
2090 }
2091 active_kernel_evidence_.push_back(
2092 {include_pairs ? "pair+soap" : "soap", nlml, loo, optimized,
2093 selected, default_initial, initial, value, warm_start_used,
2094 objective.evaluations});
2095 }
2096 if (report_level >= 1)
2097 for (const auto& evidence: active_kernel_evidence_)
2098 log_man << "Active kernel evidence: " << evidence.kernel << " NLML "
2099 << evidence.nlml << " geometry_LOO "
2100 << evidence.geometry_loo << " optimized "
2101 << evidence.optimized << " selected " << evidence.selected
2102 << " initial_MAP " << evidence.initial_map
2103 << " default_initial_MAP " << evidence.default_initial_map
2104 << " final_MAP " << evidence.final_map << " warm_start "
2105 << evidence.warm_start_used << " evaluations "
2106 << evidence.objective_evaluations << "\n";
2107#else
2108 (void)state;
2109#endif
2110}
2111
2112void GaussianProcessRegression::selectAdditivePairResidual(
2113 ActivePosteriorState& state)
2114{
2115 AtomsConfiguration additive_configuration = atoms_config;
2116 if (length_scale_ties_.valid) {
2117 // The independent pair process shares chemical parents; environment
2118 // refinements and released scales belong to the many-body component.
2119 for (Eigen::Index i = 0; i < additive_configuration.pairtype.size();
2120 ++i) {
2121 auto& type = additive_configuration.pairtype.data()[i];
2122 if (type < 0) continue;
2123 if (static_cast<std::size_t>(type) >=
2124 length_scale_ties_.parent.size())
2125 throw std::invalid_argument("invalid chemical pair parent");
2126 type = length_scale_ties_.parent[static_cast<std::size_t>(type)];
2127 }
2128 additive_configuration.n_pt = length_scale_ties_.base_count;
2129 additive_configuration.n_base_pt = 0;
2130 additive_configuration.pair_type_parent.clear();
2131 }
2132 const Eigen::Index length_count = additive_configuration.n_pt;
2133 if (length_count <= 0) return;
2134 const AdditivePairKernel prototype(
2135 additive_configuration, Eigen::VectorXd::Ones(length_count), 1.0);
2136 const auto& pairs = prototype.pairs();
2137 if (pairs.empty()) return;
2138 const auto retained_kernel = state.kernel;
2139 const bool retained_pair = state.includes_pair;
2140 std::string retained_name = "pair";
2141 for (const auto& evidence: active_kernel_evidence_)
2142 if (evidence.selected) retained_name = evidence.kernel;
2143 const Eigen::Index count = state.observations.R.rows();
2144 const double baseline_nlml = state.posterior.negativeLogLikelihood();
2145 const double baseline_loo =
2146 state.posterior.negativeLogLeaveOneGeometryOut(count);
2147 const Coord fit_positions =
2148 state.conditioning.positions(state.observations.R);
2149 const auto features = prototype.rowFeatures(fit_positions);
2150 const Eigen::Index dimensions = prototype.dimensions();
2151 // Types with pairs, their inverse-distance spread over the fit rows
2152 // (the initial length scale) and the smallest nonzero separation of two
2153 // sampled inverse distances (the length-scale floor).
2154 std::vector<Eigen::Index> types;
2155 Eigen::VectorXd spread(length_count), spacing(length_count);
2156 for (Eigen::Index type = 0; type < length_count; ++type) {
2157 std::vector<double> values;
2158 for (const auto& row: features)
2159 for (std::size_t p = 0; p < pairs.size(); ++p)
2160 if (pairs[p].type == type)
2161 values.push_back(row.u(static_cast<Eigen::Index>(p)));
2162 if (values.empty()) continue;
2163 double mean = 0.0;
2164 for (const double v: values)
2165 mean += v;
2166 mean /= static_cast<double>(values.size());
2167 double variance = 0.0;
2168 for (const double v: values)
2169 variance += (v - mean) * (v - mean);
2170 variance /= static_cast<double>(values.size());
2171 std::sort(values.begin(), values.end());
2172 double separation = std::numeric_limits<double>::infinity();
2173 for (std::size_t i = 1; i < values.size(); ++i) {
2174 const double d = values[i] - values[i - 1];
2175 if (d > 0.0) separation = std::min(separation, d);
2176 }
2177 types.push_back(type);
2178 spread(type) = variance > 0.0 ? std::sqrt(2.0 * variance) : 1.0;
2179 spacing(type) = std::isfinite(separation) ? separation : 0.0;
2180 }
2181 if (types.empty()) return;
2182 const EigenMatrix pair_covariance =
2183 retained_kernel->jointEnergyGradientCovariance(fit_positions);
2184 EigenMatrix rows;
2185 Eigen::VectorXd indices;
2186 aux::AuxiliaryFunctionality{}.assembleMatrixOfRepetitiveCoordinates(
2187 state.observations.R, rows, indices);
2188 const Eigen::VectorXd targets = state.posterior.residual() / y_scale_;
2189 const double residual_amplitude_floor =
2190 std::log(likelihoodDiagonal(rows).mean() + jitter_sigma2);
2191 const ConditionalPosterior background = state.posterior;
2192 double best_nlml = baseline_nlml;
2193 ScgOptimizationSettings settings = scg_opt_settings;
2194 settings.active_parameters.clear();
2195 settings.use_tail_lower_barrier = false;
2196 Eigen::VectorXd standalone_start;
2197 for (const bool include_pairs: {false, true}) {
2198 ConditionalPosterior posterior = background;
2199 const EigenMatrix fixed =
2200 include_pairs ? pair_covariance
2201 : EigenMatrix::Zero(pair_covariance.rows(),
2202 pair_covariance.cols());
2203 AdditivePairFitObjective objective{
2204 posterior,
2205 state.conditioning,
2206 features,
2207 pairs,
2208 dimensions,
2209 length_count,
2210 fixed,
2211 types,
2212 std::log(outputVarianceScaleSquared()),
2213 backend().mpi(),
2214 backend().local()};
2215 const Eigen::Index parameters =
2216 1 + static_cast<Eigen::Index>(types.size());
2217 Eigen::VectorXd theta(parameters), rho0(parameters - 1);
2218 // Every configuration sums one process per pair, so the residual
2219 // variance of a configuration is the pair-process variance times
2220 // the squared pair count.
2221 theta(0) = sexpat_cov_func->combineParameters()(0) -
2222 2.0 * std::log(static_cast<double>(pairs.size()));
2223 for (std::size_t index = 0; index < types.size(); ++index) {
2224 const Eigen::Index i = static_cast<Eigen::Index>(index);
2225 rho0(i) = spread(types[index]);
2226 theta(i + 1) = std::log(rho0(i));
2227 }
2228 const double strength = 1e-4 + 1e-3 * count;
2229 auto config = funcmin::makeMapObjectiveConfig(rows, targets, theta,
2230 strength, rho0, settings);
2231 config.parameter_lower = Eigen::VectorXd::Constant(
2232 theta.size(), -std::numeric_limits<double>::infinity());
2233 config.parameter_lower.tail(rho0.size()) =
2234 rho0.array().log() +
2235 0.5 * std::log(std::numeric_limits<double>::epsilon());
2236 for (std::size_t index = 0; index < types.size(); ++index) {
2237 const Eigen::Index i = static_cast<Eigen::Index>(index);
2238 const double floor = spacing(types[index]);
2239 if (!(floor > 0.0)) continue;
2240 const double log_floor = std::log(floor);
2241 config.parameter_lower(i + 1) =
2242 std::max(config.parameter_lower(i + 1), log_floor);
2243 theta(i + 1) = std::max(theta(i + 1), log_floor);
2244 }
2245 config.parameter_lower(0) = residual_amplitude_floor;
2246 theta(0) = std::max(theta(0), residual_amplitude_floor);
2248 double initial = 0.0;
2249 Eigen::VectorXd gradient;
2250 const auto evaluate_map = [&](const Eigen::VectorXd& point,
2251 double& value,
2252 Eigen::VectorXd& derivative) {
2253 EnergyAndGradient result(value, derivative);
2254 objective.evaluate(point, rows, indices, targets, result);
2255 funcmin::applyMapPenalty(point, config, value, &derivative);
2256 };
2257 evaluate_map(theta, initial, gradient);
2258 const double default_initial = initial;
2259 const Eigen::VectorXd fit_start = theta;
2260 const Eigen::VectorXd fit_start_gradient = gradient;
2261 bool warm_start_used = false;
2262 if (active_posterior_ && active_posterior_->additive_kernel) {
2263 const auto& retained = *active_posterior_->additive_kernel;
2264 Eigen::VectorXd warm = theta;
2265 warm(0) = std::log(retained.magnitudeVariance()) -
2266 objective.log_output_variance;
2267 if (retained.lengthScales().size() == length_count)
2268 for (std::size_t index = 0; index < types.size(); ++index)
2269 warm(static_cast<Eigen::Index>(index) + 1) =
2270 std::log(retained.lengthScales()(types[index]));
2271 warm_start_used = improveMapStart(warm, config, evaluate_map, theta,
2272 initial, gradient);
2273 }
2274 // The standalone optimum seeds the sum only when it improves the
2275 // sum's own MAP objective. Its covariance changes in the sum, so
2276 // this start still goes through the composite optimizer.
2277 const bool component_start_used =
2278 include_pairs &&
2279 improveMapStart(standalone_start, config, evaluate_map, theta,
2280 initial, gradient);
2281 warm_start_used = warm_start_used || component_start_used;
2282 // A stationary warm start keeps the retained candidate as it is.
2283 const bool stationary_warm_start =
2284 warm_start_used && !component_start_used &&
2285 warmStartStationary(fit_start, fit_start_gradient, theta, gradient,
2286 settings.common.tolerance_sol);
2287 bool optimized = std::isfinite(initial) && gradient.allFinite();
2288 if (optimized && !stationary_warm_start) {
2289 funcmin::RgminOpt optimizer;
2290 optimizer.setAlgorithmSettings(settings);
2291 optimizer.setMethod(rgmin_method_set_
2292 ? static_cast<rgmin_method_t>(rgmin_method_)
2293 : RGMIN_LBFGS);
2294 optimizer.optimize(rows, indices, targets, theta,
2295 &AdditivePairFitObjective::evaluate, objective,
2296 strength, rho0, &config);
2297 optimized = !optimizer.failedOptim;
2298 }
2299 double value = initial;
2300 if (!stationary_warm_start) {
2301 EnergyAndGradient final_result(value, gradient);
2302 objective.evaluate(theta, rows, indices, targets, final_result);
2303 funcmin::applyMapPenalty(theta, config, value, &gradient);
2304 }
2305 optimized = optimized && std::isfinite(value) && value <= initial &&
2306 gradient.allFinite() && posterior.valid();
2307 const bool feasible = std::isfinite(value) && value <= initial &&
2308 gradient.allFinite() && posterior.valid();
2309 if (!include_pairs && feasible) standalone_start = theta;
2310 if (feasible) posterior.prepareLocalPrediction();
2311 const double nlml = feasible ? posterior.negativeLogLikelihood()
2312 : std::numeric_limits<double>::infinity();
2313 const double loo = feasible
2314 ? posterior.negativeLogLeaveOneGeometryOut(count)
2315 : std::numeric_limits<double>::infinity();
2316 const bool selected =
2317 feasible && nlml < best_nlml && loo < baseline_loo;
2318 const std::string name =
2319 include_pairs ? retained_name + "+additive" : "additive";
2320 if (selected) {
2321 for (auto& evidence: active_kernel_evidence_)
2322 evidence.selected = false;
2323 state.posterior = std::move(posterior);
2324 state.kernel_projection = std::move(objective.projection);
2325 state.additive_kernel = std::make_shared<AdditivePairKernel>(
2326 additive_configuration, objective.lengths(theta),
2327 std::exp(theta(0) + objective.log_output_variance));
2328 if (!include_pairs) {
2329 state.environment_kernel = nullptr;
2330 state.cartesian_kernel = nullptr;
2331 }
2332 state.includes_pair = include_pairs && retained_pair;
2333 state.kernel_name = name;
2334 state.kernel =
2335 include_pairs
2336 ? std::make_shared<Sum>(
2337 std::vector<std::shared_ptr<const KernelOperator>>{
2338 retained_kernel, state.additive_kernel})
2339 : std::shared_ptr<const KernelOperator>(
2340 state.additive_kernel);
2341 best_nlml = nlml;
2342 }
2343 active_kernel_evidence_.push_back(
2344 {name, nlml, loo, optimized, selected, default_initial, initial,
2345 value, warm_start_used, objective.evaluations});
2346 }
2347 if (report_level >= 1)
2348 for (const auto& evidence: active_kernel_evidence_)
2349 log_man << "Active kernel evidence: " << evidence.kernel << " NLML "
2350 << evidence.nlml << " geometry_LOO "
2351 << evidence.geometry_loo << " optimized "
2352 << evidence.optimized << " selected " << evidence.selected
2353 << " initial_MAP " << evidence.initial_map
2354 << " default_initial_MAP " << evidence.default_initial_map
2355 << " final_MAP " << evidence.final_map << " warm_start "
2356 << evidence.warm_start_used << " evaluations "
2357 << evidence.objective_evaluations << "\n";
2358}
2359
2361 const Observation& full_observation)
2362{
2363 if (atomic_environment_model_) return false;
2364 if (!active_posterior_) return false;
2365 const auto retained = active_posterior_;
2366 return reconditionActivePosterior(full_observation, *retained);
2367}
2368
2369bool GaussianProcessRegression::reconditionActivePosterior(
2370 const Observation& full_observation, const ActivePosteriorState& retained)
2371{
2372 auto state = prepareActivePosterior(full_observation);
2373 if (!state) return false;
2374 EigenMatrix covariance = EigenMatrix::Zero(state->posterior.channels(),
2375 state->posterior.channels());
2376 if (retained.kernel)
2377 covariance = retained.kernel->jointEnergyGradientCovariance(
2378 state->observations.R);
2379 if (!state->posterior.condition(covariance)) return false;
2380 state->kernel = retained.kernel;
2381 state->environment_kernel = retained.environment_kernel;
2382 state->cartesian_kernel = retained.cartesian_kernel;
2383 state->additive_kernel = retained.additive_kernel;
2384 state->includes_pair = retained.includes_pair;
2385 state->kernel_name = retained.kernel_name;
2386 state->fitted_lengths = retained.fitted_lengths;
2387 state->fitted_theta = retained.fitted_theta;
2388 prepareActivePosteriorMeanExpansion(*state);
2389 active_posterior_ = std::move(state);
2390 advanceActivePosteriorEpoch();
2391 return true;
2392}
2393
2394void GaussianProcessRegression::prepareActivePosteriorMeanExpansion(
2395 ActivePosteriorState& state)
2396{
2397 const VarianceSubsetScope subset(variance_subset_configurations_,
2398 variance_subset_forced_ids_,
2399 state.background_subset_ids);
2400 state.residual_cross =
2401 state.kernel
2402 ? makeKernelCrossCovariance(state.kernel, state.observations.R)
2403 : KernelOperator::CrossCovarianceFunction{};
2404 state.residual_mean =
2405 state.kernel ? makeKernelMean(state.kernel, state.observations.R,
2406 state.posterior.weights())
2407 : KernelOperator::MeanFunction{};
2408 state.residual_hessian = {};
2409 state.residual_hessian_analytic = false;
2410 state.residual_hessian_exact = false;
2411 if (state.kernel) {
2412 const auto& training = state.observations.R;
2413 const auto& weights = state.posterior.weights();
2414 // prepareMeanHessian / prepareMeanHessianVector return an empty
2415 // function when the kernel has no closed form. The virtual
2416 // meanHessianVector then distinguishes Pullback-style formulas,
2417 // which return a product, from the unsupported default.
2418 const bool prepared_hessian = static_cast<bool>(
2419 state.kernel->prepareMeanHessian(training, weights));
2420 const bool prepared_vector =
2421 !prepared_hessian &&
2422 static_cast<bool>(
2423 state.kernel->prepareMeanHessianVector(training, weights));
2424 const bool implemented = prepared_hessian || prepared_vector;
2425 // Do not call meanHessianVector here. Curvature at a collinear
2426 // valence angle is undefined, and conditioning has not asked for a
2427 // Hessian.
2428 state.residual_hessian_probe_pending =
2429 !implemented && training.rows() > 0 && training.cols() > 0 &&
2430 weights.size() == training.rows() * (training.cols() + 1);
2431 state.residual_hessian_analytic = implemented;
2432 state.residual_hessian_exact = prepared_hessian;
2433 state.residual_hessian =
2434 makeKernelMeanHessian(state.kernel, training, weights);
2435 state.residual_hessian_refusal = makeRefusalAwareKernelMeanHessian(
2436 state.kernel, training, weights, &state.residual_hessian_exact);
2437 }
2438 state.mean_weights.resize(0);
2439 state.background_mean = {};
2440 state.background_hessian = {};
2441 state.background_hessian_refusal = {};
2442 state.background_hessian_exact = false;
2443 state.residual_hessian_matrix =
2444 state.kernel
2445 ? makeKernelMeanHessianMatrix(state.kernel, state.observations.R,
2446 state.posterior.weights())
2447 : KernelOperator::MeanHessianMatrixFunction{};
2448 state.background_hessian_matrix = {};
2449 if (!sexpat_cov_func ||
2450 (use_hssvd_backend_ &&
2451 (!hssvd_dual_kernel_ || hssvd_local_active_set_size_ > 0)))
2452 return;
2453 const Eigen::Index old_count = full_fit_observations_.R.rows();
2454 const Eigen::Index added_count = state.observations.R.rows();
2455 const Eigen::Index count = old_count + added_count;
2456 const Eigen::Index dof = state.observations.R.cols();
2457#ifdef GPR_LINALG_KOKKOS
2459#endif
2460 const Eigen::VectorXd alpha =
2461 (use_hssvd_backend_ || descriptor_predictor_ready_)
2462 ? hssvd_dual_predict_weights_
2464 if (alpha.size() != old_count * (dof + 1)) return;
2465 const Eigen::VectorXd correction = conditionalBackgroundMeanWeights(
2466 state.observations.R, state.posterior.weights());
2467 if (correction.size() != alpha.size() || !correction.allFinite()) return;
2468 // m = k_X (s alpha - s^2 S K_XA w) + k_A s^2 w + k_residual w.
2469 // These are fitted mean coefficients; no query state is retained.
2470 const Eigen::VectorXd old_weights =
2471 y_scale_ * alpha - outputVarianceScaleSquared() * correction;
2472 const Eigen::VectorXd added_weights =
2473 outputVarianceScaleSquared() * state.posterior.weights();
2474 state.mean_positions.resize(count, dof);
2475 state.mean_positions.topRows(old_count) = full_fit_observations_.R;
2476 state.mean_positions.bottomRows(added_count) = state.observations.R;
2477 state.mean_weights.resize(count * (dof + 1));
2478 for (Eigen::Index channel = 0; channel <= dof; ++channel) {
2479 state.mean_weights.segment(channel * count, old_count) =
2480 old_weights.segment(channel * old_count, old_count);
2481 state.mean_weights.segment(channel * count + old_count, added_count) =
2482 added_weights.segment(channel * added_count, added_count);
2483 }
2484 auto primitive = std::make_shared<SexpatCF>(*sexpat_cov_func);
2485 primitive->clearDistanceCache();
2486 auto background = primitive->assembledOperator();
2487 if (!background)
2488 background = std::make_shared<Sexpat>(std::move(primitive));
2489 state.background_mean =
2490 makeKernelMean(background, state.mean_positions, state.mean_weights);
2491 // An assembled operator refers to this copy of the primitive, and a
2492 // composition without a preparation evaluates it at each query.
2493 auto background_hessian = background->prepareMeanHessian(
2494 state.mean_positions, state.mean_weights);
2495 state.background_hessian_exact = static_cast<bool>(background_hessian);
2496 state.background_hessian_refusal = makeRefusalAwareKernelMeanHessian(
2497 background, state.mean_positions, state.mean_weights,
2498 &state.background_hessian_exact);
2499 if (!background_hessian)
2500 background_hessian = makeKernelMeanHessian(
2501 background, state.mean_positions, state.mean_weights);
2502 state.background_hessian =
2503 [owner = primitive, hessian = std::move(background_hessian)](
2504 const Eigen::VectorXd& position) { return hessian(position); };
2505 state.background_hessian_matrix = makeKernelMeanHessianMatrix(
2506 background, state.mean_positions, state.mean_weights);
2507 const double constant =
2508 const_cov_fun ? const_cov_fun->getConstSigma2() : 0.0;
2509 state.background_mean_offset = static_cast<double>(
2510 static_cast<long double>(y_mean_) +
2511 constant * state.mean_weights.head(count).cast<long double>().sum());
2512}
2513
2514void GaussianProcessRegression::resolveResidualHessianProbe(
2515 const ActivePosteriorState& state)
2516{
2517 if (!state.residual_hessian_probe_pending || !state.kernel) return;
2518 std::call_once(state.residual_hessian_probe_once, [&state] {
2519 const auto& training = state.observations.R;
2520 const auto& weights = state.posterior.weights();
2521 if (training.rows() <= 0 || training.cols() <= 0 ||
2522 weights.size() != training.rows() * (training.cols() + 1))
2523 return;
2524 // The kernel and its components report a chart's capability, so
2525 // a chart nested in a sum or a conditioning is seen as well as one
2526 // at the top. A chart that cannot supply curvature refuses the
2527 // product instead of falling through to a four-point difference.
2528 switch (state.kernel->meanCurvature()) {
2529 case KernelOperator::MeanCurvature::Refused:
2530 state.residual_hessian_analytic = false;
2531 return;
2532 case KernelOperator::MeanCurvature::Exact:
2533 state.residual_hessian_analytic = true;
2534 return;
2535 case KernelOperator::MeanCurvature::Unknown:
2536 break;
2537 }
2538 try {
2539 Eigen::VectorXd probe;
2540 Eigen::VectorXd axis = Eigen::VectorXd::Zero(training.cols());
2541 axis(0) = 1.0;
2542 state.residual_hessian_analytic = state.kernel->meanHessianVector(
2543 training, weights, training.row(0).transpose(), axis, probe);
2544 } catch (const geometry::UndefinedInternalCoordinate&) {
2545 // A formula that is undefined at this row is implemented. The
2546 // row says nothing about a query, which is judged where it is
2547 // contracted.
2548 state.residual_hessian_analytic = true;
2549 }
2550 });
2551}
2552
2553GaussianProcessRegression::MeanHessianAction
2555{
2556 return prepareMeanHessianAction(R, false);
2557}
2558
2561{
2562 return prepareMeanHessianAction(R, true);
2563}
2564
2566GaussianProcessRegression::prepareMeanHessianAction(const Coord& R,
2567 bool analytic_only)
2568{
2569 if (R.rows() != 1 || R.cols() == 0 || !R.allFinite()) return {};
2570 if (atomic_environment_model_) {
2571 if (analytic_only) return {};
2572 return [this, R](const Eigen::VectorXd& direction,
2573 Eigen::VectorXd& action) {
2574 return calculateMeanHessianVectorDispatched(R, direction, action);
2575 };
2576 }
2577 bool add_physical_prior = false;
2578 // An operator the kernel prepares itself owns the answer, including a
2579 // refusal. An empty action at the query is that refusal, as is an
2580 // action that returns false. The generic directional wrapper refuses
2581 // for kernels without an analytic contraction, which the dispatched
2582 // stencil then serves.
2583 bool exact = false;
2584 // A step reports a refusal through the bool of the call that invoked
2585 // it. The bool lives on that call's stack, so another direction, thread,
2586 // or model cannot observe it.
2587 using HessianStep = std::function<bool(
2588 const Eigen::VectorXd&, Eigen::VectorXd&, bool& exact_refusal)>;
2589 HessianStep step;
2590 const auto refused = [](const Eigen::VectorXd&, Eigen::VectorXd& action) {
2591 action.resize(0);
2592 return false;
2593 };
2594 if (active_posterior_ && active_posterior_->mean_weights.size() > 0 &&
2595 active_posterior_->background_hessian) {
2596 requireActivePosteriorBackground();
2597 resolveResidualHessianProbe(*active_posterior_);
2598 if (active_posterior_->residualCurvatureRefused()) {
2599 return
2600 [](const Eigen::VectorXd& direction, Eigen::VectorXd& action) {
2601 (void)direction;
2602 action.resize(0);
2603 return false;
2604 };
2605 }
2606 const auto& state = *active_posterior_;
2607 const auto& hook = optimizer_state_->mean_hessian;
2608 const auto* background_prepare = &state.background_hessian;
2609 const auto* residual_prepare = &state.residual_hessian;
2610 bool background_exact = state.background_hessian_exact;
2611 bool residual_stored_exact = state.residual_hessian_exact;
2612 if (hook.active_posterior_actions) {
2613 background_prepare = &hook.background;
2614 residual_prepare = &hook.residual;
2615 background_exact = hook.background_exact;
2616 residual_stored_exact = hook.residual_exact;
2617 const bool residual_exact =
2618 static_cast<bool>(state.kernel) && residual_stored_exact;
2619 auto background = *background_prepare
2620 ? (*background_prepare)(R.row(0).transpose())
2621 : MeanHessianAction{};
2622 auto residual = *residual_prepare
2623 ? (*residual_prepare)(R.row(0).transpose())
2624 : MeanHessianAction{};
2625 const bool residual_ready =
2626 !state.kernel || static_cast<bool>(residual);
2627 if ((background_exact && !background) ||
2628 (residual_exact && !residual_ready))
2629 return refused;
2630 if (background && residual_ready) {
2631 step = [background = std::move(background),
2632 residual = std::move(residual), dof = R.cols(),
2633 background_exact, residual_exact](
2634 const Eigen::VectorXd& direction,
2635 Eigen::VectorXd& action, bool& exact_refusal) {
2636 if (direction.size() != dof || !direction.allFinite())
2637 return false;
2638 if (!background(direction, action) ||
2639 action.size() != dof) {
2640 if (background_exact) exact_refusal = true;
2641 return false;
2642 }
2643 if (residual) {
2644 Eigen::VectorXd term;
2645 if (!residual(direction, term) || term.size() != dof) {
2646 if (residual_exact) exact_refusal = true;
2647 return false;
2648 }
2649 action += term;
2650 }
2651 if (!action.allFinite()) {
2652 if (background_exact || residual_exact)
2653 exact_refusal = true;
2654 return false;
2655 }
2656 return true;
2657 };
2658 add_physical_prior = true;
2659 }
2660 } else {
2661 const bool residual_exact =
2662 static_cast<bool>(state.kernel) && residual_stored_exact;
2663 bool query_refused = false;
2664 auto background = state.background_hessian_refusal
2665 ? state.background_hessian_refusal(
2666 R.row(0).transpose(), query_refused)
2668 auto residual = state.residual_hessian_refusal
2669 ? state.residual_hessian_refusal(
2670 R.row(0).transpose(), query_refused)
2672 const bool residual_ready =
2673 !state.kernel || static_cast<bool>(residual);
2674 // One exact term and one generic term is not an all-exact mean,
2675 // but a refusal of an exact child still owns the composed operator.
2676 if (query_refused || (background_exact && !background) ||
2677 (residual_exact && !residual_ready))
2678 return refused;
2679 if (background && residual_ready) {
2680 step = [background = std::move(background),
2681 residual = std::move(residual), dof = R.cols(),
2682 background_exact, residual_exact](
2683 const Eigen::VectorXd& direction,
2684 Eigen::VectorXd& action, bool& exact_refusal) {
2685 if (direction.size() != dof || !direction.allFinite())
2686 return false;
2687 if (!background(direction, action, exact_refusal) ||
2688 action.size() != dof) {
2689 if (background_exact) exact_refusal = true;
2690 if (!exact_refusal && residual) {
2691 Eigen::VectorXd unused;
2692 (void)residual(direction, unused, exact_refusal);
2693 }
2694 return false;
2695 }
2696 if (residual) {
2697 Eigen::VectorXd term;
2698 if (!residual(direction, term, exact_refusal) ||
2699 term.size() != dof) {
2700 if (residual_exact) exact_refusal = true;
2701 return false;
2702 }
2703 action += term;
2704 }
2705 if (!action.allFinite()) {
2706 if (background_exact || residual_exact)
2707 exact_refusal = true;
2708 return false;
2709 }
2710 return true;
2711 };
2712 add_physical_prior = true;
2713 }
2714 }
2715 }
2716 if (!step && !optimizer_state_->mean_hessian.map_kernel_overrides_hssvd) {
2717 auto hessian = std::make_shared<PreparedHssvdHessianVector>();
2718 if (prepareMeanHessianVectorHssvd(R, *hessian)) {
2719 // A prepared block owns every direction. A failed apply is a
2720 // refusal, so the hard wrapper does not stencil a substitute.
2721 exact = true;
2722 step = [this, hessian = std::move(hessian)](
2723 const Eigen::VectorXd& direction,
2724 Eigen::VectorXd& action, bool& exact_refusal) {
2725 if (!applyMeanHessianVectorHssvd(*hessian, direction, action)) {
2726 exact_refusal = true;
2727 return false;
2728 }
2729 return true;
2730 };
2731 }
2732 }
2733 if (!step) {
2734 Eigen::VectorXd weights;
2735 auto kernel = mapSexpatMeanKernel(R.cols(), weights, analytic_only);
2736 if (kernel) {
2737 const auto& positions = full_fit_observations_.R;
2738 auto prepare = makeRefusalAwareKernelMeanHessian(kernel, positions,
2739 weights, &exact);
2740 bool query_refused = false;
2741 auto action = prepare ? prepare(R.row(0).transpose(), query_refused)
2743 if (query_refused || (exact && !action)) return refused;
2744 if (action) {
2745 step = [action = std::move(action)](
2746 const Eigen::VectorXd& direction,
2747 Eigen::VectorXd& result, bool& exact_refusal) {
2748 return action(direction, result, exact_refusal);
2749 };
2750 add_physical_prior = true;
2751 }
2752 }
2753 }
2754 if (step && add_physical_prior) {
2755 const auto prior_pairs =
2756 ffPriorMeanActive() ? ff_prior_mean_->hessianPairs(R.row(0))
2757 : zblPriorMeanActive() ? zbl_prior_mean_->hessianPairs(R.row(0))
2758 : std::vector<priors::PriorHessianPair>{};
2759 const Eigen::MatrixXd secant_hessian = secantQuadraticPriorActive()
2760 ? secantQuadraticHessian()
2761 : Eigen::MatrixXd();
2762 if (!prior_pairs.empty() || secant_hessian.size() > 0)
2763 step = [mean = std::move(step), prior_pairs, secant_hessian](
2764 const Eigen::VectorXd& direction,
2765 Eigen::VectorXd& action, bool& exact_refusal) {
2766 if (!mean(direction, action, exact_refusal)) return false;
2767 if (!prior_pairs.empty())
2768 action +=
2769 priors::applyPriorHessianPairs(prior_pairs, direction);
2770 if (secant_hessian.size() > 0) {
2771 if (secant_hessian.cols() != direction.size()) return false;
2772 action += secant_hessian * direction;
2773 }
2774 return action.allFinite();
2775 };
2776 }
2777 // An analytic-only action never reaches the stencil of the mean gradient.
2778 if (analytic_only && !step) return {};
2779 if (step && (exact || analytic_only))
2780 return [dof = R.cols(), step = std::move(step)](
2781 const Eigen::VectorXd& direction, Eigen::VectorXd& action) {
2782 bool exact_refusal = false;
2783 if (direction.size() != dof || !direction.allFinite() ||
2784 !step(direction, action, exact_refusal)) {
2785 action.resize(0);
2786 return false;
2787 }
2788 return true;
2789 };
2790 return [this, R, step = std::move(step)](const Eigen::VectorXd& direction,
2791 Eigen::VectorXd& action) {
2792 // The refusal belongs to this call. It is not kept for the next
2793 // direction, and it is not visible to another thread or model.
2794 bool exact_refusal = false;
2795 if (direction.size() != R.cols() || !direction.allFinite()) {
2796 action.resize(0);
2797 return false;
2798 }
2799 if (step && step(direction, action, exact_refusal)) return true;
2800 // Refusal of an exact term is final. A generic term that misses
2801 // still falls through to the stencil.
2802 if (exact_refusal) {
2803 action.resize(0);
2804 return false;
2805 }
2806 return calculateMeanHessianVectorDispatched(R, direction, action);
2807 };
2808}
2809
2810std::shared_ptr<const KernelOperator>
2811GaussianProcessRegression::mapSexpatMeanKernel(Eigen::Index dof,
2812 Eigen::VectorXd& weights,
2813 bool cholesky_under_hssvd)
2814{
2815 const bool cholesky_weights =
2816 use_hssvd_backend_ && cholesky_under_hssvd && !hssvd_basis_valid_;
2817 if (active_posterior_ || !sexpat_cov_func || !is_decomposed_succesfully ||
2818 rff_replaces_exact_ ||
2819 (uncertainty_mode_ == UncertaintyMode::LAPLACE_SLICE &&
2820 rff_features_ > 0 && rff_model_.isBuilt()) ||
2821 uncertainty_mode_ != UncertaintyMode::MAP ||
2822 (use_hssvd_backend_ && !cholesky_weights &&
2823 (!hssvd_dual_kernel_ || hssvd_local_active_set_size_ != 0)))
2824 return nullptr;
2825 const auto& positions = full_fit_observations_.R;
2826#ifdef GPR_LINALG_KOKKOS
2827 materializeDeviceAlpha();
2828#endif
2829 const bool basis_weights = use_hssvd_backend_ && !cholesky_weights;
2830 weights = y_scale_ * ((basis_weights || descriptor_predictor_ready_)
2831 ? hssvd_dual_predict_weights_
2832 : unpermuteTrainingVector(a));
2833 if (positions.rows() == 0 || positions.cols() != dof ||
2834 weights.size() != positions.rows() * (dof + 1))
2835 return nullptr;
2836 if (optimizer_state_->mean_hessian.map_kernel)
2837 return optimizer_state_->mean_hessian.map_kernel;
2838 auto primitive = std::make_shared<SexpatCF>(*sexpat_cov_func);
2839 primitive->clearDistanceCache();
2840 auto kernel = primitive->assembledOperator();
2841 if (!kernel) kernel = std::make_shared<Sexpat>(std::move(primitive));
2842 return kernel;
2843}
2844
2846 Eigen::MatrixXd& hessian)
2847{
2848 hessian.resize(0, 0);
2849 if (R.rows() != 1 || R.cols() == 0 || !R.allFinite()) return false;
2850 const Eigen::Index dof = R.cols();
2851 const Eigen::VectorXd position = R.row(0).transpose();
2852 const auto columns = [dof](const MeanHessianAction& action,
2853 Eigen::MatrixXd& result) {
2854 if (!action) return false;
2855 result.resize(dof, dof);
2856 Eigen::VectorXd column;
2857 for (Eigen::Index j = 0; j < dof; ++j) {
2858 if (!action(Eigen::VectorXd::Unit(dof, j), column) ||
2859 column.size() != dof)
2860 return false;
2861 result.col(j) = column;
2862 }
2863 return true;
2864 };
2865 using Status = KernelOperator::MeanHessianStatus;
2866 // A computed kernel matrix takes the physical prior; a refusal is final.
2867 // Unavailable leaves the matrix to the action columns below, whose
2868 // generic miss reaches the stencil.
2869 const auto finish_kernel_matrix =
2870 [&](Status status) -> std::optional<bool> {
2871 if (status == Status::Unavailable) return std::nullopt;
2872 if (status == Status::Computed && hessian.rows() == dof &&
2873 hessian.cols() == dof) {
2874 if (ffPriorMeanActive())
2876 ff_prior_mean_->hessianPairs(R.row(0)), hessian);
2877 else if (zblPriorMeanActive())
2879 zbl_prior_mean_->hessianPairs(R.row(0)), hessian);
2881 const Eigen::MatrixXd& secant = secantQuadraticHessian();
2882 if (secant.rows() != dof || secant.cols() != dof) {
2883 hessian.resize(0, 0);
2884 return false;
2885 }
2886 hessian += secant;
2887 }
2888 if (hessian.allFinite()) return true;
2889 }
2890 hessian.resize(0, 0);
2891 return false;
2892 };
2893 if (!atomic_environment_model_ && active_posterior_ &&
2894 active_posterior_->mean_weights.size() > 0 &&
2895 active_posterior_->background_hessian) {
2896 requireActivePosteriorBackground();
2897 const auto& state = *active_posterior_;
2898 if (state.background_hessian_exact &&
2899 (!state.kernel || state.residual_hessian_exact)) {
2900 Status status = state.background_hessian_matrix(position, hessian);
2901 if (status == Status::Computed && state.kernel) {
2902 Eigen::MatrixXd residual;
2903 status = state.residual_hessian_matrix(position, residual);
2904 if (status == Status::Computed) hessian += residual;
2905 }
2906 if (const auto done = finish_kernel_matrix(status)) return *done;
2907 }
2908 }
2909 if (!atomic_environment_model_ && !active_posterior_ &&
2910 !optimizer_state_->mean_hessian.map_kernel_overrides_hssvd) {
2912 if (prepareMeanHessianVectorHssvd(R, prepared)) {
2914 prepared, Eigen::MatrixXd::Identity(dof, dof), hessian) &&
2915 hessian.rows() == dof && hessian.cols() == dof &&
2916 hessian.allFinite())
2917 return true;
2918 // A prepared block that does not apply has refused. The action
2919 // columns, and the stencil behind them, are not a substitute.
2920 hessian.resize(0, 0);
2921 return false;
2922 }
2923 }
2924 if (Eigen::VectorXd weights;
2925 !atomic_environment_model_ && !active_posterior_) {
2926 if (auto kernel = mapSexpatMeanKernel(dof, weights)) {
2927 const auto dense = makeKernelMeanHessianMatrix(
2928 kernel, full_fit_observations_.R, weights);
2929 if (const auto done =
2930 finish_kernel_matrix(dense(position, hessian)))
2931 return *done;
2932 }
2933 }
2934 if (columns(prepareMeanHessian(R), hessian) && hessian.allFinite())
2935 return true;
2936 hessian.resize(0, 0);
2937 return false;
2938}
2939
2941 const Coord& R, const Eigen::VectorXd& direction, double& curvature)
2942{
2943 curvature = std::numeric_limits<double>::quiet_NaN();
2944 if (atomic_environment_model_ || R.rows() != 1 || R.cols() == 0 ||
2945 direction.size() != R.cols() || !R.allFinite() ||
2946 !direction.allFinite())
2947 return false;
2948 // Laplace, SVGD, and BMA predictive means are factor mixtures. The
2949 // HS-SVD and MAP kernel contractions below differentiate the MAP mean
2950 // only, so they are not this mean's curvature.
2951 if (!active_posterior_ && (uncertainty_mode_ == UncertaintyMode::LAPLACE ||
2952 uncertainty_mode_ == UncertaintyMode::SVGD ||
2953 uncertainty_mode_ == UncertaintyMode::BMA))
2954 return false;
2955
2956 const Eigen::VectorXd position = R.row(0).transpose();
2957 // The caller already holds the contraction. Rebuilding the dense matrix
2958 // here would replace an exact action with a second assembly.
2959 auto finish = [&](const Eigen::VectorXd& hessian_vector) {
2960 if (hessian_vector.size() != direction.size() ||
2961 !hessian_vector.allFinite())
2962 return false;
2963 const double value = direction.dot(hessian_vector);
2964 if (!std::isfinite(value)) return false;
2965 curvature = value;
2966 return true;
2967 };
2968 auto add_prior = [&](Eigen::VectorXd& hessian_vector) {
2969 if (ffPriorMeanActive())
2970 hessian_vector += priors::applyPriorHessianPairs(
2971 ff_prior_mean_->hessianPairs(R.row(0)), direction);
2972 else if (zblPriorMeanActive())
2973 hessian_vector += priors::applyPriorHessianPairs(
2974 zbl_prior_mean_->hessianPairs(R.row(0)), direction);
2975 };
2976
2977 const auto mean_is_exact = [](const KernelOperator& kernel) {
2978 return kernel.meanCurvature() == KernelOperator::MeanCurvature::Exact;
2979 };
2980 // Ownership is the kernel's meanCurvature, not whether
2981 // prepareMeanHessian is non-empty. A pullback with a directional
2982 // Jacobian is Exact, and ConditionedKernel reports its child, so
2983 // conditioned geodesic heat is Exact too. Inverse-distance Sexpat has
2984 // no assembled chart or heat operator and reports Exact itself.
2985 const auto background_is_exact = [&] {
2986 if (!sexpat_cov_func) return false;
2987 if (const auto kernel = sexpat_cov_func->assembledOperator())
2988 return mean_is_exact(*kernel);
2989 const Sexpat inverse_distance(*sexpat_cov_func);
2990 return mean_is_exact(inverse_distance);
2991 };
2992
2993 // An active posterior owns the mean. A residual or background that is
2994 // not Exact cannot be replaced by a stencil here.
2995 if (active_posterior_) {
2996 if (active_posterior_->mean_weights.size() == 0) return false;
2997 requireActivePosteriorBackground();
2998 const auto& state = *active_posterior_;
2999 if (!state.background_hessian_refusal || !background_is_exact() ||
3000 (state.kernel && (!state.residual_hessian_refusal ||
3001 !mean_is_exact(*state.kernel))))
3002 return false;
3003 // One direction, one action. The stored matrix functions walk every
3004 // Cartesian axis and are the dense assembly this query does not make.
3005 bool refused = false;
3006 const auto background =
3007 state.background_hessian_refusal(position, refused);
3008 const auto residual =
3009 state.kernel ? state.residual_hessian_refusal(position, refused)
3011 if (refused || !background || (state.kernel && !residual)) return false;
3012 Eigen::VectorXd hessian_vector;
3013 if (!background(direction, hessian_vector, refused) || refused ||
3014 hessian_vector.size() != direction.size())
3015 return false;
3016 if (residual) {
3017 Eigen::VectorXd term;
3018 if (!residual(direction, term, refused) || refused ||
3019 term.size() != direction.size())
3020 return false;
3021 hessian_vector += term;
3022 }
3023 add_prior(hessian_vector);
3024 return finish(hessian_vector);
3025 }
3026
3027 // Chart and geodesic means are not the inverse-distance Sexpat Hessian.
3028 // Exactness is the assembled operator's meanCurvature. A query the
3029 // operator refuses stays refused; it is not replaced by a stencil.
3030 if (sexpat_cov_func && (sexpat_cov_func->usesManifoldChart() ||
3031 sexpat_cov_func->usesGeodesicHeatKernel())) {
3033 uncertainty_mode_ != UncertaintyMode::MAP ||
3034 R_matrix.rows() != a.size() || R_matrix.cols() < R.cols() ||
3035 a.size() == 0 || a.size() % (R.cols() + 1) != 0)
3036 return false;
3037 const Eigen::Index count = a.size() / (R.cols() + 1);
3038 const Coord training = R_matrix.topRows(count).leftCols(R.cols());
3039 const Eigen::VectorXd weights = y_scale_ * unpermuteTrainingVector(a);
3040 const auto kernel = sexpat_cov_func->assembledOperator();
3041 if (!kernel || !mean_is_exact(*kernel)) return false;
3042 Eigen::VectorXd hessian_vector;
3043 bool applied = false;
3044 try {
3045 applied = kernel->meanHessianVector(training, weights, position,
3046 direction, hessian_vector);
3047 } catch (const geometry::UndefinedInternalCoordinate&) {
3048 return false;
3049 }
3050 if (!applied) return false;
3051 add_prior(hessian_vector);
3052 return finish(hessian_vector);
3053 }
3054
3055 // A dual HS-SVD model and the MAP kernel expansion share one mean. The
3056 // spectral contraction takes precedence, as in calculateMeanHessian,
3057 // unless a MAP test kernel overrides it.
3058 if (!optimizer_state_->mean_hessian.map_kernel_overrides_hssvd) {
3059 Eigen::VectorXd hessian_vector;
3060 switch (meanHessianProductHssvd(R, direction, hessian_vector)) {
3062 return finish(hessian_vector);
3064 return false;
3066 break;
3067 }
3068 }
3069 if (Eigen::VectorXd weights;
3070 auto kernel = mapSexpatMeanKernel(R.cols(), weights)) {
3071 if (!mean_is_exact(*kernel)) return false;
3072 auto prepare = makeRefusalAwareKernelMeanHessian(
3073 kernel, full_fit_observations_.R, weights);
3074 bool refused = false;
3075 const auto action = prepare(position, refused);
3076 Eigen::VectorXd hessian_vector;
3077 if (refused || !action || !action(direction, hessian_vector, refused) ||
3078 refused || hessian_vector.size() != direction.size())
3079 return false;
3080 add_prior(hessian_vector);
3081 return finish(hessian_vector);
3082 }
3083 return false;
3084}
3085
3087 const Coord& R, const Eigen::VectorXd& direction,
3088 Eigen::VectorXd& hessian_vector)
3089{
3090 // calculatePotentialDispatched returns the random-feature mean on these
3091 // arms before any uncertainty-mode arm, so the Hessian takes this route
3092 // first; its Hessian is exact in the features and the descriptor.
3093 if (!atomic_environment_model_ && !active_posterior_ &&
3094 rff_model_.isBuilt() &&
3095 (rff_replaces_exact_ ||
3096 (uncertainty_mode_ == UncertaintyMode::LAPLACE_SLICE &&
3097 rff_features_ > 0))) {
3098 hessian_vector.resize(0);
3099 if (R.rows() != 1 || R.cols() != direction.size() || !R.allFinite() ||
3100 !direction.allFinite() || !sexpat_cov_func)
3101 return false;
3102 if (direction.norm() == 0.0) {
3103 hessian_vector = Eigen::VectorXd::Zero(direction.size());
3104 return true;
3105 }
3106 if (!rff_model_.meanHessianVector(R.row(0).transpose(), direction,
3107 hessian_vector))
3108 return false;
3109 if (rff_standardized_targets_ && std::isfinite(y_scale_) &&
3110 y_scale_ > 0.0)
3111 hessian_vector *= y_scale_;
3112 if (ffPriorMeanActive())
3113 hessian_vector += priors::applyPriorHessianPairs(
3114 ff_prior_mean_->hessianPairs(R.row(0)), direction);
3115 else if (zblPriorMeanActive())
3116 hessian_vector += priors::applyPriorHessianPairs(
3117 zbl_prior_mean_->hessianPairs(R.row(0)), direction);
3119 hessian_vector += secantQuadraticHessian() * direction;
3120 return hessian_vector.allFinite();
3121 }
3122 // Laplace, SVGD, and BMA predictive means are factor mixtures, including
3123 // when an HSSVD factor of the MAP mean is also available. A mixture that
3124 // refuses is not replaced by the stencil below.
3125 if (!atomic_environment_model_ && !active_posterior_ &&
3126 (uncertainty_mode_ == UncertaintyMode::LAPLACE ||
3127 uncertainty_mode_ == UncertaintyMode::SVGD ||
3128 uncertainty_mode_ == UncertaintyMode::BMA)) {
3129 const auto mixture = uncertainty_mode_ == UncertaintyMode::LAPLACE
3131 R, direction, hessian_vector)
3132 : uncertainty_mode_ == UncertaintyMode::SVGD
3133 ? calculateSvgdMixtureMeanHessianVector(
3134 R, direction, hessian_vector)
3135 : calculateBmaMixtureMeanHessianVector(
3136 R, direction, hessian_vector);
3138 return hessian_vector.allFinite();
3139 if (mixture == MixtureMeanHessianStatus::Refused) return false;
3140 }
3141 if (!atomic_environment_model_ && !active_posterior_ &&
3142 !optimizer_state_->mean_hessian.map_kernel_overrides_hssvd) {
3143 switch (meanHessianProductHssvd(R, direction, hessian_vector)) {
3145 return true;
3147 hessian_vector.resize(0);
3148 return false;
3150 break;
3151 }
3152 }
3153 hessian_vector.resize(0);
3154 if (R.rows() != 1 || R.cols() != direction.size() || !R.allFinite() ||
3155 !direction.allFinite() ||
3156 (!atomic_environment_model_ && !sexpat_cov_func))
3157 return false;
3158 if (atomic_environment_model_ && !atomicEnvironmentPosteriorBuilt())
3159 return false;
3160 // Build the exact MAP kernel action only when the spectral or prepared
3161 // descriptor contraction did not already consume the call.
3162 if (!atomic_environment_model_ && !active_posterior_) {
3163 Eigen::VectorXd weights;
3164 if (auto kernel = mapSexpatMeanKernel(direction.size(), weights)) {
3165 bool all_exact = false;
3166 bool has_exact_or_refusal = false;
3167 auto prepare = makeRefusalAwareKernelMeanHessian(
3168 kernel, full_fit_observations_.R, weights, &all_exact,
3169 &has_exact_or_refusal);
3170 if (all_exact || has_exact_or_refusal) {
3171 ++optimizer_state_->mean_hessian.dispatched_map_hessian_actions;
3172 bool exact_refusal = false;
3173 const auto action =
3174 prepare ? prepare(R.row(0).transpose(), exact_refusal)
3176 const bool ok =
3177 action &&
3178 action(direction, hessian_vector, exact_refusal) &&
3179 hessian_vector.size() == direction.size() &&
3180 hessian_vector.allFinite();
3181 if (!ok) {
3182 if (all_exact || exact_refusal) {
3183 hessian_vector.resize(0);
3184 return false;
3185 }
3186 hessian_vector.resize(0);
3187 } else {
3188 if (ffPriorMeanActive())
3189 hessian_vector += priors::applyPriorHessianPairs(
3190 ff_prior_mean_->hessianPairs(R.row(0)), direction);
3191 else if (zblPriorMeanActive())
3192 hessian_vector += priors::applyPriorHessianPairs(
3193 zbl_prior_mean_->hessianPairs(R.row(0)), direction);
3195 hessian_vector += secantQuadraticHessian() * direction;
3196 if (!hessian_vector.allFinite()) {
3197 hessian_vector.resize(0);
3198 return false;
3199 }
3200 return true;
3201 }
3202 }
3203 }
3204 }
3205 const double norm = direction.norm();
3206 if (!std::isfinite(norm)) return false;
3207 if (norm == 0.0) {
3208 hessian_vector = Eigen::VectorXd::Zero(direction.size());
3209 return true;
3210 }
3211 if (!atomic_environment_model_ && !active_posterior_ &&
3212 !optimizer_state_->mean_hessian.map_kernel &&
3214 uncertainty_mode_ == UncertaintyMode::MAP &&
3215 (sexpat_cov_func->usesManifoldChart() ||
3216 sexpat_cov_func->usesGeodesicHeatKernel()) &&
3217 R_matrix.rows() == a.size() && R_matrix.cols() >= R.cols() &&
3218 a.size() > 0 && a.size() % (R.cols() + 1) == 0) {
3219 const Eigen::Index count = a.size() / (R.cols() + 1);
3220 const Coord training = R_matrix.topRows(count).leftCols(R.cols());
3221 const Eigen::VectorXd weights = y_scale_ * unpermuteTrainingVector(a);
3222 if (!sexpat_cov_func->meanHessianVector(training, weights,
3223 R.row(0).transpose(), direction,
3224 hessian_vector))
3225 return false;
3226 if (ffPriorMeanActive())
3227 hessian_vector += priors::applyPriorHessianPairs(
3228 ff_prior_mean_->hessianPairs(R.row(0)), direction);
3229 else if (zblPriorMeanActive())
3230 hessian_vector += priors::applyPriorHessianPairs(
3231 zbl_prior_mean_->hessianPairs(R.row(0)), direction);
3233 hessian_vector += secantQuadraticHessian() * direction;
3234 return hessian_vector.allFinite();
3235 }
3236 if (!atomic_environment_model_ && active_posterior_ &&
3237 active_posterior_->mean_weights.size() > 0) {
3238 requireActivePosteriorBackground();
3239 resolveResidualHessianProbe(*active_posterior_);
3240 if (active_posterior_->residualCurvatureRefused()) {
3241 hessian_vector.resize(0);
3242 return false;
3243 }
3244 const auto& state = *active_posterior_;
3245 bool exact_refusal = false;
3246 const auto residual_action =
3247 state.residual_hessian_refusal
3248 ? state.residual_hessian_refusal(R.row(0).transpose(),
3249 exact_refusal)
3251 const auto background_action =
3252 state.background_hessian_refusal
3253 ? state.background_hessian_refusal(R.row(0).transpose(),
3254 exact_refusal)
3256 const bool background_exact = state.background_hessian_exact;
3257 const bool residual_exact =
3258 static_cast<bool>(state.kernel) && state.residual_hessian_exact;
3259 // A missing action from an exact term refuses the whole mean, even
3260 // when the other term is a generic stencil.
3261 if (exact_refusal || (background_exact && !background_action) ||
3262 (residual_exact && !residual_action)) {
3263 hessian_vector.resize(0);
3264 return false;
3265 }
3266 Eigen::VectorXd residual = Eigen::VectorXd::Zero(direction.size());
3267 const bool residual_ok =
3268 !state.kernel ||
3269 (residual_action &&
3270 residual_action(direction, residual, exact_refusal) &&
3271 residual.size() == direction.size());
3272 const bool background_ok =
3273 background_action &&
3274 background_action(direction, hessian_vector, exact_refusal) &&
3275 hessian_vector.size() == direction.size();
3276 if (residual_ok && background_ok) {
3277 hessian_vector += residual;
3278 if (ffPriorMeanActive())
3279 hessian_vector += priors::applyPriorHessianPairs(
3280 ff_prior_mean_->hessianPairs(R.row(0)), direction);
3281 else if (zblPriorMeanActive())
3282 hessian_vector += priors::applyPriorHessianPairs(
3283 zbl_prior_mean_->hessianPairs(R.row(0)), direction);
3285 hessian_vector += secantQuadraticHessian() * direction;
3286 if (hessian_vector.allFinite()) return true;
3287 }
3288 // An exact term that misses or returns false refuses the composed
3289 // mean. A generic partner that misses does not: the stencil below
3290 // still serves a mean with no exact term in the failure.
3291 if (exact_refusal || (background_exact && !background_ok) ||
3292 (residual_exact && !residual_ok) ||
3293 ((background_exact || residual_exact) && residual_ok &&
3294 background_ok)) {
3295 hessian_vector.resize(0);
3296 return false;
3297 }
3298 }
3299 const Eigen::VectorXd unit = direction / norm;
3300 double inverse_step_scale = 0.0;
3301 if (atomic_environment_model_) {
3302 inverse_step_scale =
3303 atomic_environment_posterior_->inverseCartesianLengthScale(
3304 R.row(0).transpose());
3305 } else {
3306 Eigen::VectorXd features, rate, gradient_norms;
3307 std::vector<int> types;
3309 R, atoms_config, unit, features, rate, types, &gradient_norms);
3310 const auto& lengths = sexpat_cov_func->getLengthScaleRef();
3311 // A tangent direction can have zero descriptor rate and finite
3312 // curvature. Full Cartesian gradient norms keep its stencil on the
3313 // molecular scale.
3314 for (Eigen::Index i = 0; i < rate.size(); ++i) {
3315 const Eigen::Index type = lengths.size() == 1 ? 0 : types[i];
3316 if (type >= lengths.size() || !(lengths.data()[type] > 0.0))
3317 return false;
3318 inverse_step_scale = std::max(
3319 inverse_step_scale, gradient_norms(i) / lengths.data()[type]);
3320 if (features(i) > 0.0)
3321 inverse_step_scale = std::max(inverse_step_scale,
3322 gradient_norms(i) / features(i));
3323 if (active_posterior_ &&
3324 type < active_posterior_->fitted_lengths.size())
3325 inverse_step_scale =
3326 std::max(inverse_step_scale,
3327 gradient_norms(i) /
3328 active_posterior_->fitted_lengths(type));
3329 }
3330 if (active_posterior_ && active_posterior_->environment_kernel)
3331 inverse_step_scale = std::max(
3332 inverse_step_scale,
3333 active_posterior_->environment_kernel->directionalInverseLength(
3334 R.row(0).transpose(), unit));
3335 if (active_posterior_ && active_posterior_->cartesian_kernel) {
3336 const auto& kernel = *active_posterior_->cartesian_kernel;
3337 inverse_step_scale = std::max(
3338 inverse_step_scale,
3339 (kernel.chart().jacobian(R.row(0).transpose()) * unit).norm() /
3340 kernel.lengthScale());
3341 }
3342 }
3343 if (!std::isfinite(inverse_step_scale)) return false;
3344 // Laplace, SVGD, and BMA already returned above, including a failed
3345 // mixture whose MAP mean has a pair-kernel product. What remains is a
3346 // mean with no analytic Hessian: an active-posterior residual, an
3347 // atomic environment, or a gradient-only arc model.
3348 const double step = std::pow(std::numeric_limits<double>::epsilon(), 0.2) /
3349 (inverse_step_scale > 0.0 ? inverse_step_scale : 1.0);
3350 Observation stencil;
3351 stencil.R.resize(4, R.cols());
3352 constexpr double shifts[] = {-2.0, -1.0, 1.0, 2.0};
3353 for (Eigen::Index i = 0; i < 4; ++i)
3354 stencil.R.row(i) = R.row(0) + shifts[i] * step * unit.transpose();
3356 if (stencil.G.rows() != 4 || stencil.G.cols() != R.cols() ||
3357 !stencil.G.allFinite())
3358 return false;
3359 hessian_vector =
3360 (norm / (12.0 * step)) * (8.0 * (stencil.G.row(2) - stencil.G.row(1)) -
3361 (stencil.G.row(3) - stencil.G.row(0)))
3362 .transpose();
3363 return hessian_vector.allFinite();
3364}
3365
3366void GaussianProcessRegression::activePosteriorCovarianceBlocks(
3367 const EigenMatrix& positions, EigenMatrix& prior, EigenMatrix& cross)
3368{
3369 requireActivePosteriorBackground();
3370 const auto& state = *active_posterior_;
3371 // Every block belongs to the background used by the conditioning factor;
3372 // choosing another subset at a query does not define that posterior.
3373 const VarianceSubsetScope subset(variance_subset_configurations_,
3374 variance_subset_forced_ids_,
3375 state.background_subset_ids);
3376 const Eigen::Index n = positions.rows();
3377 const Eigen::Index m = state.observations.R.rows();
3378 const Eigen::Index dimensions = positions.cols();
3379 if (dimensions != state.observations.R.cols() || !positions.allFinite())
3380 throw std::invalid_argument("invalid active posterior query geometry");
3381 if (n == 0) {
3382 prior.resize(0, 0);
3383 cross.resize(0, m * (dimensions + 1));
3384 return;
3385 }
3386 if (detail::matrixExactlyEqual(positions, state.observations.R)) {
3387 calculateBackgroundObservationPosteriorCovariance(positions, prior,
3388 false);
3389 if (state.kernel)
3390 prior += state.kernel->jointEnergyGradientCovariance(positions);
3391 cross = prior;
3392 return;
3393 }
3394
3395 calculateBackgroundObservationPosteriorCovariance(positions, prior, false);
3396 calculateBackgroundObservationPosteriorCrossCovariance(
3397 positions, state.observations.R, cross);
3398 if (state.kernel) {
3399 prior += state.kernel->jointEnergyGradientCovariance(positions);
3400 cross += state.residual_cross(positions);
3401 }
3402}
3403
3404void GaussianProcessRegression::calculateActivePosteriorMean(
3405 Observation& observation)
3406{
3407 requireActivePosteriorBackground();
3408 if (observation.R.rows() == 0) {
3409 observation.E.resize(1, 0);
3410 observation.G.resize(0, observation.R.cols());
3411 return;
3412 }
3413 const auto& state = *active_posterior_;
3414 // Coincident background channels retain the statistical-noise identities
3415 // used by the spectral covariance. Other queries contract the immutable
3416 // mean expansion without rebuilding cross tensors or solving a factor.
3417 bool coincident = false;
3418 if (state.background_mean && canUseHssvdVariance()) {
3419 for (Eigen::Index i = 0; i < observation.R.rows() && !coincident; ++i)
3420 for (Eigen::Index j = 0; j < state.mean_positions.rows(); ++j)
3421 if ((observation.R.row(i).array() ==
3422 state.mean_positions.row(j).array())
3423 .all()) {
3424 coincident = true;
3425 break;
3426 }
3427 }
3428 if (state.background_mean && !coincident) {
3429 Eigen::VectorXd mean = state.background_mean(observation.R);
3430 mean.head(observation.R.rows()).array() += state.background_mean_offset;
3431 if (state.kernel) mean += state.residual_mean(observation.R);
3432 if (!mean.allFinite())
3433 throw std::invalid_argument("nonfinite fitted conditional mean");
3434 assignObservationChannels(mean, observation);
3435 addPriorMeanToObservation(observation);
3436 return;
3437 }
3438 const VarianceSubsetScope subset(variance_subset_configurations_,
3439 variance_subset_forced_ids_,
3440 state.background_subset_ids);
3441 calculateBackgroundPotentialDispatched(observation);
3442 const Eigen::VectorXd& weights = state.posterior.weights();
3443 EigenMatrix cross;
3444 calculateBackgroundObservationPosteriorCrossCovariance(
3445 observation.R, state.observations.R, cross, &weights);
3446 Eigen::VectorXd mean = observationChannels(observation) + cross.col(0);
3447 if (state.kernel) mean += state.residual_mean(observation.R);
3448 if (!mean.allFinite())
3449 throw std::invalid_argument("nonfinite conditional posterior mean");
3450 assignObservationChannels(mean, observation);
3451}
3452
3453void GaussianProcessRegression::calculateActivePosteriorCovariance(
3454 const EigenMatrix& positions, EigenMatrix& covariance)
3455{
3456 EigenMatrix prior, cross;
3457 activePosteriorCovarianceBlocks(positions, prior, cross);
3458 covariance = active_posterior_->posterior.predictCovariance(prior, cross);
3459}
3460
3461std::optional<JointObservationVarianceReduction>
3463 const EigenMatrix& positions, const Eigen::Index candidate_query,
3464 const std::vector<Eigen::Index>& target_queries,
3465 const double noise_variance, const bool allow_hssvd_local)
3466{
3467 const Eigen::Index count = positions.rows();
3468 const Eigen::Index dimensions = positions.cols();
3469 const Eigen::Index channels = dimensions + 1;
3470 if (count <= 0 || dimensions <= 0 || candidate_query < 0 ||
3471 candidate_query >= count || target_queries.empty() ||
3472 !positions.allFinite() || !std::isfinite(noise_variance) ||
3473 noise_variance < 0.0)
3474 return std::nullopt;
3475 std::vector<bool> seen(static_cast<std::size_t>(count), false);
3476 for (const Eigen::Index target: target_queries) {
3477 if (target < 0 || target >= count || seen[target]) return std::nullopt;
3478 seen[target] = true;
3479 }
3480 if (!active_posterior_ || !active_posterior_->kernel ||
3481 detail::matrixExactlyEqual(positions,
3482 active_posterior_->observations.R)) {
3483 EigenMatrix covariance;
3484 calculateObservationPosteriorCovariance(positions, covariance,
3485 allow_hssvd_local);
3487 covariance, count, dimensions, candidate_query, target_queries,
3488 noise_variance);
3489 }
3490
3491 requireActivePosteriorBackground();
3492 const auto& state = *active_posterior_;
3493 const VarianceSubsetScope subset(variance_subset_configurations_,
3494 variance_subset_forced_ids_,
3495 state.background_subset_ids);
3496 if (dimensions != state.observations.R.cols())
3497 throw std::invalid_argument("invalid active posterior query geometry");
3498 EigenMatrix background, whitened;
3499 calculateBackgroundObservationPosteriorCovariance(positions, background,
3500 false);
3501 {
3502 EigenMatrix cross;
3504 positions, state.observations.R, cross);
3505 cross += state.residual_cross(positions);
3506 whitened = state.posterior.whitenPredictionCrossCovariance(cross);
3507 }
3508 if (!background.allFinite()) return std::nullopt;
3509
3510 const Coord candidate_position = positions.middleRows(candidate_query, 1);
3511 EigenMatrix candidate =
3512 state.kernel->jointEnergyGradientCovariance(candidate_position);
3513 EigenMatrix candidate_whitened(whitened.rows(), channels);
3514 for (Eigen::Index channel = 0; channel < channels; ++channel)
3515 candidate_whitened.col(channel) =
3516 whitened.col(channel * count + candidate_query);
3517 candidate.noalias() -= candidate_whitened.transpose() * candidate_whitened;
3518 for (Eigen::Index row = 0; row < channels; ++row)
3519 for (Eigen::Index column = 0; column < channels; ++column)
3520 candidate(row, column) +=
3521 background(row * count + candidate_query,
3522 column * count + candidate_query);
3523
3524 // The same candidate precision weights serve every reference geometry.
3525 // Residual self blocks contribute only their force diagonal to the trace.
3526 const auto candidate_cross =
3527 makeKernelCrossCovariance(state.kernel, candidate_position);
3528 EigenMatrix target_candidate(target_queries.size() * dimensions, channels);
3529 double target_variance = 0.0;
3530 linalg::ExactSum stable_target_variance;
3531 linalg::ExactSum stable_target_signal;
3532 Eigen::Index first = 0;
3533 for (const Eigen::Index target: target_queries) {
3534 const Coord target_position = positions.middleRows(target, 1);
3535 const EigenMatrix residual_self =
3536 state.kernel->jointEnergyGradientCovariance(target_position);
3537 target_candidate.middleRows(first, dimensions) =
3538 candidate_cross(target_position).bottomRows(dimensions);
3539 for (Eigen::Index channel = 1; channel < channels; ++channel) {
3540 const Eigen::Index source = channel * count + target;
3542 stable_target_variance.add(background(source, source));
3543 stable_target_variance.add(residual_self(channel, channel));
3544 stable_target_signal.add(background(source, source));
3545 stable_target_signal.add(residual_self(channel, channel));
3546 for (Eigen::Index row = 0; row < whitened.rows(); ++row)
3547 stable_target_variance.addProduct(-whitened(row, source),
3548 whitened(row, source));
3549 } else {
3550 target_variance += background(source, source) +
3551 residual_self(channel, channel) -
3552 whitened.col(source).squaredNorm();
3553 }
3554 target_candidate.row(first + channel - 1).noalias() -=
3555 whitened.col(source).transpose() * candidate_whitened;
3556 for (Eigen::Index column = 0; column < channels; ++column)
3557 target_candidate(first + channel - 1, column) +=
3558 background(source, column * count + candidate_query);
3559 }
3560 first += dimensions;
3561 }
3563 target_variance = stable_target_variance.value();
3564 // The reduction subtracts squares of the active posterior's solve, so
3565 // the allowance is that factor's, asked for only if the value is
3566 // negative.
3568 target_variance, stable_target_signal.value(),
3569 target_variance < 0.0 ? state.posterior.schurRelativeError()
3570 : 0.0))
3571 return std::nullopt;
3572 }
3573 return jointObservationVarianceReduction(std::move(candidate),
3574 target_candidate, target_variance,
3575 noise_variance);
3576}
3577
3578double GaussianProcessRegression::calculateActivePosteriorFunctionalVariance(
3579 const EigenMatrix& positions, const Eigen::VectorXd& weights)
3580{
3581 requireActivePosteriorBackground();
3582 const auto& state = *active_posterior_;
3583 const VarianceSubsetScope subset(variance_subset_configurations_,
3584 variance_subset_forced_ids_,
3585 state.background_subset_ids);
3586 if (positions.cols() != state.observations.R.cols())
3587 throw std::invalid_argument("invalid active posterior query geometry");
3588 if (detail::matrixExactlyEqual(positions, state.observations.R)) {
3589 EigenMatrix covariance;
3590 calculateActivePosteriorCovariance(positions, covariance);
3591 return static_cast<double>(weights.cast<long double>().dot(
3592 covariance.cast<long double>() * weights.cast<long double>()));
3593 }
3594 EigenMatrix prior(1, 1), cross;
3595 prior(0, 0) =
3596 calculateBackgroundObservationFunctionalVariance(positions, weights);
3597 calculateBackgroundObservationPosteriorCrossCovariance(
3598 state.observations.R, positions, cross, &weights);
3599 if (state.kernel) {
3600 const EigenMatrix residual_prior =
3601 state.kernel->jointEnergyGradientCovariance(positions);
3602 prior(0, 0) += static_cast<double>(weights.cast<long double>().dot(
3603 residual_prior.cast<long double>() * weights.cast<long double>()));
3604 cross.col(0) +=
3605 (state.residual_cross(positions).transpose().cast<long double>() *
3606 weights.cast<long double>())
3607 .cast<double>();
3608 }
3609 return state.posterior.predictCovariance(prior, cross.transpose())(0, 0);
3610}
3611
3612bool GaussianProcessRegression::tryActivePosteriorEnergyVariance(
3613 const EigenMatrix& positions, Eigen::VectorXd& energy_variance)
3614{
3615 energy_variance.resize(0);
3616 requireActivePosteriorBackground();
3617 const auto& state = *active_posterior_;
3618 const Eigen::Index n = positions.rows();
3619 const Eigen::Index dimensions = positions.cols();
3620 if (n <= 0 || dimensions <= 0 || !positions.allFinite() ||
3621 dimensions != state.observations.R.cols() ||
3622 state.observations.R.rows() <= 0)
3623 return false;
3624 // On the conditioning rows the joint path uses the stable noise identity.
3625 // Anywhere else only the energy columns are consumed.
3626 if (positions.rows() == state.observations.R.rows() &&
3627 (positions.array() == state.observations.R.array()).all())
3628 return false;
3629 if (canUseHssvdVariance() || !hasTrainingCholeskyFactor(R_matrix.rows()) ||
3630 variance_subset_configurations_ > 0 ||
3631 !variance_subset_forced_ids_.empty())
3632 return false;
3633#ifdef GPR_LINALG_SCALAPACK
3634 if (training_cholesky_is_distributed_) return false;
3635#endif
3636 const Eigen::Index channels = dimensions + 1;
3637 const Eigen::Index active_rows = state.observations.R.rows();
3638 if (state.posterior.channels() != active_rows * channels) return false;
3639
3640 EigenMatrix energy_rows(n, dimensions + 1);
3641 energy_rows.leftCols(dimensions) = positions;
3642 energy_rows.col(dimensions).setZero();
3643 const Eigen::VectorXd energy_index = Eigen::VectorXd::Zero(n);
3644
3645 EigenMatrix energy_gram;
3646 evaluateCovarianceMatrix(energy_rows, energy_rows, energy_index,
3647 energy_index, energy_gram,
3648 /*serial_per_rank=*/true);
3649 if (energy_gram.rows() != n || energy_gram.cols() != n ||
3650 !energy_gram.allFinite())
3651 return false;
3652 const Eigen::VectorXd prior_diag = energy_gram.diagonal();
3653
3654 EigenMatrix training_energy;
3655 evaluateCovarianceMatrix(R_matrix, energy_rows, R_indices, energy_index,
3656 training_energy, /*serial_per_rank=*/true);
3657 training_energy = permuteTrainingRows(training_energy);
3658 if (training_energy.rows() != R_matrix.rows() ||
3659 training_energy.cols() != n || !training_energy.allFinite() ||
3660 !hasTrainingCholeskyFactor(training_energy.rows()))
3661 return false;
3662 const bool deflated_active =
3663 rigid_deflation_.isActiveForFullOrder(training_energy.rows());
3664 const EigenMatrix energy_proj =
3665 deflated_active ? rigid_deflation_.projectRows(training_energy)
3666 : training_energy;
3667 Eigen::VectorXd variance;
3668 if (linalg::stablePosteriorVarianceEnabled())
3669 variance =
3670 trainingSolver().posteriorVarianceDiagonal(energy_proj, prior_diag);
3671 else
3672 variance = prior_diag - trainingSolver().quadraticDiagonal(energy_proj);
3673 if (variance.size() != n || !variance.allFinite()) return false;
3674 // The stable variance came from a conditioned Schur diagonal, which has
3675 // already been checked against the factor's allowance and clamped.
3676 if (!linalg::stablePosteriorVarianceEnabled()) {
3677 for (Eigen::Index i = 0; i < n; ++i) {
3678 const double scale = std::max(1.0, std::abs(prior_diag(i)));
3679 const double roundoff =
3680 std::numeric_limits<double>::epsilon() * scale;
3681 if (variance(i) < 0.0 && std::abs(variance(i)) <= roundoff)
3682 variance(i) = 0.0;
3683 }
3684 }
3685 variance *= outputVarianceScaleSquared();
3686
3688 EigenMatrix active_rows_rep;
3689 Eigen::VectorXd active_index;
3690 layout.assembleMatrixOfRepetitiveCoordinates(state.observations.R,
3691 active_rows_rep, active_index);
3692 EigenMatrix cross;
3693 evaluateCovarianceMatrix(energy_rows, active_rows_rep, energy_index,
3694 active_index, cross, /*serial_per_rank=*/true);
3695 EigenMatrix training_active;
3696 evaluateCovarianceMatrix(R_matrix, active_rows_rep, R_indices, active_index,
3697 training_active, /*serial_per_rank=*/true);
3698 training_active = permuteTrainingRows(training_active);
3699 if (cross.rows() != n || cross.cols() != active_rows * channels ||
3700 training_active.rows() != training_energy.rows() ||
3701 training_active.cols() != cross.cols() || !cross.allFinite() ||
3702 !training_active.allFinite())
3703 return false;
3704#ifdef GPR_LINALG_KOKKOS
3705 materializeDeviceFactor();
3706#endif
3707 if (deflated_active) {
3708 const EigenMatrix active_proj =
3709 rigid_deflation_.projectRows(training_active);
3710 subtractCholeskyCross(backend(), L, energy_proj, active_proj, cross);
3711 } else {
3712 subtractCholeskyCross(backend(), L, training_energy, training_active,
3713 cross);
3714 }
3715 cross *= outputVarianceScaleSquared();
3716
3717 if (state.kernel) {
3718 variance += state.kernel->energyDiagonal(positions);
3719 for (Eigen::Index channel = -1; channel < dimensions; ++channel) {
3720 const Eigen::Index column0 = (channel + 1) * active_rows;
3721 cross.block(0, column0, n, active_rows) +=
3722 state.kernel->covarianceBlock(positions, state.observations.R,
3723 -1, channel);
3724 }
3725 }
3726 if (!variance.allFinite() || !cross.allFinite()) return false;
3727 variance = state.posterior.predictVariance(variance, cross);
3728 if (variance_convention_ == VarianceConvention::Predictive) {
3729 variance +=
3730 likelihoodDiagonal(energy_rows) * outputVarianceScaleSquared();
3731 }
3732 variance *= reportedVarianceCalibrationFactor();
3733 if (variance.size() != n || !variance.allFinite()) return false;
3734 ++active_energy_variance_solves_for_testing_;
3735 energy_variance = std::move(variance);
3736 return true;
3737}
3738
3739void GaussianProcessRegression::calculateActivePosteriorVariance(
3740 Observation& observation)
3741{
3742 ScopedVarianceTimer variance_timer;
3743 requireActivePosteriorBackground();
3744 const auto& state = *active_posterior_;
3745 const VarianceSubsetScope subset(variance_subset_configurations_,
3746 variance_subset_forced_ids_,
3747 state.background_subset_ids);
3748 Eigen::VectorXd variance;
3749 if (detail::matrixExactlyEqual(observation.R, state.observations.R)) {
3750 EigenMatrix covariance;
3751 calculateActivePosteriorCovariance(observation.R, covariance);
3752 variance = covariance.diagonal();
3753 } else {
3754 if (observation.R.cols() != state.observations.R.cols() ||
3755 !observation.R.allFinite())
3756 throw std::invalid_argument(
3757 "invalid active posterior query geometry");
3758 if (observation.R.rows() == 0) {
3759 observation.E.resize(1, 0);
3760 observation.G.resize(0, observation.R.cols());
3761 return;
3762 }
3763 EigenMatrix diagonal, cross;
3764 calculateBackgroundObservationMarginalAndCrossCovariance(
3765 observation.R, state.observations.R, diagonal, cross);
3766 variance = diagonal.col(0);
3767 if (state.kernel) {
3768 variance +=
3769 state.kernel->jointEnergyGradientDiagonal(observation.R);
3770 cross += state.residual_cross(observation.R);
3771 }
3772 variance = state.posterior.predictVariance(variance, cross);
3773 }
3774 if (variance_convention_ == VarianceConvention::Predictive) {
3775 EigenMatrix rows;
3776 Eigen::VectorXd indices;
3778 observation.R, rows, indices);
3779 variance += likelihoodDiagonal(rows) * outputVarianceScaleSquared();
3780 }
3781 // Reported uncertainty retains the background's calibration convention;
3782 // the joint covariance operator carries the latent statistical covariance.
3783 variance *= reportedVarianceCalibrationFactor();
3784 assignObservationChannels(variance, observation);
3785}
3786
3787} // namespace gpr
@ y
Definition Enums.h:28
@ MOVING_ATOM
Definition Enums.h:35
Correctly rounded Schur-complement diagonals from Cholesky solves.
Exact floating-point accumulator (Kulisch long accumulator).
void assembleMatrixOfRepetitiveCoordinates(const gpr::Coord &coord, gpr::EigenMatrix &matrix, Eigen::VectorXd &ind)
Assemble Eigen matrix with repetitive rows based on provided set of coordinates R.
Methods to calculate distances between atoms.
Definition Distance.h:154
void dist_at(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale, gpr::FieldMatrixd &dist, bool take_sqrt=true)
Give the distance between two atomic configurations as defined in the special GPstuff covariance func...
Definition Distance.cpp:620
void setAlgorithmSettings(const gpr::ScgOptimizationSettings &s)
Definition RgminOpt.h:44
void setMethod(rgmin::Method m) noexcept
Definition RgminOpt.h:49
void optimize(const gpr::EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &w, FuncName func_to_min, ClassName &holder, double, const Eigen::VectorXd &lengthscale_rho0=Eigen::VectorXd(), const MapObjectiveConfig *objective_config=nullptr)
Definition RgminOpt.inl:19
void setBox(Eigen::VectorXd lower, Eigen::VectorXd upper)
Coordinate box on x + p. Empty is unbounded on that side.
Definition RgminOpt.h:136
static Eigen::VectorXd contractJointLogLengthDerivatives(const std::vector< PairFeatures > &features, const std::vector< Pair > &pairs, Eigen::Index dimensions, const Eigen::VectorXd &length_scales, double magnitude_variance, const std::vector< Eigen::Index > &types, const Eigen::MatrixXd &weight, const linalg::MpiContext &communication=linalg::MpiContext::local(), const linalg::LocalExecutor &execution=linalg::LocalExecutor{})
static std::vector< Eigen::MatrixXd > jointWithLogLengthDerivatives(const std::vector< PairFeatures > &features, const std::vector< Pair > &pairs, Eigen::Index dimensions, const Eigen::VectorXd &length_scales, double magnitude_variance, const std::vector< Eigen::Index > &types, const linalg::MpiContext &communication=linalg::MpiContext::local(), const linalg::LocalExecutor &execution=linalg::LocalExecutor{})
static SpeciesEnvironmentKernel::Descriptor forConfiguration(const AtomsConfiguration &configuration, double cutoff=4.0, bool gradients=true)
linalg::BackendContext & backend() const
Eigen::VectorXd unpermuteTrainingVector(const Eigen::VectorXd &input) const
ActivePosteriorRestorePoint retainActivePosterior() const
const Eigen::MatrixXd & secantQuadraticHessian() const
bool prepareTrainingKernelGeometry(const EigenMatrix &x, const Eigen::VectorXd &x_ind, TrainingKernelGeometry &out, bool reused=false) const
bool calculateExactDirectionalCurvature(const Coord &R, const Eigen::VectorXd &direction, double &curvature)
bool refreshActivePosterior(const Observation &full_observation)
std::vector< int > selectOptimizationSubsetRows(const Observation &full_observation) const
Select a hyperparameter-optimization subset via FPS-EMD.
std::function< bool(const Eigen::VectorXd &, Eigen::VectorXd &)> MeanHessianAction
bool calculateMeanHessianVectorDispatched(const Coord &R, const Eigen::VectorXd &direction, Eigen::VectorXd &hessian_vector)
std::unique_ptr< SexpatCF > sexpat_cov_func
bool prepareMeanHessianVectorHssvd(const Coord &R, PreparedHssvdHessianVector &prepared) const
bool calculateMeanHessian(const Coord &R, Eigen::MatrixXd &hessian)
Dense Hessian of the physical posterior mean at one geometry.
bool fitActivePosterior(const Observation &full_observation, const std::vector< bool > &active_lengths, bool compare_cartesian_residual=false)
void calculateBackgroundObservationPosteriorCrossCovariance(const EigenMatrix &left, const EigenMatrix &right, EigenMatrix &covariance, const Eigen::VectorXd *mean_weights=nullptr)
Definition Variance.cpp:906
void calculatePotentialDispatched(Observation &image1)
Definition Predict.cpp:982
void updateModelWithFullData(const Observation &full_observation)
void calculateObservationPosteriorCovariance(const EigenMatrix &positions, EigenMatrix &K_post, bool allow_hssvd_local=true)
MeanHessianAction prepareAnalyticMeanHessian(const Coord &R)
std::shared_ptr< const KernelOperator > makeActiveCovarianceOperator(const Eigen::VectorXd &theta, const std::vector< bool > &active_lengths) const
Eigen::Index activePosteriorObservationCount() const noexcept
void setEnvironmentResiduals(bool enabled)
bool applyMeanHessianBlockHssvd(const PreparedHssvdHessianVector &prepared, const Eigen::MatrixXd &directions, Eigen::MatrixXd &hessian_block) const
bool conditionActivePosterior(const Observation &full_observation, std::shared_ptr< const KernelOperator > active_kernel={})
std::optional< JointObservationVarianceReduction > calculateObservationForceVarianceReduction(const EigenMatrix &positions, Eigen::Index candidate_query, const std::vector< Eigen::Index > &target_queries, double noise_variance, bool allow_hssvd_local=true)
bool restoreActivePosterior(const ActivePosteriorRestorePoint &point, const Observation &full_observation)
bool hasTrainingCholeskyFactor(Eigen::Index expected_rows) const noexcept
MeanHessianAction prepareMeanHessian(const Coord &R)
Linear action of the physical posterior mean at one geometry.
Eigen::VectorXd calculateObservationNoiseDiagonal(const EigenMatrix &positions) const
Definition Variance.cpp:550
MixtureMeanHessianStatus calculateLaplaceMixtureMeanHessianVector(const Coord &R, const Eigen::VectorXd &direction, Eigen::VectorXd &hessian_vector)
static void computeDirectionalFeatures(const Coord &x, const AtomsConfiguration &conf_info, const Eigen::VectorXd &direction, Eigen::VectorXd &phi, Eigen::VectorXd &rates, std::vector< int > &pairtypes)
std::function< HessianAction(const Eigen::VectorXd &)> MeanHessianPreparation
std::function< MeanHessianStatus( const Eigen::VectorXd &, Eigen::MatrixXd &)> MeanHessianMatrixFunction
std::function< Eigen::VectorXd(const Eigen::MatrixXd &)> MeanFunction
std::function< Eigen::MatrixXd(const Eigen::MatrixXd &)> CrossCovarianceFunction
const LocalExecutor & local() const noexcept
const std::shared_ptr< const EnvironmentGpuExecutor > & environmentGpu() const noexcept
void addProduct(double a, double b) noexcept
Definition ExactSum.h:70
void add(double x) noexcept
Definition ExactSum.h:54
double value() const noexcept
The exact sum rounded once to the nearest double, ties to even.
Definition ExactSum.h:190
int status
void restoreMapAmplitudeFeasibility(Eigen::VectorXd &w, const MapObjectiveConfig &cfg)
MapObjectiveConfig makeMapObjectiveConfig(const gpr::EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::VectorXd &w, double current_barrier_strength, const Eigen::VectorXd &lengthscale_rho0, const gpr::ScgOptimizationSettings &settings, bool robust_signal_anchor=true)
void applyMapPenalty(const Eigen::VectorXd &w, const MapObjectiveConfig &cfg, double &energy, Eigen::VectorXd *gradient)
bool mapParametersInDomain(const Eigen::VectorXd &w, const MapObjectiveConfig &cfg)
Eigen::VectorXd assemble(const DeviceEnvironments &left_environments, const DeviceEnvironments &right_environments, const gpr::detail::EnvironmentPairBatch &batch, std::size_t scratch_bytes)
bool stablePosteriorVarianceEnabled() noexcept
Whether stable posterior variance reductions are enabled.
Definition ExactSchur.h:40
bool acceptStablePosteriorVariance(double &variance, double signal_variance, double relative_allowance) noexcept
Accept one stable posterior variance.
Definition ExactSchur.h:86
void addPriorHessianPairs(const std::vector< PriorHessianPair > &pairs, Eigen::MatrixXd &hessian)
Add the same pair blocks to a dense Cartesian Hessian.
Eigen::MatrixXd applyPriorHessianPairs(const std::vector< PriorHessianPair > &pairs, const Eigen::MatrixBase< Derived > &directions)
Apply physical prior curvature without forming a dense Hessian.
double variance(const Weights &w, const Matrix &covariance)
VecchiaResult evaluate(const Eigen::MatrixXd &points, const Eigen::VectorXd &y, double lengthscale, double noise, int max_neighbours)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
KernelOperator::CrossCovarianceFunction makeKernelCrossCovariance(std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training)
std::function< bool( const Eigen::VectorXd &, Eigen::VectorXd &, bool &exact_refusal)> RefusalAwareHessianAction
Hessian action that reports whether an exact child refused.
FieldMatrixd Coord
Definition Macros.h:35
std::optional< JointObservationVarianceReduction > jointObservationVarianceReduction(Eigen::MatrixXd candidate_covariance, const Eigen::MatrixXd &target_candidate_covariance, const double target_variance, const double noise_variance)
std::function< RefusalAwareHessianAction( const Eigen::VectorXd &, bool &exact_refusal)> RefusalAwareHessianPreparation
Query preparation that reports whether an exact child refused.
double lengthscaleProjectionFloor(double max_pair_distance, double absolute_floor)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
KernelOperator::MeanHessianMatrixFunction makeKernelMeanHessianMatrix(std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights)
Dense mean Hessian of a kernel from the columns of its refusal-aware action. A failed column is Refus...
KernelOperator::MeanHessianPreparation makeKernelMeanHessian(std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
RefusalAwareHessianPreparation makeRefusalAwareKernelMeanHessian(std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights, bool *all_exact, bool *has_exact_or_refusal)
Prepare a fitted kernel Hessian action that propagates exact-child refusals through composite operato...
std::optional< JointObservationVarianceReduction > jointObservationForceVarianceReduction(const Eigen::MatrixXd &posterior_covariance, const Eigen::Index query_count, const Eigen::Index dimensions, const Eigen::Index candidate_query, const std::vector< Eigen::Index > &target_queries, const double noise_variance)
Integrated force-variance reduction from one joint energy-force query.
KernelOperator::MeanFunction makeKernelMean(std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights)
Owning fitted mean, using the kernel's representation or its exact product.
STL namespace.
Eigen::VectorXd parameter_lower
Eigen::VectorXd parameter_upper
ActivePosteriorState(Observation data, std::shared_ptr< const KernelOperator > active_kernel, ConditionalPosterior fitted, LaplacePosteriorStamp background_stamp, double mean, double scale, bool use_hssvd)
std::shared_ptr< const AdditivePairKernel > additive_kernel
std::shared_ptr< const SpeciesEnvironmentKernel > environment_kernel
KernelOperator::MeanHessianPreparation residual_hessian
std::shared_ptr< const ManifoldEnergyForceKernel > cartesian_kernel
KernelOperator::MeanHessianMatrixFunction background_hessian_matrix
KernelOperator::MeanHessianMatrixFunction residual_hessian_matrix
KernelOperator::CrossCovarianceFunction residual_cross
std::shared_ptr< const KernelOperator > kernel
KernelOperator::MeanHessianPreparation background_hessian
Observation data: energy, gradient and positions.
static long chart_max_joint_rows
static int support_expansions
static long factorization_rows
static int pair_objective_count
static long objective_channels
static double pair_contraction_seconds
static double support_seconds
static double chart_objective_seconds
static int factorization_count
static double objective_seconds
static double factorization_seconds
static double support_refit_seconds
static double pair_objective_seconds
static double projection_factor_seconds
static int support_refit_count
static double assembly_seconds
static double gradient_seconds
static int chart_objective_count
static double correction_seconds
static long pair_max_joint_rows
static double projection_solve_seconds
static double pair_covariance_seconds
static int gradient_count
static double residual_seconds
Residual-kernel candidate fits of the active correction.
static long objective_rows
static int objective_count