Loading...
Searching...
No Matches
SexpatCF.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/*
6 * SexpAt.cpp
7 *
8 * Created on: 8 Oct 2020
9 * Author: Maxim Masterov
10 * Company: SURFSara
11 */
12
13#include "SexpatCF.h"
14
18#include "KernelOperator.h"
19#if defined(USE_OPENMP) || defined(GPR_OPENMP_LOCAL_ORACLE)
20#include <omp.h>
21#endif
22
23namespace gpr {
24
25// Thread-local switch indicating whether the current thread is inside
26// the local-oracle (serial_per_rank=true) gradient region, e.g. the
27// SVGD per-particle oracle. SCG / MAP path keeps this false; the SVGD
28// oracle wraps the grad_oracle lambda in a RAII guard that flips it
29// to true so the OpenMP pragmas inside SexpatCF::calculateGradOf-
30// CovMatrixWithDerivatives* activate without contending with
31// distributed Cholesky / pdtrsm in the SCG path.
32//
33// The SexpatCF gradient kernels dominate the local-oracle cost, so the
34// carve-out is closest to the work it gates.
35thread_local bool sexpat_local_oracle_active = false;
36
37} // namespace gpr
38
39#include <algorithm>
40#include <cfloat>
41#include <limits>
42#include <memory>
43#include <stdexcept>
44#include <utility>
45
51#include "../prior/PriorSqrtt.h"
52
53namespace gpr {
54
55namespace {
56
57// Defined below. Every stored entry takes the packet exponential, so the
58// result does not depend on the entry's offset or on the length.
59void scaledExpOfHalfNegative(double* data, Eigen::Index size, double magnitude);
60
61// A parameter derivative belongs to its primitive, independently of the
62// covariance weights carried by other summands.
63class PrimitiveKernelScope {
64public:
65 explicit PrimitiveKernelScope(bool& composition)
66 : composition_(composition),
67 previous_(std::exchange(composition, false))
68 {
69 }
70 ~PrimitiveKernelScope()
71 {
72 composition_ = previous_;
73 }
74 PrimitiveKernelScope(const PrimitiveKernelScope&) = delete;
75 PrimitiveKernelScope& operator=(const PrimitiveKernelScope&) = delete;
76
77private:
78 bool& composition_;
79 bool previous_;
80};
81
82struct Dual2 {
83 double value = 0.0;
84 double first = 0.0;
85 double second = 0.0;
86};
87
88inline Dual2 constant_dual(double value)
89{
90 return {value, 0.0, 0.0};
91}
92
93inline Dual2 direction_dual(double value, double direction)
94{
95 return {value, direction * value, direction * direction * value};
96}
97
98inline Dual2 operator+(const Dual2& a, const Dual2& b)
99{
100 return {a.value + b.value, a.first + b.first, a.second + b.second};
101}
102
103inline Dual2 operator-(const Dual2& a, const Dual2& b)
104{
105 return {a.value - b.value, a.first - b.first, a.second - b.second};
106}
107
108inline Dual2 operator*(const Dual2& a, const Dual2& b)
109{
110 return {a.value * b.value, a.first * b.value + a.value * b.first,
111 a.second * b.value + 2.0 * a.first * b.first + a.value * b.second};
112}
113
114inline Dual2 operator*(double scalar, const Dual2& a)
115{
116 return {scalar * a.value, scalar * a.first, scalar * a.second};
117}
118
119inline Dual2 operator/(const Dual2& a, const Dual2& b)
120{
121 const double inv = 1.0 / b.value;
122 const double inv2 = inv * inv;
123 const double inv3 = inv2 * inv;
124 const Dual2 inv_b{inv, -b.first * inv2,
125 2.0 * b.first * b.first * inv3 - b.second * inv2};
126 return a * inv_b;
127}
128
129bool resize_geometry_gradient_blocks(std::vector<FieldMatrixd>& blocks,
130 std::size_t n_blocks, Eigen::Index rows,
131 Eigen::Index cols)
132{
133 if (n_blocks == 0 || rows <= 0 || cols <= 0) return false;
134 blocks.resize(n_blocks);
135 for (FieldMatrixd& block: blocks) {
136 if (block.rows() != rows || block.cols() != cols) {
137 block.resize(rows, cols);
138 }
139 }
140 return true;
141}
142
143bool valid_gradient_parameter_selection(
144 const std::vector<Eigen::Index>* indices, Eigen::Index parameter_count)
145{
146 if (indices == nullptr) return true;
147 return !indices->empty() &&
148 std::all_of(indices->begin(), indices->end(),
149 [parameter_count](Eigen::Index index) {
150 return index >= 0 && index < parameter_count;
151 });
152}
153
154inline Dual2 log_dual(const Dual2& a)
155{
156 const double inv = 1.0 / a.value;
157 return {numerics::log(a.value), a.first * inv,
158 a.second * inv - a.first * a.first * inv * inv};
159}
160
161inline Dual2 sqrt_dual(const Dual2& a)
162{
163 const double root = std::sqrt(a.value);
164 const double inv2root = 0.5 / root;
165 return {root, a.first * inv2root,
166 a.second * inv2root - 0.25 * a.first * a.first / (a.value * root)};
167}
168
169struct DirectionalKernelScalars {
170 double sigma_dir = 0.0;
171 Eigen::VectorXd length_dir;
172};
173
174DirectionalKernelScalars unpack_direction(const SexpatCF& cov_func,
175 const Eigen::VectorXd& direction)
176{
177 DirectionalKernelScalars unpacked;
178 unpacked.sigma_dir = direction.size() > 0 ? direction(0) : 0.0;
179
180 const Eigen::Index n_ls = cov_func.getLengthScaleRef().size();
181 unpacked.length_dir.resize(n_ls);
182 unpacked.length_dir.setZero();
183 for (Eigen::Index i = 0; i < n_ls && i + 1 < direction.size(); ++i)
184 unpacked.length_dir(i) = direction(i + 1);
185 return unpacked;
186}
187
188inline double expanded_length_direction(const Eigen::VectorXd& direction,
189 Eigen::Index idx)
190{
191 if (direction.size() == 0) return 0.0;
192 return direction.size() == 1 ? direction(0) : direction(idx);
193}
194
195inline void accumulate_directional_pt_fields(
196 const std::vector<FieldMatrixd>& pt_fields,
197 const Eigen::VectorXd& direction, double linear_scale,
198 double quadratic_scale, FieldMatrixd& first, FieldMatrixd& second)
199{
200 if (pt_fields.empty()) return;
201
202 if (first.size() == 0) {
203 first.resize(pt_fields[0].rows(), pt_fields[0].cols());
204 first.setZero();
205 second.resize(pt_fields[0].rows(), pt_fields[0].cols());
206 second.setZero();
207 }
208
209 for (Eigen::Index pt = 0; pt < static_cast<Eigen::Index>(pt_fields.size());
210 ++pt) {
211 const double dir = expanded_length_direction(direction, pt);
212 first.noalias() += linear_scale * dir * pt_fields[pt];
213 second.noalias() += quadratic_scale * dir * dir * pt_fields[pt];
214 }
215}
216
217inline void compute_kernel_prefactors(const FieldMatrixd& K,
218 const std::vector<FieldMatrixd>& dist_pt,
219 const Eigen::VectorXd& direction,
220 double sigma_dir, FieldMatrixd& k1,
221 FieldMatrixd& k2)
222{
223 k1.resize(K.rows(), K.cols());
224 k1.setConstant(sigma_dir);
225 FieldMatrixd s2_term = FieldMatrixd::Zero(K.rows(), K.cols());
226 for (Eigen::Index pt = 0; pt < static_cast<Eigen::Index>(dist_pt.size());
227 ++pt) {
228 const double dir = expanded_length_direction(direction, pt);
229 k1.array() -= dir * dist_pt[pt].array();
230 s2_term.array() += dir * dir * dist_pt[pt].array();
231 }
232
233 k2 = (k1.array().square() + 2.0 * s2_term.array()).matrix();
234}
235
236inline FieldMatrixd evaluate_kernel_matrix(const SexpatCF& cov_func,
237 const Coord& x1, Coord& x2)
238{
239 if (x2.size() == 0) x2 = x1;
240 return Sexpat(cov_func).covarianceBlock(x1, x2, -1, -1);
241}
242
243} // namespace
244
246{
247 clear();
248}
249
251{
252 clear();
253}
254
256{
257 const auto& active_lengths = getLengthScaleRef();
258 // CHEMGP and GPRD_ZBL: original Sexpat prior density from the published
259 // C++ dimer path (gprd_zbl subrepo SexpatCF.cpp).
260 if (usesClassicJointEnergyForcePrior(model_profile_)) {
261 PriorGaussian prior_gaussian;
262 PriorSqrtt prior_sqrtt;
263 FieldMatrixd magn_sigma2(1, 1);
264 magn_sigma2(0, 0) = magnSigma2;
265 prior_gaussian.setParameters(prior_parameters_gaussian);
266 prior_sqrtt.setParameters(prior_parameters_sqrtt);
267
268 double lp = 0.0;
269 if (use_lognormal_magn_prior_ &&
270 prior_parameters_lognormal.getS2() > 0.0) {
271 // Log-normal support is the positive reals. A non-positive
272 // amplitude is rejected; a huge finite one stays finite.
273 if (!(magnSigma2 > 0.0) || !std::isfinite(magnSigma2))
274 return -std::numeric_limits<double>::infinity();
275 PriorLogNormal prior_lognormal;
276 prior_lognormal.setParameters(prior_parameters_lognormal);
277 lp = prior_lognormal.calculateLogPrior(magn_sigma2) +
278 numerics::log(magnSigma2);
279 } else {
280 lp = prior_sqrtt.calculateLogPrior(magn_sigma2) +
281 numerics::log(magnSigma2);
282 }
283 FieldMatrixd one(1, 1);
284 const bool anchors_ready =
285 use_hierarchical_prior_ &&
286 hierarchical_mu_log_.size() == 1 + active_lengths.size();
287 for (Eigen::Index n = 0; n < active_lengths.size(); ++n) {
288 const double length = *(active_lengths.data() + n);
289 const double s2 = hierarchicalPriorVariance(n + 1);
290 if (anchors_ready && hierarchicalAnchored(n) && s2 > 0.0) {
291 // The population's log-Gaussian on this pair type.
292 const double d =
293 numerics::log(length) - hierarchical_mu_log_(n + 1);
294 lp -= lengthPriorWeight(n) * 0.5 *
295 (numerics::log(2.0 * M_PI) + numerics::log(s2) +
296 d * d / s2);
297 continue;
298 }
299 one(0, 0) = length;
300 lp +=
301 lengthPriorWeight(n) *
302 (prior_gaussian.calculateLogPrior(one) + numerics::log(length));
303 }
304 return lp;
305 }
306
307 // Non-hierarchical global GPs use the SCG objective priors as the
308 // single regularisation source: half-Cauchy on sigma_m and
309 // half-Student-t on each lengthscale, annealed by N_eff via
310 // current_barrier_strength. The hierarchical branch is the per-image
311 // GP path and uses this object's packed log-parameter Gaussian prior.
312 if (use_hierarchical_prior_) {
313 // Hierarchical-Bayes Gaussian on the packed *log-space*
314 // parameters: ~theta_log = [log(magnSigma2),
315 // log(active_lengths[0]), ..., log(active_lengths[K-1])] ~ N(mu_log,
316 // s2_log * I)~. The density operates in log-space directly
317 // (the SCG optimiser runs on these packed log-parameters), so
318 // no linear-to-log Jacobian terms are added.
319 const Eigen::Index expected = 1 + active_lengths.size();
320 if (hierarchical_mu_log_.size() != expected) {
321 return 0.0; // shape mismatch: silently no-op the prior term
322 }
323 // Each packed parameter has its own variance (the shared one
324 // unless the population prior set a pair type's width); a
325 // parameter without a positive width carries no term.
326 const double log_2_pi = numerics::log(2.0 * M_PI);
327 double lp = 0.0;
328 const double s2_m = hierarchicalPriorVariance(0);
329 if (s2_m > 0.0) {
330 const double dm =
331 numerics::log(magnSigma2) - hierarchical_mu_log_(0);
332 lp -= 0.5 * (log_2_pi + numerics::log(s2_m)) + 0.5 * dm * dm / s2_m;
333 }
334 for (Eigen::Index n = 0; n < active_lengths.size(); ++n) {
335 const double s2 = hierarchicalPriorVariance(n + 1);
336 if (!(s2 > 0.0)) continue;
337 const double log_ls = numerics::log(*(active_lengths.data() + n));
338 const double dl = log_ls - hierarchical_mu_log_(n + 1);
339 const double weight = lengthPriorWeight(n);
340 lp -= 0.5 * weight * (log_2_pi + numerics::log(s2) + dl * dl / s2);
341 }
342 return lp;
343 }
344
345 // Global GP: Penalized-Complexity length-scale prior, if set. In the packed
346 // log-space parameters (theta = log rho) the PC range prior transforms
347 // (Jacobian drho/dtheta = rho) to
348 // log pi_theta = log(lambda) - log(rho) - lambda/rho.
349 // As rho -> 0 the -lambda/rho term -> -inf, conditioning the optimiser
350 // never to collapse a length scale into a near-singular kernel. magnSigma2
351 // (index 0) is unpenalised.
352 if (use_pc_lengthscale_prior_ &&
353 pc_lambda_.size() == active_lengths.size()) {
354 double lp = 0.0;
355 for (Eigen::Index n = 0; n < active_lengths.size(); ++n) {
356 const double rho = *(active_lengths.data() + n);
357 const double lam = pc_lambda_(n);
358 if (lam > 0.0 && rho > 0.0)
359 lp += lengthPriorWeight(n) *
360 (numerics::log(lam) - numerics::log(rho) - lam / rho);
361 }
362 return lp;
363 }
364 // Otherwise flat; regularisation stays in the SCG barrier terms.
365 // The opt-in log-normal magnitude prior is applied by the MAP
366 // objective on this path, so it is not added a second time here.
367 return 0.0;
368}
369
371{
372 const auto& active_lengths = getLengthScaleRef();
373 FieldMatrixd lpg;
374 Eigen::Index num_length_scales = active_lengths.size();
375
376 if (usesClassicJointEnergyForcePrior(model_profile_)) {
377 PriorGaussian prior_gaussian;
378 PriorSqrtt prior_sqrtt;
379 FieldMatrixd magn_sigma2(1, 1);
380 magn_sigma2(0, 0) = magnSigma2;
381 prior_gaussian.setParameters(prior_parameters_gaussian);
382 prior_sqrtt.setParameters(prior_parameters_sqrtt);
383
384 lpg.resize(1, 1 + num_length_scales);
385 if (use_lognormal_magn_prior_ &&
386 prior_parameters_lognormal.getS2() > 0.0) {
387 if (!(magnSigma2 > 0.0) || !std::isfinite(magnSigma2)) {
388 lpg(0, 0) = std::numeric_limits<double>::quiet_NaN();
389 } else {
390 const double log_m = numerics::log(magnSigma2);
391 lpg(0, 0) = -(log_m - prior_parameters_lognormal.getMu()) /
392 prior_parameters_lognormal.getS2();
393 }
394 } else {
395 const FieldMatrixd magn_gradient =
396 prior_sqrtt.calculateLogPriorGradient(magn_sigma2);
397 lpg(0, 0) = magn_gradient(0, 0) * magnSigma2 + 1.0;
398 }
399 const FieldMatrixd length_gradient =
400 prior_gaussian.calculateLogPriorGradient(active_lengths);
401 const bool anchors_ready =
402 use_hierarchical_prior_ &&
403 hierarchical_mu_log_.size() == 1 + num_length_scales;
404 for (Eigen::Index n = 0; n < num_length_scales; ++n) {
405 const double length = *(active_lengths.data() + n);
406 const double s2 = hierarchicalPriorVariance(n + 1);
407 if (anchors_ready && hierarchicalAnchored(n) && s2 > 0.0) {
408 lpg(0, 1 + n) =
409 -lengthPriorWeight(n) *
410 (numerics::log(length) - hierarchical_mu_log_(n + 1)) / s2;
411 continue;
412 }
413 lpg(0, 1 + n) = lengthPriorWeight(n) *
414 (*(length_gradient.data() + n) * length + 1.0);
415 }
416 return lpg;
417 }
418
419 if (use_hierarchical_prior_) {
420 // Gradient of the hierarchical Gaussian log-prior wrt the
421 // packed log-parameters: ~d/d(log(theta_j)) [-0.5 (log(theta_j)
422 // - mu_log_j)^2 / s2_log] = -(log(theta_j) - mu_log_j) /
423 // s2_log~. No linear-to-log Jacobian terms because the prior
424 // already lives in log-space; this is the direct gradient that
425 // the SCG optimiser adds to the data NLML gradient.
426 lpg.resize(1, 1 + num_length_scales);
427 const Eigen::Index expected = 1 + num_length_scales;
428 lpg.setZero();
429 if (hierarchical_mu_log_.size() != expected) return lpg;
430 const double s2_m = hierarchicalPriorVariance(0);
431 if (s2_m > 0.0)
432 lpg(0, 0) =
433 -(numerics::log(magnSigma2) - hierarchical_mu_log_(0)) / s2_m;
434 for (Eigen::Index n = 0; n < num_length_scales; ++n) {
435 const double s2 = hierarchicalPriorVariance(n + 1);
436 if (!(s2 > 0.0)) continue;
437 const double log_ls = numerics::log(*(active_lengths.data() + n));
438 lpg(0, 1 + n) = -lengthPriorWeight(n) *
439 (log_ls - hierarchical_mu_log_(n + 1)) / s2;
440 }
441 return lpg;
442 }
443
444 // Global GP gradient mirror. Zero unless the PC length-scale prior is set:
445 // d/dtheta log pi_theta = -1 + lambda/rho per length scale (magnSigma2,
446 // index 0, unpenalised). As rho -> 0 this -> +inf, pushing the optimiser
447 // away from collapse.
448 lpg.resize(1, 1 + num_length_scales);
449 lpg.setZero();
450 if (use_pc_lengthscale_prior_ && pc_lambda_.size() == num_length_scales) {
451 for (Eigen::Index n = 0; n < num_length_scales; ++n) {
452 const double rho = *(active_lengths.data() + n);
453 const double lam = pc_lambda_(n);
454 if (lam > 0.0 && rho > 0.0)
455 lpg(0, 1 + n) = lengthPriorWeight(n) * (-1.0 + lam / rho);
456 }
457 }
458 return lpg;
459}
460
462 FieldMatrixd& C)
463{
464 if (compose_operators_) {
465 if (auto op = assembledOperator()) {
466 if (x2.size() == 0) x2 = x1;
467 if (usesManifoldChart()) {
468 noteManifoldGeometryRows(x1.rows(), x2.rows());
469 }
470 C = op->covarianceBlock(x1, x2, -1, -1);
471 return;
472 }
473 }
474 // Based on equation (2.3)
475 if (x2.size() == 0) x2 = x1;
476
477 FieldMatrixd dist_field;
478
479 // Fused path: get squared distances directly, skip sqrt + square roundtrip
480 dist_calculator_.dist_at_cached_sq(x1, x2, conf_info, lengthScale,
481 dist_field);
482
483 // dist_field contains squared distances. The padded packet exponential
484 // below is the same one as the shared kernel: an entry does not depend
485 // on where it sits or on the length modulo the packet. There is no
486 // separate Highway hn::Exp tail on this path.
487 C.resize(dist_field.rows(), dist_field.cols());
488 if (C.size() > 0) {
489 std::copy_n(dist_field.data(), static_cast<std::size_t>(C.size()),
490 C.data());
491 }
492 scaledExpOfHalfNegative(C.data(), C.size(), magnSigma2);
493}
494
496 std::shared_ptr<const geometry::InternalCoordinateChart> chart,
497 double length_scale)
498{
499 if (!chart || !chart->valid()) {
500 throw std::invalid_argument(
501 "Sexpat manifold dispatch requires a valid tangent chart");
502 }
503 if (!(length_scale > 0.0) || !std::isfinite(length_scale)) {
504 throw std::invalid_argument(
505 "Sexpat manifold length scale must be positive and finite");
506 }
507 manifold_chart_ = std::move(chart);
508 chart_length_scale_.resize(1, 1);
509 chart_length_scale_(0, 0) = length_scale;
511}
512
514{
515 manifold_chart_.reset();
517}
518
520 std::shared_ptr<const GeodesicHeatEnergyForceKernel> kernel)
521{
522 if (kernel && kernel->dimensions() != 3 * conf_info.atoms_mov.type.size())
523 throw std::invalid_argument(
524 "geodesic heat component has incompatible Cartesian dimensions");
525 if (kernel && kernel->covarianceWeight() == 0.0) kernel.reset();
526 geodesic_heat_kernel_ = std::move(kernel);
528}
529
531 double covariance_weight)
532{
533 if (covariance_weight == 0.0) {
535 return;
536 }
537 setGeodesicHeatKernel(std::make_shared<const GeodesicHeatEnergyForceKernel>(
538 reference_path, conf_info, lengthScale, covariance_weight));
539}
540
541FieldMatrixd SexpatCF::chartParameterBlock(
542 const Coord& left, const Coord& right, Eigen::Index left_channel,
543 Eigen::Index right_channel,
545{
546 auto kernel = std::make_shared<ManifoldEnergyForceKernel>(
547 manifold_chart_, magnSigma2, chart_length_scale_(0, 0));
548 kernel->setDerivative(derivative);
549 return Pullback(std::shared_ptr<const ManifoldEnergyForceKernel>(kernel))
550 .covarianceBlock(left, right, left_channel, right_channel);
551}
552
553void SexpatCF::chartDirectionalBlocks(const Coord& left, const Coord& right,
554 Eigen::Index left_channel,
555 Eigen::Index right_channel,
556 const Eigen::VectorXd& direction,
557 FieldMatrixd& first,
558 FieldMatrixd& second) const
559{
560 using Derivative = ManifoldEnergyForceKernel::Derivative;
561 const double magnitude_direction =
562 direction.size() > 0 ? direction(0) : 0.0;
563 const double length_direction = direction.size() > 1 ? direction(1) : 0.0;
564 const auto value = chartParameterBlock(left, right, left_channel,
565 right_channel, Derivative::Value);
566 const auto length = chartParameterBlock(
567 left, right, left_channel, right_channel, Derivative::LogLengthScale);
568 first = magnitude_direction * value + length_direction * length;
569 second = magnitude_direction * magnitude_direction * value +
570 2.0 * magnitude_direction * length_direction * length;
571 if (length_direction != 0.0)
572 second.noalias() +=
573 length_direction * length_direction *
574 chartParameterBlock(left, right, left_channel, right_channel,
575 Derivative::LogLengthScale2);
576}
577
578void SexpatCF::noteManifoldGeometryRows(Eigen::Index left_rows,
579 Eigen::Index right_rows) const noexcept
580{
581 manifold_geometry_rows_evaluated_for_testing_ +=
582 static_cast<std::size_t>(left_rows + right_rows);
583}
584
585std::shared_ptr<const KernelOperator> SexpatCF::assembledOperator() const
586{
587 if (!usesManifoldChart() && !usesGeodesicHeatKernel()) return nullptr;
588 std::shared_ptr<const KernelOperator> base;
589 if (usesManifoldChart()) {
590 if (chart_length_scale_.size() != 1) {
591 throw std::logic_error(
592 "chart covariance requires one intrinsic length scale");
593 }
594 base = std::make_shared<Pullback>(manifold_chart_, magnSigma2,
595 chart_length_scale_(0, 0));
596 } else {
597 auto primitive = std::make_shared<SexpatCF>(*this);
598 primitive->clearDistanceCache();
599 base = std::make_shared<Sexpat>(
600 std::shared_ptr<const SexpatCF>(std::move(primitive)));
601 }
602 if (!usesGeodesicHeatKernel()) return base;
603 return std::make_shared<Sum>(
604 std::vector<std::shared_ptr<const KernelOperator>>{
605 std::move(base),
606 std::make_shared<GeodesicHeat>(geodesic_heat_kernel_)});
607}
608
610 const Eigen::VectorXd& weights,
611 const Eigen::VectorXd& position,
612 const Eigen::VectorXd& direction,
613 Eigen::VectorXd& action) const
614{
615 if (const auto kernel = assembledOperator())
616 return kernel->meanHessianVector(training, weights, position, direction,
617 action);
618 return Sexpat(*this).meanHessianVector(training, weights, position,
619 direction, action);
620}
621
622FieldMatrixd SexpatCF::inverseDistanceCovarianceBlock(
623 const Eigen::MatrixXd& left_positions,
624 const Eigen::MatrixXd& right_positions, Eigen::Index left_channel,
625 Eigen::Index right_channel) const
626{
627 const PrimitiveKernelScope primitive(compose_operators_);
628
629 Coord x1 = left_positions;
630 Coord x2 = right_positions;
631 if (x2.size() == 0) x2 = x1;
632 SexpatCF& self = const_cast<SexpatCF&>(*this);
633 if (left_channel < 0 && right_channel < 0) {
634 FieldMatrixd block;
635 self.calculateCovarianceMatrix(x1, x2, block);
636 return block;
637 }
638 FieldMatrixIdx dims1(1, 1);
639 FieldMatrixIdx dims2(1, 1);
640 std::vector<FieldMatrixd> blocks;
641 if (left_channel >= 0 && right_channel >= 0) {
642 dims1(0, 0) = static_cast<Index_t>(left_channel + 1);
643 dims2(0, 0) = static_cast<Index_t>(right_channel + 1);
644 if (left_channel == right_channel) {
645 self.ginput2(x1, x2, dims1, blocks);
646 } else {
647 self.ginput3(x1, x2, dims1, dims2, blocks);
648 }
649 return blocks.at(0);
650 }
651 if (left_channel >= 0) {
652 dims1(0, 0) = static_cast<Index_t>(left_channel + 1);
653 self.ginput4(x1, x2, dims1, blocks);
654 return blocks.at(0);
655 }
656 dims1(0, 0) = static_cast<Index_t>(right_channel + 1);
657 self.ginput4(x2, x1, dims1, blocks);
658 return blocks.at(0).transpose();
659}
660
661Sexpat::Sexpat(const SexpatCF& primitive)
662 : Sexpat(primitive, primitive.hessianPrecision())
663{
664}
665
666Sexpat::Sexpat(const SexpatCF& primitive, HessianPrecision precision)
667 : primitive_(&primitive), hessian_precision_(precision)
668{
669}
670
671Sexpat::Sexpat(std::shared_ptr<const SexpatCF> primitive)
672 : owned_primitive_(std::move(primitive)),
673 primitive_(owned_primitive_.get()),
674 hessian_precision_(primitive_ ? primitive_->hessianPrecision()
675 : HessianPrecision::Double)
676{
677 if (primitive_ == nullptr)
678 throw std::invalid_argument("Sexpat requires a covariance primitive");
679}
680
681Sexpat::Sexpat(std::shared_ptr<const SexpatCF> primitive,
682 HessianPrecision precision)
683 : owned_primitive_(std::move(primitive)),
684 primitive_(owned_primitive_.get()),
685 hessian_precision_(precision)
686{
687 if (primitive_ == nullptr)
688 throw std::invalid_argument("Sexpat requires a covariance primitive");
689}
690
691Eigen::VectorXd Sexpat::energyDiagonal(const Eigen::MatrixXd& positions) const
692{
693 if (positions.cols() <= 0 || !positions.allFinite())
694 throw std::invalid_argument(
695 "inverse-distance covariance positions have invalid shape or "
696 "values");
697 return Eigen::VectorXd::Constant(positions.rows(),
698 primitive_->getMagnSigma2());
699}
700
701Eigen::MatrixXd Sexpat::covarianceBlock(const Eigen::MatrixXd& left_positions,
702 const Eigen::MatrixXd& right_positions,
703 Eigen::Index left_channel,
704 Eigen::Index right_channel) const
705{
706 return primitive_->inverseDistanceCovarianceBlock(
707 left_positions, right_positions, left_channel, right_channel);
708}
709
711{
712 if (!std::isfinite(factor) || !(factor > 0.0))
713 throw std::invalid_argument(
714 "geodesic covariance scale must be finite and positive");
715 if (!geodesic_heat_kernel_ || factor == 1.0) return;
716 geodesic_heat_kernel_ =
717 std::make_shared<const GeodesicHeatEnergyForceKernel>(
718 geodesic_heat_kernel_->withCovarianceWeight(
719 factor * geodesic_heat_kernel_->covarianceWeight()));
721}
722
724{
725 geodesic_heat_kernel_.reset();
727}
728
730 const Coord& positions) const
731{
732 if (!geodesic_heat_kernel_) {
733 throw std::logic_error(
734 "Sexpat geodesic heat covariance is not configured");
735 }
736 return GeodesicHeat(geodesic_heat_kernel_)
738}
739
741 const Coord& left_positions, const Coord& right_positions) const
742{
743 if (!geodesic_heat_kernel_) {
744 throw std::logic_error(
745 "Sexpat geodesic heat covariance is not configured");
746 }
747 return GeodesicHeat(geodesic_heat_kernel_)
748 .jointEnergyGradientCrossCovariance(left_positions, right_positions);
749}
750
752 const Coord& positions) const
753{
754 if (!manifold_chart_ || chart_length_scale_.size() != 1) {
755 throw std::logic_error("Sexpat manifold covariance is not configured");
756 }
757 const Eigen::Index dimensions = manifold_chart_->anchor().size();
758 if (positions.cols() != dimensions) {
759 throw std::invalid_argument(
760 "Sexpat manifold covariance geometry dimension mismatch");
761 }
762 noteManifoldGeometryRows(positions.rows(), 0);
763 return Pullback(std::make_shared<ManifoldEnergyForceKernel>(
764 manifold_chart_, magnSigma2, chart_length_scale_(0, 0)))
766}
767
769 const Coord& left_positions, const Coord& right_positions) const
770{
771 if (!manifold_chart_ || chart_length_scale_.size() != 1) {
772 throw std::logic_error("Sexpat manifold covariance is not configured");
773 }
774 const Eigen::Index dimensions = manifold_chart_->anchor().size();
775 if (left_positions.cols() != dimensions ||
776 right_positions.cols() != dimensions) {
777 throw std::invalid_argument(
778 "Sexpat manifold covariance geometry dimension mismatch");
779 }
780 noteManifoldGeometryRows(left_positions.rows(), right_positions.rows());
781 return Pullback(std::make_shared<ManifoldEnergyForceKernel>(
782 manifold_chart_, magnSigma2, chart_length_scale_(0, 0)))
783 .jointEnergyGradientCrossCovariance(left_positions, right_positions);
784}
785
787 FieldMatrixd& C)
788{
789 if (compose_operators_) {
790 if (auto op = assembledOperator()) {
791 C.resize(x.rows(), 1);
792 C.col(0) = op->covarianceBlock(x, x, -1, -1).diagonal();
793 if (usesManifoldChart()) {
794 noteManifoldGeometryRows(x.rows(), x.rows());
795 }
796 return;
797 }
798 }
799 C.resize(x.rows(), 1);
800 if (fabs(magnSigma2) <= DBL_EPSILON)
801 C.setZero();
802 else
803 C.setConstant(magnSigma2);
804}
805
807 uint8_t derivative_options,
808 const FieldMatrixIdx& dims1,
809 const FieldMatrixIdx& dims2,
811{
812 if (usesManifoldChart() || usesGeodesicHeatKernel()) return false;
814 geometry.derivative_options = derivative_options;
815
816 if (conf_info.n_pt <= 0 || x1.rows() <= 0 || x2.rows() <= 0) {
817 return false;
818 }
819 const uint8_t supported_options = OptionsForGradCalculation::D1 |
822 if ((derivative_options & ~supported_options) != 0) return false;
823 if (derivative_options != 0 &&
824 derivative_options != OptionsForGradCalculation::D1 &&
825 derivative_options != supported_options) {
826 return false;
827 }
828
829 FieldMatrixd unit_length_scale(1, conf_info.n_pt);
830 unit_length_scale.setOnes();
831
832 aux::Distance distance;
833 distance.setFarFieldRadius(far_field_radius_);
834 std::vector<FieldMatrixd> distance_pt;
835 distance.dist_at_vec(x1, x2, conf_info, unit_length_scale, distance_pt);
836 if (distance_pt.size() != static_cast<std::size_t>(conf_info.n_pt)) {
837 return false;
838 }
839
840 geometry.distance.resize(distance_pt.size());
841 for (std::size_t pt = 0; pt < distance_pt.size(); ++pt) {
842 geometry.distance[pt] = -distance_pt[pt];
843 }
844
845 auto copy_pairtype_fields = [&](const std::vector<FieldMatrixd>& source,
846 std::vector<FieldMatrixd>& target) -> bool {
847 if (source.size() != static_cast<std::size_t>(conf_info.n_pt)) {
848 return false;
849 }
850 target.resize(source.size());
851 for (std::size_t pt = 0; pt < source.size(); ++pt) {
852 target[pt] = -source[pt];
853 }
854 return true;
855 };
856
857 if (derivative_options == 0) {
858 geometry.valid = true;
859 return true;
860 }
861
862 aux::Gradient grad_calculator;
863 grad_calculator.setFarFieldRadius(far_field_radius_);
866
867 if (derivative_options == OptionsForGradCalculation::D1) {
868 const uint8_t calc_options =
870 grad_calculator.calculateDerivativesSameDim(
871 x1, x2, conf_info, unit_length_scale, dims1, calc_options,
872 derivatives, derivatives_pt);
873 if (!copy_pairtype_fields(derivatives_pt.D1, geometry.d1)) {
874 return false;
875 }
876 geometry.valid = true;
877 return true;
878 }
879
880 const uint8_t calc_options =
884
885 const bool same_dimension =
886 dims1.size() == dims2.size() && (dims1.array() == dims2.array()).all();
887 if (same_dimension) {
888 grad_calculator.calculateDerivativesSameDim(
889 x1, x2, conf_info, unit_length_scale, dims1, calc_options,
890 derivatives, derivatives_pt);
891 } else {
892 grad_calculator.calculateDerivativesDiffDim(
893 x1, x2, conf_info, unit_length_scale, dims1, dims2, calc_options,
894 Directions::y, derivatives, derivatives_pt);
895 }
896
897 if (!copy_pairtype_fields(derivatives_pt.D1, geometry.d1) ||
898 !copy_pairtype_fields(derivatives_pt.D2, geometry.d2) ||
899 !copy_pairtype_fields(derivatives_pt.D12, geometry.d12)) {
900 return false;
901 }
902
903 geometry.valid = true;
904 return true;
905}
906
908 const Coord& x_loc,
909 std::vector<FieldMatrixd>& shared_distance_neg_per_pt) const
910{
911 if (usesManifoldChart() || usesGeodesicHeatKernel()) return false;
912 shared_distance_neg_per_pt.clear();
913 if (conf_info.n_pt <= 0 || x_loc.rows() <= 0) return false;
914 FieldMatrixd unit_length_scale(1, conf_info.n_pt);
915 unit_length_scale.setOnes();
916 aux::Distance distance;
917 distance.setFarFieldRadius(far_field_radius_);
918 std::vector<FieldMatrixd> distance_pt;
919 distance.dist_at_vec(x_loc, x_loc, conf_info, unit_length_scale,
920 distance_pt);
921 if (distance_pt.size() != static_cast<std::size_t>(conf_info.n_pt)) {
922 return false;
923 }
924 shared_distance_neg_per_pt.resize(distance_pt.size());
925 for (std::size_t pt = 0; pt < distance_pt.size(); ++pt) {
926 shared_distance_neg_per_pt[pt] = -distance_pt[pt];
927 }
928 return true;
929}
930
932 const Coord& x1, const Coord& x2, uint8_t derivative_options,
933 const FieldMatrixIdx& dims1, const FieldMatrixIdx& dims2,
935{
936 if (usesManifoldChart() || usesGeodesicHeatKernel()) return false;
938 geometry.derivative_options = derivative_options;
939
940 if (conf_info.n_pt <= 0 || x1.rows() <= 0 || x2.rows() <= 0) {
941 return false;
942 }
943 const uint8_t supported_options = OptionsForGradCalculation::D1 |
946 if ((derivative_options & ~supported_options) != 0) return false;
947 if (derivative_options != 0 &&
948 derivative_options != OptionsForGradCalculation::D1 &&
949 derivative_options != supported_options) {
950 return false;
951 }
952
953 // .distance field intentionally left empty -- caller provides it via
954 // evaluateCrossBlockGeometryShared / WithSharedKernel.
955 if (derivative_options == 0) {
956 geometry.valid = true;
957 return true;
958 }
959
960 FieldMatrixd unit_length_scale(1, conf_info.n_pt);
961 unit_length_scale.setOnes();
962
963 auto copy_pairtype_fields = [&](const std::vector<FieldMatrixd>& source,
964 std::vector<FieldMatrixd>& target) -> bool {
965 if (source.size() != static_cast<std::size_t>(conf_info.n_pt)) {
966 return false;
967 }
968 target.resize(source.size());
969 for (std::size_t pt = 0; pt < source.size(); ++pt) {
970 target[pt] = -source[pt];
971 }
972 return true;
973 };
974
975 aux::Gradient grad_calculator;
976 grad_calculator.setFarFieldRadius(far_field_radius_);
979
980 if (derivative_options == OptionsForGradCalculation::D1) {
981 const uint8_t calc_options =
983 grad_calculator.calculateDerivativesSameDim(
984 x1, x2, conf_info, unit_length_scale, dims1, calc_options,
985 derivatives, derivatives_pt);
986 if (!copy_pairtype_fields(derivatives_pt.D1, geometry.d1)) {
987 return false;
988 }
989 geometry.valid = true;
990 return true;
991 }
992
993 const uint8_t calc_options =
997 const bool same_dimension =
998 dims1.size() == dims2.size() && (dims1.array() == dims2.array()).all();
999 if (same_dimension) {
1000 grad_calculator.calculateDerivativesSameDim(
1001 x1, x2, conf_info, unit_length_scale, dims1, calc_options,
1002 derivatives, derivatives_pt);
1003 } else {
1004 grad_calculator.calculateDerivativesDiffDim(
1005 x1, x2, conf_info, unit_length_scale, dims1, dims2, calc_options,
1006 Directions::y, derivatives, derivatives_pt);
1007 }
1008
1009 if (!copy_pairtype_fields(derivatives_pt.D1, geometry.d1) ||
1010 !copy_pairtype_fields(derivatives_pt.D2, geometry.d2) ||
1011 !copy_pairtype_fields(derivatives_pt.D12, geometry.d12)) {
1012 return false;
1013 }
1014 geometry.valid = true;
1015 return true;
1016}
1017
1019 const Eigen::VectorXd& theta,
1020 FieldMatrixd& out) const
1021{
1022 auto fail = [&out]() {
1023 out.resize(0, 0);
1024 return false;
1025 };
1026 if (!geometry.valid || geometry.distance.empty() || theta.size() < 2) {
1027 return fail();
1028 }
1029
1030 const auto n_pairtypes =
1031 static_cast<Eigen::Index>(geometry.distance.size());
1032 const auto n_length_scales = lengthScale.size();
1033 if (n_length_scales <= 0 || theta.size() < 1 + n_length_scales) {
1034 return fail();
1035 }
1036 const bool scalar_length = n_length_scales == 1;
1037 if (!scalar_length && n_length_scales != n_pairtypes) {
1038 return fail();
1039 }
1040
1041 const Eigen::Index rows = geometry.distance[0].rows();
1042 const Eigen::Index cols = geometry.distance[0].cols();
1043 if (scalar_length && n_pairtypes == 1) {
1044 const auto& q = geometry.distance[0];
1045 if (q.rows() != rows || q.cols() != cols) return false;
1046 const double inv_length_sq = numerics::exp(-2.0 * theta(1));
1047 out =
1048 (numerics::exp(theta(0)) * (-0.5 * inv_length_sq * q.array()).exp())
1049 .matrix();
1050 switch (geometry.derivative_options) {
1051 case 0:
1052 return true;
1054 if (geometry.d1.size() != 1 || geometry.d1[0].rows() != rows ||
1055 geometry.d1[0].cols() != cols) {
1056 return false;
1057 }
1058 out.array() *= -0.5 * inv_length_sq * geometry.d1[0].array();
1059 return true;
1062 if (geometry.d1.size() != 1 || geometry.d2.size() != 1 ||
1063 geometry.d12.size() != 1 || geometry.d1[0].rows() != rows ||
1064 geometry.d1[0].cols() != cols ||
1065 geometry.d2[0].rows() != rows ||
1066 geometry.d2[0].cols() != cols ||
1067 geometry.d12[0].rows() != rows ||
1068 geometry.d12[0].cols() != cols) {
1069 return false;
1070 }
1071 out.array() *=
1072 (-0.5 * inv_length_sq * geometry.d12[0].array() +
1073 0.25 * inv_length_sq * inv_length_sq *
1074 geometry.d1[0].array() * geometry.d2[0].array());
1075 return true;
1076 }
1077 return false;
1078 }
1079
1080 FieldMatrixd q = FieldMatrixd::Zero(rows, cols);
1081 FieldMatrixd d1;
1082 FieldMatrixd d2;
1083 FieldMatrixd d12;
1084 const bool need_d1 = geometry.derivative_options != 0;
1085 const bool need_d2d12 =
1086 geometry.derivative_options ==
1089 if (need_d1) d1 = FieldMatrixd::Zero(rows, cols);
1090 if (need_d2d12) {
1091 d2 = FieldMatrixd::Zero(rows, cols);
1092 d12 = FieldMatrixd::Zero(rows, cols);
1093 }
1094
1095 auto add_scaled_fields = [&](const std::vector<FieldMatrixd>& fields,
1096 FieldMatrixd& target, Eigen::Index pt,
1097 double scale) -> bool {
1098 if (fields.empty()) return true;
1099 if (pt >= static_cast<Eigen::Index>(fields.size())) return false;
1100 if (fields[static_cast<std::size_t>(pt)].rows() != rows ||
1101 fields[static_cast<std::size_t>(pt)].cols() != cols) {
1102 return false;
1103 }
1104 target.noalias() += scale * fields[static_cast<std::size_t>(pt)];
1105 return true;
1106 };
1107
1108 for (Eigen::Index pt = 0; pt < n_pairtypes; ++pt) {
1109 if (geometry.distance[static_cast<std::size_t>(pt)].rows() != rows ||
1110 geometry.distance[static_cast<std::size_t>(pt)].cols() != cols) {
1111 return false;
1112 }
1113 const double log_length = scalar_length ? theta(1) : theta(1 + pt);
1114 const double inv_length_sq = numerics::exp(-2.0 * log_length);
1115 q.noalias() +=
1116 inv_length_sq * geometry.distance[static_cast<std::size_t>(pt)];
1117 if (need_d1 && !add_scaled_fields(geometry.d1, d1, pt, inv_length_sq)) {
1118 return false;
1119 }
1120 if (need_d2d12 &&
1121 (!add_scaled_fields(geometry.d2, d2, pt, inv_length_sq) ||
1122 !add_scaled_fields(geometry.d12, d12, pt, inv_length_sq))) {
1123 return false;
1124 }
1125 }
1126
1127 out = (numerics::exp(theta(0)) * (-0.5 * q.array()).exp()).matrix();
1128 switch (geometry.derivative_options) {
1129 case 0:
1130 return true;
1132 if (geometry.d1.empty()) return false;
1133 out.array() *= -0.5 * d1.array();
1134 return true;
1137 if (geometry.d1.empty() || geometry.d2.empty() ||
1138 geometry.d12.empty()) {
1139 return false;
1140 }
1141 out.array() *=
1142 (-0.5 * d12.array() + 0.25 * d1.array() * d2.array());
1143 return true;
1144 }
1145 return false;
1146}
1147
1150 const std::vector<FieldMatrixd>& shared_distance_neg_per_pt,
1151 const Eigen::VectorXd& theta, FieldMatrixd& out) const
1152{
1153 auto fail = [&out]() {
1154 out.resize(0, 0);
1155 return false;
1156 };
1157 if (!geometry.valid || theta.size() < 2) return fail();
1158 const auto n_pairtypes =
1159 static_cast<Eigen::Index>(shared_distance_neg_per_pt.size());
1160 const auto n_length_scales = lengthScale.size();
1161 if (n_pairtypes <= 0 || n_length_scales <= 0 ||
1162 theta.size() < 1 + n_length_scales) {
1163 return fail();
1164 }
1165 const bool scalar_length = n_length_scales == 1;
1166 if (!scalar_length && n_length_scales != n_pairtypes) return fail();
1167
1168 const Eigen::Index rows = shared_distance_neg_per_pt[0].rows();
1169 const Eigen::Index cols = shared_distance_neg_per_pt[0].cols();
1170
1171 if (scalar_length && n_pairtypes == 1) {
1172 const auto& q = shared_distance_neg_per_pt[0];
1173 if (q.rows() != rows || q.cols() != cols) return false;
1174 const double inv_length_sq = numerics::exp(-2.0 * theta(1));
1175 out =
1176 (numerics::exp(theta(0)) * (-0.5 * inv_length_sq * q.array()).exp())
1177 .matrix();
1178 switch (geometry.derivative_options) {
1179 case 0:
1180 return true;
1182 if (geometry.d1.size() != 1 || geometry.d1[0].rows() != rows ||
1183 geometry.d1[0].cols() != cols) {
1184 return false;
1185 }
1186 out.array() *= -0.5 * inv_length_sq * geometry.d1[0].array();
1187 return true;
1190 if (geometry.d1.size() != 1 || geometry.d2.size() != 1 ||
1191 geometry.d12.size() != 1 || geometry.d1[0].rows() != rows ||
1192 geometry.d1[0].cols() != cols ||
1193 geometry.d2[0].rows() != rows ||
1194 geometry.d2[0].cols() != cols ||
1195 geometry.d12[0].rows() != rows ||
1196 geometry.d12[0].cols() != cols) {
1197 return false;
1198 }
1199 out.array() *=
1200 (-0.5 * inv_length_sq * geometry.d12[0].array() +
1201 0.25 * inv_length_sq * inv_length_sq *
1202 geometry.d1[0].array() * geometry.d2[0].array());
1203 return true;
1204 }
1205 return false;
1206 }
1207
1208 FieldMatrixd q = FieldMatrixd::Zero(rows, cols);
1209 FieldMatrixd d1;
1210 FieldMatrixd d2;
1211 FieldMatrixd d12;
1212 const bool need_d1 = geometry.derivative_options != 0;
1213 const bool need_d2d12 =
1214 geometry.derivative_options ==
1217 if (need_d1) d1 = FieldMatrixd::Zero(rows, cols);
1218 if (need_d2d12) {
1219 d2 = FieldMatrixd::Zero(rows, cols);
1220 d12 = FieldMatrixd::Zero(rows, cols);
1221 }
1222
1223 auto add_scaled_fields = [&](const std::vector<FieldMatrixd>& fields,
1224 FieldMatrixd& target, Eigen::Index pt,
1225 double scale) -> bool {
1226 if (fields.empty()) return true;
1227 if (pt >= static_cast<Eigen::Index>(fields.size())) return false;
1228 if (fields[static_cast<std::size_t>(pt)].rows() != rows ||
1229 fields[static_cast<std::size_t>(pt)].cols() != cols) {
1230 return false;
1231 }
1232 target.noalias() += scale * fields[static_cast<std::size_t>(pt)];
1233 return true;
1234 };
1235
1236 for (Eigen::Index pt = 0; pt < n_pairtypes; ++pt) {
1237 if (shared_distance_neg_per_pt[static_cast<std::size_t>(pt)].rows() !=
1238 rows ||
1239 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)].cols() !=
1240 cols) {
1241 return false;
1242 }
1243 const double log_length = scalar_length ? theta(1) : theta(1 + pt);
1244 const double inv_length_sq = numerics::exp(-2.0 * log_length);
1245 q.noalias() += inv_length_sq *
1246 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)];
1247 if (need_d1 && !add_scaled_fields(geometry.d1, d1, pt, inv_length_sq)) {
1248 return false;
1249 }
1250 if (need_d2d12 &&
1251 (!add_scaled_fields(geometry.d2, d2, pt, inv_length_sq) ||
1252 !add_scaled_fields(geometry.d12, d12, pt, inv_length_sq))) {
1253 return false;
1254 }
1255 }
1256
1257 out = (numerics::exp(theta(0)) * (-0.5 * q.array()).exp()).matrix();
1258 switch (geometry.derivative_options) {
1259 case 0:
1260 return true;
1262 if (geometry.d1.empty()) return false;
1263 out.array() *= -0.5 * d1.array();
1264 return true;
1267 if (geometry.d1.empty() || geometry.d2.empty() ||
1268 geometry.d12.empty()) {
1269 return false;
1270 }
1271 out.array() *=
1272 (-0.5 * d12.array() + 0.25 * d1.array() * d2.array());
1273 return true;
1274 }
1275 return false;
1276}
1277
1278namespace {
1279
1280// data[k] = magnitude * exp(-0.5 * data[k]) for every entry. When Eigen
1281// is vectorized (-Dscalar_eigen=false), pexp and std::exp differ by 1 ulp,
1282// and Eigen uses std::exp on the tail that is not a multiple of the packet,
1283// so an entry would otherwise depend on its index and on the length. The
1284// default build leaves Eigen unvectorized.
1285// Each chunk is copied into an aligned buffer padded out to the widest
1286// packet. Every stored entry then takes the packet exponential.
1287void scaledExpOfHalfNegative(double* data, Eigen::Index size, double magnitude)
1288{
1289 constexpr Eigen::Index kChunk = 2048; // multiple of the widest packet
1290 constexpr Eigen::Index kPacket = 8; // AVX-512 doubles
1291 if (size <= 0) return;
1292 const Eigen::Index chunks = (size + kChunk - 1) / kChunk;
1293 linalg::parallelFor(chunks, [&](long c) {
1294 const Eigen::Index begin = c * kChunk;
1295 const Eigen::Index len = std::min(kChunk, size - begin);
1296 const Eigen::Index padded = ((len + kPacket - 1) / kPacket) * kPacket;
1297 alignas(64) double buffer[2048];
1298 std::copy_n(data + begin, static_cast<std::size_t>(len), buffer);
1299 std::fill(buffer + len, buffer + padded, 0.0);
1300 Eigen::Map<Eigen::ArrayXd> block(buffer, padded);
1301 block = (-0.5 * block).exp();
1302 for (Eigen::Index k = 0; k < len; ++k)
1303 data[begin + k] = magnitude * buffer[k];
1304 });
1305}
1306
1307} // namespace
1308
1310 const std::vector<FieldMatrixd>& shared_distance_neg_per_pt,
1311 const Eigen::VectorXd& theta, FieldMatrixd& kernel_out) const
1312{
1313 auto fail = [&kernel_out]() {
1314 kernel_out.resize(0, 0);
1315 return false;
1316 };
1317 if (theta.size() < 2 || shared_distance_neg_per_pt.empty()) return fail();
1318 const auto n_pairtypes =
1319 static_cast<Eigen::Index>(shared_distance_neg_per_pt.size());
1320 const auto n_length_scales = lengthScale.size();
1321 if (n_length_scales <= 0 || theta.size() < 1 + n_length_scales)
1322 return fail();
1323 const bool scalar_length = n_length_scales == 1;
1324 if (!scalar_length && n_length_scales != n_pairtypes) return fail();
1325
1326 const Eigen::Index rows = shared_distance_neg_per_pt[0].rows();
1327 const Eigen::Index cols = shared_distance_neg_per_pt[0].cols();
1328 if (kernel_out.rows() != rows || kernel_out.cols() != cols) {
1329 kernel_out.resize(rows, cols);
1330 }
1331 kernel_out.setZero();
1332 for (Eigen::Index pt = 0; pt < n_pairtypes; ++pt) {
1333 const auto& q_pt =
1334 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)];
1335 if (q_pt.rows() != rows || q_pt.cols() != cols) return fail();
1336 const double log_length = scalar_length ? theta(1) : theta(1 + pt);
1337 const double inv_length_sq = numerics::exp(-2.0 * log_length);
1338 kernel_out.noalias() += inv_length_sq * q_pt;
1339 }
1340 scaledExpOfHalfNegative(kernel_out.data(), kernel_out.size(),
1341 numerics::exp(theta(0)));
1342 return true;
1343}
1344
1346 const CrossBlockGeometry& geometry, const FieldMatrixd& shared_kernel,
1347 const Eigen::VectorXd& theta, FieldMatrixd& out) const
1348{
1349 auto fail = [&out]() {
1350 out.resize(0, 0);
1351 return false;
1352 };
1353 if (!geometry.valid || theta.size() < 2) return fail();
1354 const auto n_length_scales = lengthScale.size();
1355 if (n_length_scales <= 0 || theta.size() < 1 + n_length_scales)
1356 return fail();
1357 const bool scalar_length = n_length_scales == 1;
1358
1359 if (geometry.derivative_options == 0) {
1360 // Kff is the shared kernel. Force blocks use the same untruncated
1361 // k so cov(E, dE) stays d/dx' k (Rasmussen-Williams 9.4).
1362 if (out.rows() != shared_kernel.rows() ||
1363 out.cols() != shared_kernel.cols()) {
1364 out.resize(shared_kernel.rows(), shared_kernel.cols());
1365 }
1366 out.noalias() = shared_kernel;
1367 return true;
1368 }
1369
1370 const Eigen::Index rows = shared_kernel.rows();
1371 const Eigen::Index cols = shared_kernel.cols();
1372
1373 // The derivative blocks need per-pairtype inv_length_sq weighting on the
1374 // d1/d2/d12 fields. Accumulate then apply against the shared kernel.
1375 FieldMatrixd d1;
1376 FieldMatrixd d2;
1377 FieldMatrixd d12;
1378 const bool need_d1 = geometry.derivative_options != 0;
1379 const bool need_d2d12 =
1380 geometry.derivative_options ==
1383 if (need_d1) d1 = FieldMatrixd::Zero(rows, cols);
1384 if (need_d2d12) {
1385 d2 = FieldMatrixd::Zero(rows, cols);
1386 d12 = FieldMatrixd::Zero(rows, cols);
1387 }
1388 const auto n_pairtypes_d1 = static_cast<Eigen::Index>(geometry.d1.size());
1389 const auto n_pairtypes_d12 = static_cast<Eigen::Index>(geometry.d12.size());
1390 const auto n_pairtypes =
1391 std::max<Eigen::Index>(n_pairtypes_d1, n_pairtypes_d12);
1392 auto add = [&](const std::vector<FieldMatrixd>& src, FieldMatrixd& dst,
1393 Eigen::Index pt, double scale) -> bool {
1394 if (src.empty()) return true;
1395 if (pt >= static_cast<Eigen::Index>(src.size())) return false;
1396 if (src[static_cast<std::size_t>(pt)].rows() != rows ||
1397 src[static_cast<std::size_t>(pt)].cols() != cols) {
1398 return false;
1399 }
1400 dst.noalias() += scale * src[static_cast<std::size_t>(pt)];
1401 return true;
1402 };
1403 for (Eigen::Index pt = 0; pt < n_pairtypes; ++pt) {
1404 const double log_length = scalar_length ? theta(1) : theta(1 + pt);
1405 const double inv_length_sq = numerics::exp(-2.0 * log_length);
1406 if (need_d1 && !add(geometry.d1, d1, pt, inv_length_sq)) {
1407 return false;
1408 }
1409 if (need_d2d12 && (!add(geometry.d2, d2, pt, inv_length_sq) ||
1410 !add(geometry.d12, d12, pt, inv_length_sq))) {
1411 return false;
1412 }
1413 }
1414
1415 switch (geometry.derivative_options) {
1417 if (geometry.d1.empty()) return false;
1418 // Kdf: -0.5 * (sum_pt inv_l^2 * d1[pt]) * kernel (the
1419 // -0.5*inv_l^2 factor is already inside d1 via the accumulate).
1420 out = shared_kernel;
1421 out.array() *= -0.5 * d1.array();
1422 return true;
1425 if (geometry.d1.empty() || geometry.d2.empty() ||
1426 geometry.d12.empty()) {
1427 return false;
1428 }
1429 out = shared_kernel;
1430 out.array() *=
1431 (-0.5 * d12.array() + 0.25 * d1.array() * d2.array());
1432 return true;
1433 }
1434 return false;
1435}
1436
1438 const FieldMatrixd& shared_kernel,
1439 const std::vector<FieldMatrixd>& shared_distance_neg_per_pt,
1440 const Eigen::VectorXd& theta, std::vector<FieldMatrixd>& DKff,
1441 const std::vector<Eigen::Index>* parameter_indices) const
1442{
1443 const auto fail = [&DKff]() {
1444 DKff.clear();
1445 return false;
1446 };
1447 if (theta.size() < 2 || shared_distance_neg_per_pt.empty()) return fail();
1448 const auto n_pt =
1449 static_cast<Eigen::Index>(shared_distance_neg_per_pt.size());
1450 const auto n_length_scales = lengthScale.size();
1451 if (n_length_scales <= 0 || theta.size() < 1 + n_length_scales)
1452 return fail();
1453 const bool scalar_length = n_length_scales == 1;
1454 if (!scalar_length && n_length_scales != n_pt) return fail();
1455
1456 const Eigen::Index rows = shared_kernel.rows();
1457 const Eigen::Index cols = shared_kernel.cols();
1458 for (const auto& distance: shared_distance_neg_per_pt) {
1459 if (distance.rows() != rows || distance.cols() != cols) return fail();
1460 }
1461
1462 const Eigen::Index parameter_count = scalar_length ? 2 : 1 + n_pt;
1463 if (!valid_gradient_parameter_selection(parameter_indices, parameter_count))
1464 return fail();
1465 const std::size_t n_blocks =
1466 parameter_indices != nullptr
1467 ? parameter_indices->size()
1468 : static_cast<std::size_t>(parameter_count);
1469 if (!resize_geometry_gradient_blocks(DKff, n_blocks, rows, cols)) {
1470 return fail();
1471 }
1472
1473 const FieldMatrixd& K = shared_kernel;
1474
1475 // dK/dlog(l) = +K * (r^2 / l^2). shared_distance_neg_per_pt stores
1476 // the NEGATION of dist_at_vec's output, and dist_at_vec itself
1477 // returns negated squared distances, so the stored field is the
1478 // POSITIVE squared distance: the scalar branch contracts it with a
1479 // positive sign (the live calculateGradOfCovMatrix isotropic branch
1480 // and the energy's Richardson finite difference pin this sign), and
1481 // the ARD branch keeps the positive product it already forms.
1482 for (std::size_t out = 0; out < n_blocks; ++out) {
1483 const Eigen::Index parameter = parameter_indices != nullptr
1484 ? (*parameter_indices)[out]
1485 : static_cast<Eigen::Index>(out);
1486 if (parameter == 0) {
1487 DKff[out] = K;
1488 } else if (scalar_length) {
1489 const double inv_length_sq = numerics::exp(-2.0 * theta(1));
1490 FieldMatrixd dist_sq = FieldMatrixd::Zero(rows, cols);
1491 for (Eigen::Index pt = 0; pt < n_pt; ++pt) {
1492 dist_sq.noalias() +=
1493 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)];
1494 }
1495 DKff[out] = (K.array() * inv_length_sq * dist_sq.array()).matrix();
1496 } else {
1497 const Eigen::Index pt = parameter - 1;
1498 const double inv_length_sq = numerics::exp(-2.0 * theta(1 + pt));
1499 DKff[out] =
1500 (K.array() * inv_length_sq *
1501 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)]
1502 .array())
1503 .matrix();
1504 }
1505 }
1506 return true;
1507}
1508
1509namespace {
1510
1511// Accumulate per-pairtype geometry fields scaled by inv_l_pt^2.
1512template <typename Field>
1513bool accumulate_per_pt(const std::vector<Field>& src, Field& dst,
1514 const Eigen::VectorXd& theta, bool scalar_length,
1515 Eigen::Index n_pt)
1516{
1517 if (src.empty()) return true;
1518 if (static_cast<Eigen::Index>(src.size()) < n_pt) return false;
1519 for (Eigen::Index pt = 0; pt < n_pt; ++pt) {
1520 const double log_length = scalar_length ? theta(1) : theta(1 + pt);
1521 const double inv_length_sq = numerics::exp(-2.0 * log_length);
1522 dst.noalias() += inv_length_sq * src[static_cast<std::size_t>(pt)];
1523 }
1524 return true;
1525}
1526
1527bool validate_shared_directional_geometry(
1528 const SexpatCF& cov_func, const FieldMatrixd& shared_kernel,
1529 const std::vector<FieldMatrixd>& shared_distance_neg_per_pt,
1530 const Eigen::VectorXd& theta, bool& scalar_length, Eigen::Index& n_pt)
1531{
1532 n_pt = static_cast<Eigen::Index>(shared_distance_neg_per_pt.size());
1533 if (theta.size() < 2 || n_pt <= 0 || shared_kernel.size() == 0)
1534 return false;
1535 const auto n_length_scales = cov_func.getLengthScaleRef().size();
1536 if (n_length_scales <= 0 || theta.size() < 1 + n_length_scales)
1537 return false;
1538 scalar_length = n_length_scales == 1;
1539 if (!scalar_length && n_length_scales != n_pt) return false;
1540
1541 const Eigen::Index rows = shared_kernel.rows();
1542 const Eigen::Index cols = shared_kernel.cols();
1543 for (Eigen::Index pt = 0; pt < n_pt; ++pt) {
1544 const auto& q =
1545 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)];
1546 if (q.rows() != rows || q.cols() != cols) return false;
1547 }
1548 return true;
1549}
1550
1551bool directional_kernel_prefactors(
1552 const SexpatCF& cov_func, const FieldMatrixd& shared_kernel,
1553 const std::vector<FieldMatrixd>& shared_distance_neg_per_pt,
1554 const Eigen::VectorXd& theta, const Eigen::VectorXd& direction,
1555 bool& scalar_length, Eigen::Index& n_pt, FieldMatrixd& k1, FieldMatrixd& k2)
1556{
1557 if (!validate_shared_directional_geometry(cov_func, shared_kernel,
1558 shared_distance_neg_per_pt, theta,
1559 scalar_length, n_pt)) {
1560 return false;
1561 }
1562
1563 const auto dirs = unpack_direction(cov_func, direction);
1564 k1.resize(shared_kernel.rows(), shared_kernel.cols());
1565 k1.setConstant(dirs.sigma_dir);
1566 FieldMatrixd hessian_log_kernel =
1567 FieldMatrixd::Zero(shared_kernel.rows(), shared_kernel.cols());
1568
1569 for (Eigen::Index pt = 0; pt < n_pt; ++pt) {
1570 const double log_length = scalar_length ? theta(1) : theta(1 + pt);
1571 const double inv_length_sq = numerics::exp(-2.0 * log_length);
1572 const double dir = expanded_length_direction(dirs.length_dir, pt);
1573 const auto& q =
1574 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)];
1575 k1.array() += dir * inv_length_sq * q.array();
1576 hessian_log_kernel.array() -=
1577 2.0 * dir * dir * inv_length_sq * q.array();
1578 }
1579
1580 k2 = (k1.array().square() + hessian_log_kernel.array()).matrix();
1581 return true;
1582}
1583
1584bool accumulate_directional_geometry_field(
1585 const std::vector<FieldMatrixd>& src, const Eigen::VectorXd& theta,
1586 const Eigen::VectorXd& length_direction, bool scalar_length,
1587 Eigen::Index n_pt, Eigen::Index rows, Eigen::Index cols,
1588 FieldMatrixd& value, FieldMatrixd& first, FieldMatrixd& second)
1589{
1590 if (src.size() != static_cast<std::size_t>(n_pt)) return false;
1591
1592 value = FieldMatrixd::Zero(rows, cols);
1593 first = FieldMatrixd::Zero(rows, cols);
1594 second = FieldMatrixd::Zero(rows, cols);
1595
1596 for (Eigen::Index pt = 0; pt < n_pt; ++pt) {
1597 const auto& field = src[static_cast<std::size_t>(pt)];
1598 if (field.rows() != rows || field.cols() != cols) return false;
1599 const double log_length = scalar_length ? theta(1) : theta(1 + pt);
1600 const double inv_length_sq = numerics::exp(-2.0 * log_length);
1601 const double dir = expanded_length_direction(length_direction, pt);
1602 value.noalias() += inv_length_sq * field;
1603 first.noalias() += (-2.0 * dir * inv_length_sq) * field;
1604 second.noalias() += (4.0 * dir * dir * inv_length_sq) * field;
1605 }
1606 return true;
1607}
1608
1609} // namespace
1610
1612 const FieldMatrixd& shared_kernel,
1613 const std::vector<FieldMatrixd>& shared_distance_neg_per_pt,
1614 const Eigen::VectorXd& theta, const Eigen::VectorXd& direction,
1615 FieldMatrixd& first, FieldMatrixd& second) const
1616{
1617 first.resize(0, 0);
1618 second.resize(0, 0);
1619
1620 bool scalar_length = false;
1621 Eigen::Index n_pt = 0;
1622 FieldMatrixd k1, k2;
1623 if (!directional_kernel_prefactors(
1624 *this, shared_kernel, shared_distance_neg_per_pt, theta, direction,
1625 scalar_length, n_pt, k1, k2)) {
1626 return false;
1627 }
1628 (void)scalar_length;
1629 (void)n_pt;
1630
1631 first = (shared_kernel.array() * k1.array()).matrix();
1632 second = (shared_kernel.array() * k2.array()).matrix();
1633 return true;
1634}
1635
1637 const CrossBlockGeometry& geometry, const FieldMatrixd& shared_kernel,
1638 const std::vector<FieldMatrixd>& shared_distance_neg_per_pt,
1639 const Eigen::VectorXd& theta, const Eigen::VectorXd& direction,
1640 FieldMatrixd& first, FieldMatrixd& second) const
1641{
1642 first.resize(0, 0);
1643 second.resize(0, 0);
1644 if (!geometry.valid ||
1645 geometry.derivative_options != OptionsForGradCalculation::D1) {
1646 return false;
1647 }
1648
1649 bool scalar_length = false;
1650 Eigen::Index n_pt = 0;
1651 FieldMatrixd k1, k2;
1652 if (!directional_kernel_prefactors(
1653 *this, shared_kernel, shared_distance_neg_per_pt, theta, direction,
1654 scalar_length, n_pt, k1, k2)) {
1655 return false;
1656 }
1657
1658 const auto dirs = unpack_direction(*this, direction);
1659 FieldMatrixd d1, d1_first, d1_second;
1660 if (!accumulate_directional_geometry_field(
1661 geometry.d1, theta, dirs.length_dir, scalar_length, n_pt,
1662 shared_kernel.rows(), shared_kernel.cols(), d1, d1_first,
1663 d1_second)) {
1664 return false;
1665 }
1666
1667 const FieldMatrixd& active_kernel = shared_kernel;
1668 first = (-0.5 * active_kernel.array() *
1669 (k1.array() * d1.array() + d1_first.array()))
1670 .matrix();
1671 second = (-0.5 * active_kernel.array() *
1672 (k2.array() * d1.array() + 2.0 * k1.array() * d1_first.array() +
1673 d1_second.array()))
1674 .matrix();
1675 return true;
1676}
1677
1679 const CrossBlockGeometry& geometry, const FieldMatrixd& shared_kernel,
1680 const std::vector<FieldMatrixd>& shared_distance_neg_per_pt,
1681 const Eigen::VectorXd& theta, const Eigen::VectorXd& direction,
1682 FieldMatrixd& first, FieldMatrixd& second) const
1683{
1684 first.resize(0, 0);
1685 second.resize(0, 0);
1686 if (!geometry.valid ||
1687 geometry.derivative_options !=
1690 return false;
1691 }
1692
1693 bool scalar_length = false;
1694 Eigen::Index n_pt = 0;
1695 FieldMatrixd k1, k2;
1696 if (!directional_kernel_prefactors(
1697 *this, shared_kernel, shared_distance_neg_per_pt, theta, direction,
1698 scalar_length, n_pt, k1, k2)) {
1699 return false;
1700 }
1701
1702 const auto dirs = unpack_direction(*this, direction);
1703 FieldMatrixd d1, d1_first, d1_second;
1704 FieldMatrixd d2, d2_first, d2_second;
1705 FieldMatrixd d12, d12_first, d12_second;
1706 const Eigen::Index rows = shared_kernel.rows();
1707 const Eigen::Index cols = shared_kernel.cols();
1708 if (!accumulate_directional_geometry_field(
1709 geometry.d1, theta, dirs.length_dir, scalar_length, n_pt, rows,
1710 cols, d1, d1_first, d1_second) ||
1711 !accumulate_directional_geometry_field(
1712 geometry.d2, theta, dirs.length_dir, scalar_length, n_pt, rows,
1713 cols, d2, d2_first, d2_second) ||
1714 !accumulate_directional_geometry_field(
1715 geometry.d12, theta, dirs.length_dir, scalar_length, n_pt, rows,
1716 cols, d12, d12_first, d12_second)) {
1717 return false;
1718 }
1719
1720 const FieldMatrixd base =
1721 (-0.5 * d12.array() + 0.25 * d1.array() * d2.array()).matrix();
1722 const FieldMatrixd base_first =
1723 (-0.5 * d12_first.array() +
1724 0.25 * (d1_first.array() * d2.array() + d1.array() * d2_first.array()))
1725 .matrix();
1726 const FieldMatrixd base_second =
1727 (-0.5 * d12_second.array() +
1728 0.25 * (d1_second.array() * d2.array() +
1729 2.0 * d1_first.array() * d2_first.array() +
1730 d1.array() * d2_second.array()))
1731 .matrix();
1732
1733 const FieldMatrixd& active_kernel = shared_kernel;
1734 first = (active_kernel.array() *
1735 (k1.array() * base.array() + base_first.array()))
1736 .matrix();
1737 second = (active_kernel.array() *
1738 (k2.array() * base.array() +
1739 2.0 * k1.array() * base_first.array() + base_second.array()))
1740 .matrix();
1741 return true;
1742}
1743
1745 const CrossBlockGeometry& geometry, const FieldMatrixd& shared_kernel,
1746 const std::vector<FieldMatrixd>& shared_distance_neg_per_pt,
1747 const Eigen::VectorXd& theta, std::vector<FieldMatrixd>& DKff,
1748 const std::vector<Eigen::Index>* parameter_indices) const
1749{
1750 const auto fail = [&DKff]() {
1751 DKff.clear();
1752 return false;
1753 };
1754 if (!geometry.valid || theta.size() < 2) return fail();
1755 const auto n_pt =
1756 static_cast<Eigen::Index>(shared_distance_neg_per_pt.size());
1757 const auto n_length_scales = lengthScale.size();
1758 if (n_length_scales <= 0 || theta.size() < 1 + n_length_scales)
1759 return fail();
1760 const bool scalar_length = n_length_scales == 1;
1761 if (!scalar_length && n_length_scales != n_pt) return fail();
1762 if (geometry.d1.size() != static_cast<std::size_t>(n_pt)) return fail();
1763
1764 const Eigen::Index rows = shared_kernel.rows();
1765 const Eigen::Index cols = shared_kernel.cols();
1766 for (Eigen::Index pt = 0; pt < n_pt; ++pt) {
1767 const auto idx = static_cast<std::size_t>(pt);
1768 if (shared_distance_neg_per_pt[idx].rows() != rows ||
1769 shared_distance_neg_per_pt[idx].cols() != cols ||
1770 geometry.d1[idx].rows() != rows ||
1771 geometry.d1[idx].cols() != cols) {
1772 return fail();
1773 }
1774 }
1775 const Eigen::Index parameter_count = scalar_length ? 2 : 1 + n_pt;
1776 if (!valid_gradient_parameter_selection(parameter_indices, parameter_count))
1777 return fail();
1778 const std::size_t n_blocks =
1779 parameter_indices != nullptr
1780 ? parameter_indices->size()
1781 : static_cast<std::size_t>(parameter_count);
1782 if (!resize_geometry_gradient_blocks(DKff, n_blocks, rows, cols)) {
1783 return fail();
1784 }
1785
1786 // Accumulate the per-pairtype per-dim gradient with inv_l_pt^2 weighting,
1787 // matching derivatives.D1[n=0]_actual from calculateDerivativesSameDim
1788 // at the live lengthscale. Note: geometry.d1[pt] = -derivatives_pt.D1[pt]
1789 // at unit lengthscale (negated by buildCrossBlockGeometry /
1790 // DerivativesOnly). So accumulating inv_l_pt^2 * geometry.d1[pt] gives
1791 // -derivatives.D1[0]_actual.
1792 static thread_local FieldMatrixd d1_accum_neg;
1793 if (d1_accum_neg.rows() != rows || d1_accum_neg.cols() != cols)
1794 d1_accum_neg.resize(rows, cols);
1795 d1_accum_neg.setZero();
1796 if (!accumulate_per_pt(geometry.d1, d1_accum_neg, theta, scalar_length,
1797 n_pt)) {
1798 return fail();
1799 }
1800
1801 // DKff[0] = Kdf at theta = ginput4 output
1802 // = -0.5 * K * derivatives.D1[0]_actual
1803 // With evaluateValueInDerivativeField's -= sign convention:
1804 // derivatives_pt.D1[pt]_unit = -sum_{p of pt} deriv_ij_p_unit
1805 // geometry.d1[pt] = -derivatives_pt.D1[pt]_unit = +sum_{p of pt}
1806 // deriv_ij_p_unit derivatives.D1[0]_actual = sum_pt inv_l_pt^2 *
1807 // geometry.d1[pt]
1808 // = d1_accum_neg (positive sum despite name).
1809
1810 // For each pairtype, dKdf/dlog(length_pt) follows the direct formula
1811 // DK_pt = K * (-D1_pt_actual + 0.5 * D1[0]_actual * dist_pt_actual)
1812 // with:
1813 // D1_pt_actual = -inv_l_pt^2 * geometry.d1[pt]
1814 // D1[0]_actual = +d1_accum_neg
1815 // dist_pt_actual = -inv_l_pt^2 * shared_distance_neg_per_pt[pt]
1816 // => DK_pt = K * inv_l_pt^2 * (geometry.d1[pt]
1817 // - 0.5 * d1_accum_neg *
1818 // shared_distance_neg[pt])
1819 for (std::size_t out = 0; out < n_blocks; ++out) {
1820 const Eigen::Index parameter = parameter_indices != nullptr
1821 ? (*parameter_indices)[out]
1822 : static_cast<Eigen::Index>(out);
1823 if (parameter == 0) {
1824 DKff[out] =
1825 (-0.5 * shared_kernel.array() * d1_accum_neg.array()).matrix();
1826 continue;
1827 }
1828 if (scalar_length && n_pt > 1) {
1829 // One shared length varies every pairtype at once.
1830 FieldMatrixd distance = FieldMatrixd::Zero(rows, cols);
1831 for (const auto& part: shared_distance_neg_per_pt)
1832 distance += part;
1833 DKff[out] = (shared_kernel.array() * d1_accum_neg.array() *
1834 (1.0 - 0.5 * numerics::exp(-2.0 * theta(1)) *
1835 distance.array()))
1836 .matrix();
1837 continue;
1838 }
1839 const Eigen::Index pt = parameter - 1;
1840 const double inv_length_sq =
1841 numerics::exp(-2.0 * (scalar_length ? theta(1) : theta(1 + pt)));
1842 const auto& d1_pt = geometry.d1[static_cast<std::size_t>(pt)];
1843 const auto& dn_pt =
1844 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)];
1845 DKff[out] =
1846 (shared_kernel.array() * inv_length_sq *
1847 (d1_pt.array() - 0.5 * d1_accum_neg.array() * dn_pt.array()))
1848 .matrix();
1849 }
1850 return true;
1851}
1852
1854 const CrossBlockGeometry& geometry, const FieldMatrixd& shared_kernel,
1855 const std::vector<FieldMatrixd>& shared_distance_neg_per_pt,
1856 const Eigen::VectorXd& theta, std::vector<FieldMatrixd>& DKff,
1857 const std::vector<Eigen::Index>* parameter_indices) const
1858{
1859 const auto fail = [&DKff]() {
1860 DKff.clear();
1861 return false;
1862 };
1863 if (!geometry.valid || theta.size() < 2) return fail();
1864 const auto n_pt =
1865 static_cast<Eigen::Index>(shared_distance_neg_per_pt.size());
1866 const auto n_length_scales = lengthScale.size();
1867 if (n_length_scales <= 0 || theta.size() < 1 + n_length_scales)
1868 return fail();
1869 const bool scalar_length = n_length_scales == 1;
1870 if (!scalar_length && n_length_scales != n_pt) return fail();
1871 if (geometry.d1.size() != static_cast<std::size_t>(n_pt) ||
1872 geometry.d2.size() != static_cast<std::size_t>(n_pt) ||
1873 geometry.d12.size() != static_cast<std::size_t>(n_pt)) {
1874 return fail();
1875 }
1876
1877 const Eigen::Index rows = shared_kernel.rows();
1878 const Eigen::Index cols = shared_kernel.cols();
1879 for (Eigen::Index pt = 0; pt < n_pt; ++pt) {
1880 const auto idx = static_cast<std::size_t>(pt);
1881 if (shared_distance_neg_per_pt[idx].rows() != rows ||
1882 shared_distance_neg_per_pt[idx].cols() != cols ||
1883 geometry.d1[idx].rows() != rows ||
1884 geometry.d1[idx].cols() != cols ||
1885 geometry.d2[idx].rows() != rows ||
1886 geometry.d2[idx].cols() != cols ||
1887 geometry.d12[idx].rows() != rows ||
1888 geometry.d12[idx].cols() != cols) {
1889 return fail();
1890 }
1891 }
1892 const Eigen::Index parameter_count = scalar_length ? 2 : 1 + n_pt;
1893 if (!valid_gradient_parameter_selection(parameter_indices, parameter_count))
1894 return fail();
1895 const std::size_t n_blocks =
1896 parameter_indices != nullptr
1897 ? parameter_indices->size()
1898 : static_cast<std::size_t>(parameter_count);
1899 if (!resize_geometry_gradient_blocks(DKff, n_blocks, rows, cols)) {
1900 return fail();
1901 }
1902
1903 // Per-dim accumulates at actual lengthscale (negated, matching the
1904 // d1_accum_neg / d2_accum_neg / d12_accum_neg pattern).
1905 // Scratch reused across the channel-block pairs of a gradient: the
1906 // routine runs once per pair, tens of thousands of times per gradient.
1907 static thread_local FieldMatrixd d1_neg, d2_neg, d12_neg;
1908 for (FieldMatrixd* scratch: {&d1_neg, &d2_neg, &d12_neg}) {
1909 if (scratch->rows() != rows || scratch->cols() != cols)
1910 scratch->resize(rows, cols);
1911 scratch->setZero();
1912 }
1913 if (!accumulate_per_pt(geometry.d1, d1_neg, theta, scalar_length, n_pt) ||
1914 !accumulate_per_pt(geometry.d2, d2_neg, theta, scalar_length, n_pt) ||
1915 !accumulate_per_pt(geometry.d12, d12_neg, theta, scalar_length, n_pt)) {
1916 return fail();
1917 }
1918
1919 // DKff[0] = block value at theta (matches ginput2 / ginput3 output).
1920 // ginput2/3: DK = magn * exp * (-0.5 * D12[n]_actual
1921 // + 0.25 * D1[n]_actual * D2[n]_actual)
1922 // With evaluateValueInDerivativeField's += convention, per-dim
1923 // accumulators are POSITIVE: D[n]_actual = +d{1,2,12}_neg (the names
1924 // are historical, the values are positive sums).
1925 // => DK[0] = K * (-0.5 * d12_neg + 0.25 * d1_neg * d2_neg)
1926
1927 // For each pairtype, dK/dlog(length_pt). Following calculateGradOfCov-
1928 // MatrixWithDerivatives2: DK_pt = magn * exp * (-D12_pt_actual
1929 // - 0.25 * D1[n]_actual *
1930 // D2[n]_actual *
1931 // dist_pt_actual
1932 // + 0.5 * (D1[n]_actual *
1933 // D2_pt_actual
1934 // + D2[n]_actual *
1935 // D1_pt_actual
1936 // + dist_pt_actual *
1937 // D12[n]_actual))
1938 for (std::size_t out = 0; out < n_blocks; ++out) {
1939 const Eigen::Index parameter = parameter_indices != nullptr
1940 ? (*parameter_indices)[out]
1941 : static_cast<Eigen::Index>(out);
1942 if (parameter == 0) {
1943 DKff[out] = (shared_kernel.array() *
1944 (-0.5 * d12_neg.array() +
1945 0.25 * d1_neg.array() * d2_neg.array()))
1946 .matrix();
1947 continue;
1948 }
1949 if (scalar_length && n_pt > 1) {
1950 // One shared length varies every pairtype at once.
1951 FieldMatrixd distance = FieldMatrixd::Zero(rows, cols);
1952 for (const auto& part: shared_distance_neg_per_pt)
1953 distance += part;
1954 const FieldMatrixd q = numerics::exp(-2.0 * theta(1)) * distance;
1955 DKff[out] = (shared_kernel.array() *
1956 (d12_neg.array() - d1_neg.array() * d2_neg.array() +
1957 q.array() * (-0.5 * d12_neg.array() +
1958 0.25 * d1_neg.array() * d2_neg.array())))
1959 .matrix();
1960 continue;
1961 }
1962 const Eigen::Index pt = parameter - 1;
1963 const double inv_length_sq =
1964 numerics::exp(-2.0 * (scalar_length ? theta(1) : theta(1 + pt)));
1965 const auto& d1_pt = geometry.d1[static_cast<std::size_t>(pt)];
1966 const auto& d2_pt = geometry.d2[static_cast<std::size_t>(pt)];
1967 const auto& d12_pt = geometry.d12[static_cast<std::size_t>(pt)];
1968 const auto& dn_pt =
1969 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)];
1970 // Substituting:
1971 // D12_pt_actual = -inv_l_pt^2 * geometry.d12[pt]
1972 // D1[n]_actual = +d1_neg
1973 // D2[n]_actual = +d2_neg
1974 // D12[n]_actual = +d12_neg
1975 // D1_pt_actual = -inv_l_pt^2 * geometry.d1[pt]
1976 // D2_pt_actual = -inv_l_pt^2 * geometry.d2[pt]
1977 // dist_pt_actual = -inv_l_pt^2 * dn_pt
1978 //
1979 // DK_pt = K * (inv_l_pt^2 * d12_pt
1980 // - 0.25 * d1_neg * d2_neg * (-inv_l_pt^2 * dn_pt)
1981 // + 0.5 * (d1_neg * (-inv_l_pt^2 * d2_pt)
1982 // + d2_neg * (-inv_l_pt^2 * d1_pt)
1983 // + (-inv_l_pt^2 * dn_pt) * d12_neg))
1984 // = K * (inv_l_pt^2 * d12_pt
1985 // + 0.25 * inv_l_pt^2 * d1_neg * d2_neg * dn_pt
1986 // - 0.5 * inv_l_pt^2 * (d1_neg * d2_pt + d2_neg * d1_pt
1987 // + dn_pt * d12_neg))
1988 // = K * inv_l_pt^2 * (d12_pt
1989 // + 0.25 * d1_neg * d2_neg * dn_pt
1990 // - 0.5 * (d1_neg * d2_pt + d2_neg * d1_pt
1991 // + dn_pt * d12_neg))
1992 DKff[out] = (shared_kernel.array() * inv_length_sq *
1993 (d12_pt.array() +
1994 0.25 * d1_neg.array() * d2_neg.array() * dn_pt.array() -
1995 0.5 * (d1_neg.array() * d2_pt.array() +
1996 d2_neg.array() * d1_pt.array() +
1997 dn_pt.array() * d12_neg.array())))
1998 .matrix();
1999 }
2000 return true;
2001}
2002
2004 const CrossBlockGeometry& geometry, const Eigen::VectorXd& theta,
2005 const Eigen::VectorXd& weights, bool transpose_field,
2006 Eigen::VectorXd& out) const
2007{
2008 out.resize(0);
2009 if (!geometry.valid || geometry.distance.empty() || theta.size() < 2) {
2010 return false;
2011 }
2012
2013 const auto n_pairtypes =
2014 static_cast<Eigen::Index>(geometry.distance.size());
2015 const auto n_length_scales = lengthScale.size();
2016 if (n_length_scales <= 0 || theta.size() < 1 + n_length_scales) {
2017 return false;
2018 }
2019 const bool scalar_length = n_length_scales == 1;
2020 if (!scalar_length && n_length_scales != n_pairtypes) {
2021 return false;
2022 }
2023
2024 const Eigen::Index rows = geometry.distance[0].rows();
2025 const Eigen::Index cols = geometry.distance[0].cols();
2026 if (rows <= 0 || cols <= 0) return false;
2027
2028 const Eigen::Index expected_weights = transpose_field ? cols : rows;
2029 const Eigen::Index expected_out = transpose_field ? rows : cols;
2030 if (weights.size() != expected_weights) return false;
2031
2032 const bool need_d1 =
2033 geometry.derivative_options == OptionsForGradCalculation::D1 ||
2034 geometry.derivative_options ==
2037 const bool need_d2 =
2038 geometry.derivative_options ==
2041 if (!need_d1 && geometry.derivative_options != 0) return false;
2042 if (need_d1 && geometry.d1.empty()) return false;
2043 if (need_d2 && (geometry.d2.empty() || geometry.d12.empty())) return false;
2044
2045 std::vector<double> inv_length_sq(static_cast<std::size_t>(n_pairtypes),
2046 0.0);
2047 for (Eigen::Index pt = 0; pt < n_pairtypes; ++pt) {
2048 const double log_length = scalar_length ? theta(1) : theta(1 + pt);
2049 inv_length_sq[static_cast<std::size_t>(pt)] =
2050 numerics::exp(-2.0 * log_length);
2051 }
2052
2053 out.resize(expected_out);
2054 out.setZero();
2055 const double magn_sigma = numerics::exp(theta(0));
2056
2057 auto add_entry = [&](Eigen::Index row, Eigen::Index col, double value) {
2058 if (transpose_field) {
2059 out(row) += value * weights(col);
2060 } else {
2061 out(col) += value * weights(row);
2062 }
2063 };
2064
2065 for (Eigen::Index row = 0; row < rows; ++row) {
2066 for (Eigen::Index col = 0; col < cols; ++col) {
2067 double q = 0.0;
2068 double d1 = 0.0;
2069 double d2 = 0.0;
2070 double d12 = 0.0;
2071 for (Eigen::Index pt = 0; pt < n_pairtypes; ++pt) {
2072 const double coeff =
2073 inv_length_sq[static_cast<std::size_t>(pt)];
2074 const auto& dist =
2075 geometry.distance[static_cast<std::size_t>(pt)];
2076 q += coeff * dist(row, col);
2077 if (need_d1) {
2078 d1 += coeff *
2079 geometry.d1[static_cast<std::size_t>(pt)](row, col);
2080 }
2081 if (need_d2) {
2082 d2 += coeff *
2083 geometry.d2[static_cast<std::size_t>(pt)](row, col);
2084 d12 += coeff *
2085 geometry.d12[static_cast<std::size_t>(pt)](row, col);
2086 }
2087 }
2088
2089 double value = magn_sigma * numerics::exp(-0.5 * q);
2090 switch (geometry.derivative_options) {
2091 case 0:
2092 break;
2094 value *= -0.5 * d1;
2095 break;
2099 value *= (-0.5 * d12 + 0.25 * d1 * d2);
2100 break;
2101 default:
2102 return false;
2103 }
2104 add_entry(row, col, value);
2105 }
2106 }
2107 return true;
2108}
2109
2111 std::vector<FieldMatrixd>& DKff)
2112{
2113 if (usesManifoldChart()) {
2114 if (x2.size() == 0) x2 = x1;
2115 DKff = {
2116 chartParameterBlock(
2117 x1, x2, -1, -1,
2119 chartParameterBlock(
2120 x1, x2, -1, -1,
2122 return;
2123 }
2124
2125 io::ErrorManager err;
2126 FieldMatrixd dist;
2127 std::vector<FieldMatrixd> dist_pt;
2128 FieldMatrixd K, DK_l;
2129 std::vector<Index_t> i1;
2130
2131 DKff.clear();
2132
2133 if (x2.size() == 0) x2 = x1;
2134
2135 // Evaluate: DKff{1} = d Kff / d magnSigma2
2136 // DKff{2} = d Kff / d lengthScale
2137 // NOTE! Here we have already taken into account that the parameters
2138 // are transformed through log() and thus dK/dlog(p) = p * dK/dp
2139 // evaluate the gradient for training covariance
2140 if (x1.cols() != x2.cols()) {
2141 err << "gpcf_sexp -> _ghyper: The number of columns in x and x2 has to "
2142 "be the same.\n";
2143 }
2144
2145 dist_calculator_.dist_at_cached_sq(x1, x2, conf_info, lengthScale, dist);
2146
2147 // K = magnSigma2 * exp(-0.5 * dist²). Same untruncated k as ginput.
2148 K = (magnSigma2 * (-0.5 * dist.array()).exp()).matrix();
2149 DKff.push_back(K);
2150
2151 if (lengthScale.size() == 1) {
2152 // Isotropic case. K = magnSigma2 * exp(-0.5 * r^2 / l^2) and the
2153 // packed parameter is log(l), so
2154 // dK/dlog(l) = K * (r^2 / l^2) = +K .* dist2
2155 // (dist already stores the lengthscale-scaled squared distance).
2156 // A 60-digit evaluation of the marginal-likelihood gradient on
2157 // the petmad tile fixture pins the positive sign: the negated
2158 // block makes the reported gradient the exact negative of the
2159 // finite difference of the energy this class itself computes.
2160 DK_l = (K.array() * dist.array()).matrix();
2161 DKff.push_back(std::move(DK_l));
2162 } else {
2163 dist_calculator_.dist_at_vec(x1, x2, conf_info, lengthScale, dist_pt);
2164
2165 // Per-pairtype: dK/dlog(l_pt) = +K .* (r_pt^2 / l_pt^2). Unlike
2166 // dist_at_cached_sq above (positive squared distances),
2167 // dist_at_vec returns the NEGATED per-pairtype squared
2168 // distances, so the leading minus restores the positive
2169 // derivative (untruncated K, exp form); the MATLAB reference
2170 // values pin the positive sign.
2171 //
2172 // K already holds magnSigma2 * exp(-0.5 * dist^2). Reuse it rather
2173 // than writing the exp again: (-magnSigma2 * e) * d and (-(magnSigma2
2174 // * e)) * d are the same value under IEEE-754, since negation is
2175 // exact. The previous form bound the exp to `auto`, which keeps it an
2176 // unevaluated Eigen expression, so the transcendental was recomputed
2177 // over the whole matrix once per pairtype.
2178 for (Index_t m = 0; m < conf_info.n_pt; ++m) {
2179 DK_l = (-K.array() * dist_pt[m].array()).matrix();
2180 DKff.push_back(std::move(DK_l));
2181 }
2182 }
2183}
2184
2186 const Coord& x1, Coord& x2, FieldMatrixIdx& dims,
2187 std::vector<FieldMatrixd>& DKff)
2188{
2189 if (usesManifoldChart()) {
2190 if (x2.size() == 0) x2 = x1;
2191 DKff.clear();
2192 for (const auto derivative:
2195 for (Eigen::Index i = 0; i < dims.size(); ++i)
2196 DKff.push_back(
2197 chartParameterBlock(x1, x2, dims(i) - 1, -1, derivative));
2198 return;
2199 }
2200
2201 const PrimitiveKernelScope primitive(compose_operators_);
2202
2203 // Scratch that the parallel loop only reads or writes must be shared.
2204 // thread_local would give each worker an empty copy of the master's
2205 // distances and derivatives. Cdm and the gradient calculator stay
2206 // thread_local: they are filled before the team starts.
2207 thread_local std::vector<FieldMatrixd> Cdm;
2208 thread_local aux::Gradient grad_calculator;
2209 grad_calculator.setFarFieldRadius(far_field_radius_);
2210 std::vector<FieldMatrixd> dist_pt;
2211 std::vector<FieldMatrixd> DK_pt;
2214 thread_local FieldMatrixd DK;
2215 // derivatives.* are reserve+push_back'd per dimension, so they must start
2216 // empty. derivatives_pt.* are sized and zeroed in full by
2217 // resizeDerivativeFields, so clearing them here only throws away storage
2218 // that the next call reallocates.
2219 derivatives.D1.clear();
2220 derivatives.D2.clear();
2221 derivatives.D12.clear();
2222 uint8_t calc_options =
2224
2225 DKff.clear();
2226
2227 if (x2.size() == 0) x2 = x1;
2228
2229 // ginput4 evaluates exp(-0.5 * d^2) over exactly these distances; take
2230 // its factor rather than repeating the transcendental, which also makes
2231 // the dist_at_cached_sq that only fed it unnecessary here.
2232 ExpDistArray expdist;
2233 ginput4(x1, x2, dims, Cdm, &expdist);
2234
2235 for (Index_t n = 0; n < Cdm.size(); ++n) {
2236 DKff.push_back(std::move(Cdm[n]));
2237 }
2238
2239 dist_calculator_.dist_at_vec(x1, x2, conf_info, lengthScale, dist_pt);
2240
2241 // Pair-type derivative fields sum every coordinate of one
2242 // calculateDerivativesSameDim call. Ask for one coordinate at a time
2243 // so each length-scale block is that coordinate alone. One coordinate
2244 // is the call the training gradient makes, and it runs the same
2245 // product as before.
2246 const auto n_dims = static_cast<Index_t>(dims.size());
2247 const auto n_pt = conf_info.n_pt;
2248 DK_pt.resize(n_dims * n_pt);
2249 FieldMatrixIdx one_dim(1, 1);
2250 for (Index_t n = 0; n < n_dims; ++n) {
2251 one_dim(0, 0) = dims(n);
2252 derivatives.D1.clear();
2253 grad_calculator.calculateDerivativesSameDim(
2254 x1, x2, conf_info, lengthScale, one_dim, calc_options, derivatives,
2255 derivatives_pt);
2256 // The SCG assembly stays on the calling thread. A team around this
2257 // product made the one-thread train slower than the base process.
2258 // The local-oracle path still uses its own gate.
2259#if defined(USE_OPENMP) || defined(GPR_OPENMP_LOCAL_ORACLE)
2260#pragma omp parallel for schedule(static) if (sexpat_local_oracle_active)
2261#endif
2262 for (Index_t pt = 0; pt < n_pt; ++pt) {
2263 DK_pt[n * n_pt + pt] =
2264 (magnSigma2 * expdist *
2265 (-derivatives_pt.D1[pt].array() +
2266 0.5 * derivatives.D1[0].array() * dist_pt[pt].array()))
2267 .matrix();
2268 }
2269 }
2270
2271 if (lengthScale.size() == 1 && n_pt > 1) {
2272 for (Index_t n = 0; n < n_dims; ++n) {
2273 FieldMatrixd total = DK_pt[n * n_pt];
2274 for (Index_t pt = 1; pt < n_pt; ++pt)
2275 total += DK_pt[n * n_pt + pt];
2276 DKff.push_back(std::move(total));
2277 }
2278 } else {
2279 for (Index_t n = 0; n < n_dims; ++n) {
2280 for (Index_t pt = 0; pt < n_pt; ++pt)
2281 DKff.push_back(DK_pt[n * n_pt + pt]);
2282 }
2283 }
2284}
2285
2287 const Coord& x1, Coord& x2, FieldMatrixIdx& dims1, FieldMatrixIdx& dims2,
2288 std::vector<FieldMatrixd>& DKff)
2289{
2290 if (usesManifoldChart()) {
2291 if (dims1.size() != 1 || dims2.size() != 1)
2292 throw std::invalid_argument(
2293 "chart derivative dimensions must be 1x1");
2294 if (x2.size() == 0) x2 = x1;
2295 DKff.clear();
2296 for (const auto derivative:
2299 DKff.push_back(chartParameterBlock(x1, x2, dims1(0) - 1,
2300 dims2(0) - 1, derivative));
2301 return;
2302 }
2303
2304 const PrimitiveKernelScope primitive(compose_operators_);
2305
2306 // thread_local assembly scratch, the same treatment ginput2/3/4 already
2307 // give their temporaries. These are vectors of Eigen matrices rebuilt on
2308 // every call; as plain locals each call reallocated every block, which is
2309 // where perf attributes ~11% of this path to memmove and memset. Each is
2310 // cleared or fully overwritten below, so reuse is value-identical.
2311 thread_local std::vector<FieldMatrixd> Cdm;
2312 thread_local aux::Gradient grad_calculator;
2313 grad_calculator.setFarFieldRadius(far_field_radius_);
2314 thread_local std::vector<FieldMatrixd> dist_pt;
2315 thread_local std::vector<FieldMatrixd> DK_pt;
2317 thread_local Derivatives<std::vector<FieldMatrixd>> derivatives_pt;
2318 thread_local std::vector<FieldMatrixd> DKdd;
2319 thread_local FieldMatrixd DK;
2320 // derivatives.* are reserve+push_back'd per dimension, so they must start
2321 // empty. derivatives_pt.* are sized and zeroed in full by
2322 // resizeDerivativeFields, so clearing them here only throws away storage
2323 // that the next call reallocates.
2324 derivatives.D1.clear();
2325 derivatives.D2.clear();
2326 derivatives.D12.clear();
2327 uint8_t calc_options =
2331
2332 DKff.clear();
2333
2334 if (x2.size() == 0) x2 = x1;
2335
2336 // The per-pairtype loop below assigns DK once per derivative dimension and
2337 // pushes a single block afterwards, so with more than one dimension every
2338 // block but the last is computed and dropped. Every call site passes a
2339 // 1x1 dims (GaussianProcessRegression.inl, StudentTProcessRegression.cpp),
2340 // which is the only shape the body is correct for. Refuse anything else
2341 // rather than return a silently truncated result.
2342 if (dims1.size() != 1 || dims2.size() != 1) {
2343 throw std::invalid_argument(
2344 "SexpatCF::calculateGradOfCovMatrixWithDerivatives2 handles one "
2345 "derivative dimension per side; dims1 and dims2 must be 1x1");
2346 }
2347
2348 // Compute the derivative fields first. ginput3 needs D1/D2/D12 over these
2349 // same inputs and this call already asks for them plus the _pt fields, so
2350 // handing them over means the pair is built once instead of twice. The
2351 // direction argument that appears to distinguish the two requests is
2352 // never read (Gradient.cpp), so the shared fields are the same values.
2353 dist_calculator_.dist_at_vec(x1, x2, conf_info, lengthScale, dist_pt);
2354
2355 grad_calculator.calculateDerivativesDiffDim(
2356 x1, x2, conf_info, lengthScale, dims1, dims2, calc_options,
2357 Directions::x, derivatives, derivatives_pt);
2358
2359 // ginput2/ginput3 already evaluate exp(-0.5 * d^2) over exactly these
2360 // distances; take theirs instead of recomputing the transcendental, which
2361 // also makes the dist_at_cached_sq that only fed it unnecessary here.
2362 ExpDistArray expdist;
2363 if (dims1(0, 0) == dims2(0, 0))
2364 ginput2(x1, x2, dims1, DKdd, &expdist);
2365 else
2366 ginput3(x1, x2, dims1, dims2, DKdd, &expdist, &derivatives);
2367
2368 DKff.push_back(std::move(DKdd[0]));
2369
2370 for (Index_t pt = 0; pt < conf_info.n_pt; ++pt) {
2371 for (Eigen::Index n = 0; n < dims1.size(); ++n) {
2372 DK = (magnSigma2 * expdist *
2373 (-derivatives_pt.D12[pt].array() -
2374 0.25 * derivatives.D1[n].array() *
2375 derivatives.D2[n].array() * dist_pt[pt].array() +
2376 0.5 * (derivatives.D1[n].array() *
2377 derivatives_pt.D2[pt].array() +
2378 derivatives.D2[n].array() *
2379 derivatives_pt.D1[pt].array() +
2380 dist_pt[pt].array() * derivatives.D12[n].array())))
2381 .matrix();
2382 }
2383 DKff.push_back(std::move(DK));
2384 }
2385 if (lengthScale.size() == 1 && conf_info.n_pt > 1) {
2386 for (std::size_t pt = 2; pt < DKff.size(); ++pt)
2387 DKff[1] += DKff[pt];
2388 DKff.resize(2);
2389 }
2390}
2391
2393 const Coord& x1, Coord& x2, const Eigen::VectorXd& direction,
2394 FieldMatrixd& first, FieldMatrixd& second)
2395{
2396 if (usesManifoldChart()) {
2397 if (x2.size() == 0) x2 = x1;
2398 chartDirectionalBlocks(x1, x2, -1, -1, direction, first, second);
2399 return;
2400 }
2401
2402 first.resize(0, 0);
2403 second.resize(0, 0);
2404 if (lengthScale.size() == 0) return;
2405
2406 FieldMatrixd K = evaluate_kernel_matrix(*this, x1, x2);
2407 std::vector<FieldMatrixd> dist_pt;
2408 dist_calculator_.dist_at_vec(x1, x2, conf_info, lengthScale, dist_pt);
2409
2410 const auto dirs = unpack_direction(*this, direction);
2411 FieldMatrixd k1, k2;
2412 compute_kernel_prefactors(K, dist_pt, dirs.length_dir, dirs.sigma_dir, k1,
2413 k2);
2414
2415 first = (K.array() * k1.array()).matrix();
2416 second = (K.array() * k2.array()).matrix();
2417}
2418
2420 const Coord& x1, Coord& x2, FieldMatrixIdx& dims,
2421 const Eigen::VectorXd& direction, FieldMatrixd& first, FieldMatrixd& second)
2422{
2423 if (usesManifoldChart()) {
2424 if (x2.size() == 0) x2 = x1;
2425 chartDirectionalBlocks(x1, x2, dims(0) - 1, -1, direction, first,
2426 second);
2427 return;
2428 }
2429
2430 first.resize(0, 0);
2431 second.resize(0, 0);
2432 if (lengthScale.size() == 0) return;
2433
2434 if (x2.size() == 0) x2 = x1;
2435
2436 aux::Gradient grad_calculator;
2437 grad_calculator.setFarFieldRadius(far_field_radius_);
2440 const uint8_t calc_options =
2442
2443 grad_calculator.calculateDerivativesSameDim(x1, x2, conf_info, lengthScale,
2444 dims, calc_options, derivatives,
2445 derivatives_pt);
2446
2447 std::vector<FieldMatrixd> dist_pt;
2448 dist_calculator_.dist_at_vec(x1, x2, conf_info, lengthScale, dist_pt);
2449 FieldMatrixd K = evaluate_kernel_matrix(*this, x1, x2);
2450
2451 const auto dirs = unpack_direction(*this, direction);
2452 FieldMatrixd k1, k2;
2453 compute_kernel_prefactors(K, dist_pt, dirs.length_dir, dirs.sigma_dir, k1,
2454 k2);
2455
2456 FieldMatrixd d1_first;
2457 FieldMatrixd d1_second;
2458 accumulate_directional_pt_fields(derivatives_pt.D1, dirs.length_dir, 2.0,
2459 -4.0, d1_first, d1_second);
2460
2461 const auto& D1 = derivatives.D1[0];
2462 first = (-0.5 * K.array() * (k1.array() * D1.array() + d1_first.array()))
2463 .matrix();
2464 second = (-0.5 * K.array() *
2465 (k2.array() * D1.array() + 2.0 * k1.array() * d1_first.array() +
2466 d1_second.array()))
2467 .matrix();
2468}
2469
2471 const Coord& x1, Coord& x2, FieldMatrixIdx& dims1, FieldMatrixIdx& dims2,
2472 const Eigen::VectorXd& direction, FieldMatrixd& first, FieldMatrixd& second)
2473{
2474 if (usesManifoldChart()) {
2475 if (x2.size() == 0) x2 = x1;
2476 chartDirectionalBlocks(x1, x2, dims1(0) - 1, dims2(0) - 1, direction,
2477 first, second);
2478 return;
2479 }
2480
2481 first.resize(0, 0);
2482 second.resize(0, 0);
2483 if (lengthScale.size() == 0) return;
2484
2485 if (x2.size() == 0) x2 = x1;
2486
2487 aux::Gradient grad_calculator;
2488 grad_calculator.setFarFieldRadius(far_field_radius_);
2491 const uint8_t calc_options =
2495
2496 if (dims1(0, 0) == dims2(0, 0)) {
2497 grad_calculator.calculateDerivativesSameDim(
2498 x1, x2, conf_info, lengthScale, dims1, calc_options, derivatives,
2499 derivatives_pt);
2500 } else {
2501 grad_calculator.calculateDerivativesDiffDim(
2502 x1, x2, conf_info, lengthScale, dims1, dims2, calc_options,
2503 Directions::x, derivatives, derivatives_pt);
2504 }
2505
2506 std::vector<FieldMatrixd> dist_pt;
2507 dist_calculator_.dist_at_vec(x1, x2, conf_info, lengthScale, dist_pt);
2508 FieldMatrixd K = evaluate_kernel_matrix(*this, x1, x2);
2509
2510 const auto dirs = unpack_direction(*this, direction);
2511 FieldMatrixd k1, k2;
2512 compute_kernel_prefactors(K, dist_pt, dirs.length_dir, dirs.sigma_dir, k1,
2513 k2);
2514
2515 FieldMatrixd d1_first, d1_second, d2_first, d2_second, d12_first,
2516 d12_second;
2517 accumulate_directional_pt_fields(derivatives_pt.D1, dirs.length_dir, 2.0,
2518 -4.0, d1_first, d1_second);
2519 accumulate_directional_pt_fields(derivatives_pt.D2, dirs.length_dir, 2.0,
2520 -4.0, d2_first, d2_second);
2521 accumulate_directional_pt_fields(derivatives_pt.D12, dirs.length_dir, 2.0,
2522 -4.0, d12_first, d12_second);
2523
2524 const auto& D1 = derivatives.D1[0];
2525 const auto& D2 = derivatives.D2[0];
2526 const auto& D12 = derivatives.D12[0];
2527
2528 const FieldMatrixd base =
2529 (-0.5 * D12.array() + 0.25 * D1.array() * D2.array()).matrix();
2530 const FieldMatrixd base_first =
2531 (-0.5 * d12_first.array() +
2532 0.25 * (d1_first.array() * D2.array() + D1.array() * d2_first.array()))
2533 .matrix();
2534 const FieldMatrixd base_second =
2535 (-0.5 * d12_second.array() +
2536 0.25 * (d1_second.array() * D2.array() +
2537 2.0 * d1_first.array() * d2_first.array() +
2538 D1.array() * d2_second.array()))
2539 .matrix();
2540
2541 first =
2542 (K.array() * (k1.array() * base.array() + base_first.array())).matrix();
2543 second = (K.array() *
2544 (k2.array() * base.array() +
2545 2.0 * k1.array() * base_first.array() + base_second.array()))
2546 .matrix();
2547}
2548
2550 const Eigen::VectorXd& direction) const
2551{
2552 const auto& active_lengths = getLengthScaleRef();
2553 if (direction.size() == 0) return 0.0;
2554
2555 const auto dirs = unpack_direction(*this, direction);
2556
2557 if (!usesClassicJointEnergyForcePrior(model_profile_)) {
2558 if (use_hierarchical_prior_) {
2559 const Eigen::Index expected = 1 + active_lengths.size();
2560 if (hierarchical_mu_log_.size() != expected) return 0.0;
2561 double curvature = 0.0;
2562 const double s2_m = hierarchicalPriorVariance(0);
2563 if (s2_m > 0.0) curvature -= dirs.sigma_dir * dirs.sigma_dir / s2_m;
2564 for (Eigen::Index i = 0; i < active_lengths.size(); ++i) {
2565 const double s2 = hierarchicalPriorVariance(i + 1);
2566 if (!(s2 > 0.0)) continue;
2567 const double d = expanded_length_direction(dirs.length_dir, i);
2568 curvature -= lengthPriorWeight(i) * d * d / s2;
2569 }
2570 return curvature;
2571 }
2572 if (use_pc_lengthscale_prior_ &&
2573 pc_lambda_.size() == active_lengths.size()) {
2574 double curvature = 0.0;
2575 for (Eigen::Index i = 0; i < active_lengths.size(); ++i) {
2576 const double rho = *(active_lengths.data() + i);
2577 const double lambda = pc_lambda_(i);
2578 const double d = expanded_length_direction(dirs.length_dir, i);
2579 if (rho > 0.0 && lambda > 0.0) {
2580 curvature -= lengthPriorWeight(i) * lambda * d * d / rho;
2581 }
2582 }
2583 return curvature;
2584 }
2585 return 0.0;
2586 }
2587
2588 double curvature = 0.0;
2589
2590 PriorGaussian prior_gaussian;
2591 PriorSqrtt prior_sqrtt;
2592 prior_gaussian.setParameters(prior_parameters_gaussian);
2593 prior_sqrtt.setParameters(prior_parameters_sqrtt);
2594
2595 if (use_lognormal_magn_prior_ && prior_parameters_lognormal.getS2() > 0.0 &&
2596 magnSigma2 > 0.0 && std::isfinite(magnSigma2)) {
2597 curvature -= dirs.sigma_dir * dirs.sigma_dir /
2598 prior_parameters_lognormal.getS2();
2599 } else if (magnSigma2 > 0.0 && prior_sqrtt.getNu() > 0.0 &&
2600 prior_sqrtt.getS2() > 0.0) {
2601 Dual2 sigma = direction_dual(magnSigma2, dirs.sigma_dir);
2602 Dual2 sqrt_sigma = sqrt_dual(sigma);
2603 const double nu = prior_sqrtt.getNu();
2604 const double mu = prior_sqrtt.getMu();
2605 const double s2 = prior_sqrtt.getS2();
2606
2607 Dual2 centered = sqrt_sigma - constant_dual(mu);
2608 Dual2 log_prior =
2609 constant_dual(numerics::lgamma(0.5 * (nu + 1)) -
2610 numerics::lgamma(0.5 * nu) -
2611 0.5 * numerics::log(nu * M_PI * s2)) -
2612 0.5 * (nu + 1) *
2613 log_dual(constant_dual(1.0) +
2614 centered * centered / constant_dual(nu * s2)) -
2615 log_dual(2.0 * sqrt_sigma) + log_dual(sigma);
2616 curvature += log_prior.second;
2617 }
2618
2619 const double gauss_s2 = prior_gaussian.getS2();
2620 const double gauss_mu = prior_gaussian.getMu();
2621 const bool anchors_ready =
2622 use_hierarchical_prior_ &&
2623 hierarchical_mu_log_.size() == 1 + active_lengths.size();
2624 if (gauss_s2 > 0.0 || anchors_ready) {
2625 for (Eigen::Index i = 0; i < active_lengths.size(); ++i) {
2626 const double dir = expanded_length_direction(dirs.length_dir, i);
2627 const double value = *(active_lengths.data() + i);
2628 const double s2_anchor = hierarchicalPriorVariance(i + 1);
2629 if (anchors_ready && hierarchicalAnchored(i) && s2_anchor > 0.0) {
2630 // Log-Gaussian in log space: the curvature along the
2631 // direction is -d^2 / s2.
2632 curvature -= lengthPriorWeight(i) * dir * dir / s2_anchor;
2633 continue;
2634 }
2635 if (!(gauss_s2 > 0.0)) continue;
2636 Dual2 ell = direction_dual(value, dir);
2637 Dual2 centered = ell - constant_dual(gauss_mu);
2638 Dual2 log_prior =
2639 constant_dual(-0.5 * (numerics::log(2.0 * M_PI) +
2640 numerics::log(gauss_s2))) -
2641 0.5 * centered * centered / constant_dual(gauss_s2) +
2642 log_dual(ell);
2643 curvature += lengthPriorWeight(i) * log_prior.second;
2644 }
2645 }
2646
2647 return curvature;
2648}
2649
2650void SexpatCF::ginput2(const Coord& x1, Coord& x2, FieldMatrixIdx& dims,
2651 std::vector<FieldMatrixd>& DKff,
2652 ExpDistArray* out_expdist)
2653{
2654 if (compose_operators_ && usesManifoldChart()) {
2655 if (x2.size() == 0) x2 = x1;
2656 const auto op = assembledOperator();
2657 DKff.clear();
2658 DKff.reserve(static_cast<std::size_t>(dims.size()));
2659 for (Eigen::Index n = 0; n < dims.size(); ++n) {
2660 const Eigen::Index channel = dims(n) - 1;
2661 noteManifoldGeometryRows(x1.rows(), x2.rows());
2662 DKff.push_back(op->covarianceBlock(x1, x2, channel, channel));
2663 }
2664 return;
2665 }
2666 // thread_local assembly scratch: reuses the gradient-block temporaries
2667 // across the many ginput calls per outer (per SCG NLML eval and per
2668 // inner-loop predict). The Derivatives vectors are cleared at entry so
2669 // calculateDerivatives* push_backs reuse vector capacity; the
2670 // FieldMatrixd temporaries are fully overwritten before use. Value-
2671 // identical (pure allocation reuse). thread_local keeps scratch private
2672 // per thread under the OpenMP serial-oracle region.
2673 thread_local aux::Gradient grad_calculator;
2674 grad_calculator.setFarFieldRadius(far_field_radius_);
2675 thread_local FieldMatrixd dist;
2677 thread_local Derivatives<std::vector<FieldMatrixd>> derivatives_pt;
2678 thread_local FieldMatrixd DK;
2679 // derivatives.* are reserve+push_back'd per dimension, so they must start
2680 // empty. derivatives_pt.* are sized and zeroed in full by
2681 // resizeDerivativeFields, so clearing them here only throws away storage
2682 // that the next call reallocates.
2683 derivatives.D1.clear();
2684 derivatives.D2.clear();
2685 derivatives.D12.clear();
2686 uint8_t calc_options = OptionsForGradCalculation::D1 |
2689
2690 DKff.clear();
2691
2692 dist_calculator_.dist_at_cached_sq(x1, x2, conf_info, lengthScale, dist);
2693
2694 grad_calculator.calculateDerivativesSameDim(x1, x2, conf_info, lengthScale,
2695 dims, calc_options, derivatives,
2696 derivatives_pt);
2697
2698 // dist already stores squared distances here. thread_local exp buffer
2699 // reused across calls (RowMajor matches dist's storage).
2700 thread_local Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic,
2701 Eigen::RowMajor>
2702 expdist;
2703 expdist = (-0.5 * dist.array()).exp();
2704 // Hand the factor to a caller that needs the same exp over the same
2705 // distances, so it is evaluated once per call rather than twice.
2706 if (out_expdist != nullptr) *out_expdist = expdist;
2707
2708 for (Eigen::Index n = 0; n < dims.size(); ++n) {
2709 DK = (magnSigma2 * expdist *
2710 (-0.5 * derivatives.D12[n].array() +
2711 0.25 * derivatives.D1[n].array() * derivatives.D2[n].array()))
2712 .matrix();
2713 if (compose_operators_ && usesGeodesicHeatKernel()) {
2714 const Eigen::Index channel = dims(n) - 1;
2715 DK += GeodesicHeat(geodesic_heat_kernel_)
2716 .covarianceBlock(x1, x2, channel, channel);
2717 }
2718 DKff.push_back(std::move(DK));
2719 }
2720}
2721
2722void SexpatCF::ginput3(const Coord& x1, Coord& x2, FieldMatrixIdx& dims1,
2723 FieldMatrixIdx& dims2, std::vector<FieldMatrixd>& DKff,
2724 ExpDistArray* out_expdist,
2725 const SharedDerivatives* precomputed)
2726{
2727 if (compose_operators_ && usesManifoldChart()) {
2728 if (x2.size() == 0) x2 = x1;
2729 const auto op = assembledOperator();
2730 DKff.clear();
2731 DKff.reserve(static_cast<std::size_t>(dims1.size() * dims2.size()));
2732 for (Eigen::Index i = 0; i < dims1.size(); ++i) {
2733 for (Eigen::Index j = 0; j < dims2.size(); ++j) {
2734 noteManifoldGeometryRows(x1.rows(), x2.rows());
2735 DKff.push_back(
2736 op->covarianceBlock(x1, x2, dims1(i) - 1, dims2(j) - 1));
2737 }
2738 }
2739 return;
2740 }
2741 // thread_local assembly scratch: see ginput2 above for the value-
2742 // identity argument. Cleared at entry so vector capacity is reused.
2743 thread_local aux::Gradient grad_calculator;
2744 grad_calculator.setFarFieldRadius(far_field_radius_);
2745 thread_local FieldMatrixd dist;
2747 thread_local Derivatives<std::vector<FieldMatrixd>> derivatives_pt;
2748 thread_local FieldMatrixd DK;
2749 // derivatives.* are reserve+push_back'd per dimension, so they must start
2750 // empty. derivatives_pt.* are sized and zeroed in full by
2751 // resizeDerivativeFields, so clearing them here only throws away storage
2752 // that the next call reallocates.
2753 derivatives.D1.clear();
2754 derivatives.D2.clear();
2755 derivatives.D12.clear();
2756 uint8_t calc_options = OptionsForGradCalculation::D1 |
2759
2760 DKff.clear();
2761
2762 dist_calculator_.dist_at_cached_sq(x1, x2, conf_info, lengthScale, dist);
2763
2764 // The caller may already hold these: it asks for D1|D2|D12 plus the _pt
2765 // fields over the same inputs, and Gradient.cpp never reads the direction
2766 // argument that appears to distinguish the two requests, so the D1/D2/D12
2767 // it gets back are the same values this call would produce.
2768 const SharedDerivatives* active = precomputed;
2769 if (active == nullptr) {
2770 grad_calculator.calculateDerivativesDiffDim(
2771 x1, x2, conf_info, lengthScale, dims1, dims2, calc_options,
2772 Directions::y, derivatives, derivatives_pt);
2773 active = &derivatives;
2774 }
2775
2776 // dist already stores squared distances here. thread_local exp buffer
2777 // reused across calls instead of a fresh per-call eval() temporary;
2778 // RowMajor matches dist's storage so the assignment is a plain copy.
2779 thread_local Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic,
2780 Eigen::RowMajor>
2781 expdist;
2782 expdist = (-0.5 * dist.array()).exp();
2783 // Hand the factor to a caller that needs the same exp over the same
2784 // distances, so it is evaluated once per call rather than twice.
2785 if (out_expdist != nullptr) *out_expdist = expdist;
2786
2787 Index_t n = 0;
2788 for (Eigen::Index i = 0; i < dims1.size(); ++i) {
2789 for (Eigen::Index j = 0; j < dims2.size(); ++j) {
2790 DK = (magnSigma2 * expdist *
2791 (-0.5 * active->D12[n].array() +
2792 0.25 * active->D1[n].array() * active->D2[n].array()))
2793 .matrix();
2794 if (compose_operators_ && usesGeodesicHeatKernel()) {
2795 DK += GeodesicHeat(geodesic_heat_kernel_)
2796 .covarianceBlock(x1, x2, dims1(i) - 1, dims2(j) - 1);
2797 }
2798 DKff.push_back(std::move(DK));
2799 ++n;
2800 }
2801 }
2802}
2803
2804void SexpatCF::ginput4(const Coord& x1, Coord& x2, FieldMatrixIdx& dims,
2805 std::vector<FieldMatrixd>& DKff,
2806 ExpDistArray* out_expdist)
2807{
2808 if (compose_operators_ && usesManifoldChart()) {
2809 if (x2.size() == 0) x2 = x1;
2810 const auto op = assembledOperator();
2811 DKff.clear();
2812 DKff.reserve(static_cast<std::size_t>(dims.size()));
2813 for (Eigen::Index n = 0; n < dims.size(); ++n) {
2814 noteManifoldGeometryRows(x1.rows(), x2.rows());
2815 DKff.push_back(op->covarianceBlock(x1, x2, dims(n) - 1, -1));
2816 }
2817 return;
2818 }
2819 // thread_local assembly scratch: see ginput2 above for the value-
2820 // identity argument. Cleared at entry so vector capacity is reused.
2821 thread_local aux::Gradient grad_calculator;
2822 grad_calculator.setFarFieldRadius(far_field_radius_);
2823 thread_local FieldMatrixd dist;
2825 thread_local Derivatives<std::vector<FieldMatrixd>> derivatives_pt;
2826 thread_local FieldMatrixd DK;
2827 // derivatives.* are reserve+push_back'd per dimension, so they must start
2828 // empty. derivatives_pt.* are sized and zeroed in full by
2829 // resizeDerivativeFields, so clearing them here only throws away storage
2830 // that the next call reallocates.
2831 derivatives.D1.clear();
2832 derivatives.D2.clear();
2833 derivatives.D12.clear();
2834 uint8_t calc_options = OptionsForGradCalculation::D1;
2835
2836 DKff.clear();
2837
2838 if (x2.size() == 0) x2 = x1;
2839
2840 dist_calculator_.dist_at_cached_sq(x1, x2, conf_info, lengthScale, dist);
2841
2842 grad_calculator.calculateDerivativesSameDim(x1, x2, conf_info, lengthScale,
2843 dims, calc_options, derivatives,
2844 derivatives_pt);
2845
2846 // Pre-compute the common exponential factor. thread_local buffer reused
2847 // across calls (RowMajor matches dist's storage).
2848 thread_local Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic,
2849 Eigen::RowMajor>
2850 exp_factor;
2851 // Materialise the bare exp first so a caller can take it instead of
2852 // evaluating the same transcendental again. `-0.5 * magnSigma2` is a
2853 // scalar product folded before the elementwise multiply either way, so
2854 // scaling from the materialised factor gives the same values.
2855 thread_local Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic,
2856 Eigen::RowMajor>
2857 expdist;
2858 expdist = (-0.5 * dist.array()).exp();
2859 if (out_expdist != nullptr) *out_expdist = expdist;
2860 exp_factor = -0.5 * magnSigma2 * expdist;
2861
2862 for (Eigen::Index n = 0; n < dims.size(); ++n) {
2863 DK = (exp_factor * derivatives.D1[n].array()).matrix();
2864 if (compose_operators_ && usesGeodesicHeatKernel()) {
2865 DK += GeodesicHeat(geodesic_heat_kernel_)
2866 .covarianceBlock(x1, x2, dims(n) - 1, -1);
2867 }
2868 DKff.push_back(std::move(DK));
2869 }
2870}
2871
2873 const Coord& x_train, const Coord& x_test,
2874 const Eigen::Ref<const Eigen::VectorXd>& alpha_E,
2875 const Eigen::Ref<const Eigen::VectorXd>& alpha_G_flat,
2876 Eigen::Ref<Eigen::VectorXd> mu_E_out,
2877 Eigen::Ref<
2878 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>
2879 mu_G_out)
2880{
2881 Sexpat(*this).predictMeanAlphaK(x_train, x_test, alpha_E, alpha_G_flat,
2882 mu_E_out, mu_G_out);
2883}
2884
2886 const Coord& x_train, const Eigen::Ref<const Eigen::VectorXd>& alpha_E,
2887 const Eigen::Ref<const Eigen::VectorXd>& alpha_G_flat,
2888 PreparedAlphaK& prepared) const
2889{
2890 return Sexpat(*this).prepareAlphaK(x_train, alpha_E, alpha_G_flat,
2891 prepared);
2892}
2893
2895 const PreparedAlphaK& prepared, const Coord& x_test,
2896 Eigen::Ref<Eigen::VectorXd> mu_E_out,
2897 Eigen::Ref<
2898 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>
2899 mu_G_out) const
2900{
2901 Sexpat(*this).predictMeanAlphaKPrepared(prepared, x_test, mu_E_out,
2902 mu_G_out);
2903}
2904
2906 const Coord& x_train, const Eigen::Ref<const Eigen::VectorXd>& alpha_E,
2907 const Eigen::Ref<const Eigen::VectorXd>& alpha_G_flat,
2908 Eigen::Ref<Eigen::VectorXd> quad_out, bool distributed,
2909 std::size_t* local_pair_count, const linalg::MpiContext* process_group)
2910{
2911 Sexpat(*this).trainingGradientAlphaK(x_train, alpha_E, alpha_G_flat,
2912 quad_out, distributed,
2913 local_pair_count, process_group);
2914}
2915
2916void SexpatCF::cacheDistances(const Coord& x1, const Coord& x2)
2917{
2918 dist_calculator_.cacheInverseDistances(x1, x2, conf_info);
2919}
2920
2921void SexpatCF::correlationDistances(const Coord& left, const Coord& right,
2922 const AtomsConfiguration& configuration,
2923 FieldMatrixd& distances) const
2924{
2925 if (usesGeodesicHeatKernel()) {
2926 distances =
2927 assembledOperator()->energyCorrelationDistances(left, right);
2928 return;
2929 }
2930 if (!usesManifoldChart()) {
2931 aux::Distance metric;
2932 metric.setFarFieldRadius(far_field_radius_);
2933 metric.dist_at(left, right, configuration, lengthScale, distances);
2934 return;
2935 }
2936
2937 distances.resize(left.rows(), right.rows());
2938 distances.setConstant(std::numeric_limits<double>::infinity());
2939 if (left.cols() != manifoldDimensions() ||
2940 right.cols() != manifoldDimensions() || !left.allFinite() ||
2941 !right.allFinite() || chart_length_scale_.size() != 1) {
2942 return;
2943 }
2944 const double scale = chart_length_scale_(0, 0);
2945 if (!(scale > 0.0) || !std::isfinite(scale)) return;
2946
2947 Eigen::MatrixXd right_coordinates(right.rows(), manifold_chart_->rank());
2948 for (Eigen::Index j = 0; j < right.rows(); ++j) {
2949 right_coordinates.row(j) =
2950 manifold_chart_->coordinates(right.row(j).transpose()).transpose();
2951 }
2952 for (Eigen::Index i = 0; i < left.rows(); ++i) {
2953 const Eigen::VectorXd coordinate =
2954 manifold_chart_->coordinates(left.row(i).transpose());
2955 for (Eigen::Index j = 0; j < right.rows(); ++j) {
2956 distances(i, j) =
2957 (coordinate - right_coordinates.row(j).transpose()).norm() /
2958 scale;
2959 }
2960 }
2961}
2962
2964{
2965 dist_calculator_.clearCache();
2966}
2967
2968} /* namespace gpr */
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
@ D1_pt
Definition Enums.h:23
@ D1
Definition Enums.h:19
@ D12
Definition Enums.h:21
@ D2_pt
Definition Enums.h:24
@ D2
Definition Enums.h:20
@ D12_pt
Definition Enums.h:25
Methods to calculate distances between atoms.
Definition Distance.h:154
void dist_at_vec(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale, std::vector< gpr::FieldMatrixd > &dist)
Similar to dist_at but calculates vector of distances for every pair of moving and frozen atoms.
Definition Distance.cpp:796
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 setFarFieldRadius(double radius)
Definition Distance.cpp:299
Methods to calculate gradients (derivatives) with respect to different directions.
Definition Gradient.h:28
void setFarFieldRadius(double radius)
Definition Gradient.cpp:885
void calculateDerivativesDiffDim(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthScale, const gpr::FieldMatrixIdx &dims1, const gpr::FieldMatrixIdx &dims2, const uint8_t calc_options, const uint8_t direction_x2, gpr::Derivatives< std::vector< gpr::FieldMatrixd > > &derivatives, gpr::Derivatives< std::vector< gpr::FieldMatrixd > > &derivatives_pt)
Evaluate gradient of covariance function, of which has been taken partial derivatives with respect to...
Definition Gradient.cpp:655
void calculateDerivativesSameDim(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthScale, const gpr::FieldMatrixIdx &dims, uint8_t calc_options, gpr::Derivatives< std::vector< gpr::FieldMatrixd > > &derivatives, gpr::Derivatives< std::vector< gpr::FieldMatrixd > > &derivatives_pt)
Evaluate gradient of covariance function with respect to both input variables x and x2 (in same dimen...
Definition Gradient.cpp:555
Eigen::MatrixXd covarianceBlock(const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions, Eigen::Index left_channel, Eigen::Index right_channel) const override
Covariance between one channel at each set of geometry rows.
Eigen::MatrixXd jointEnergyGradientCrossCovariance(const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions) const override
Cross covariance in Observation order on each operand.
Eigen::MatrixXd jointEnergyGradientCovariance(const Eigen::MatrixXd &positions) const override
Joint covariance in Observation order [E; G_col0; ...; G_colD-1].
void setParameters(const PriorBase &other)
Definition PriorBase.h:78
double getMu() const
Definition PriorBase.h:48
double getS2() const
Definition PriorBase.h:53
double getNu() const
Definition PriorBase.h:58
Gaussian prior.
double calculateLogPrior(const FieldMatrixd &x) override
FieldMatrixd calculateLogPriorGradient(const FieldMatrixd &x) override
Log-normal prior.
double calculateLogPrior(const FieldMatrixd &x) override
Student-t prior for the square root of the parameter.
Definition PriorSqrtt.h:31
double calculateLogPrior(const FieldMatrixd &x) override
FieldMatrixd calculateLogPriorGradient(const FieldMatrixd &x) override
Eigen::MatrixXd covarianceBlock(const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions, Eigen::Index left_channel, Eigen::Index right_channel) const override
Covariance between one channel at each set of geometry rows.
Eigen::MatrixXd jointEnergyGradientCovariance(const Eigen::MatrixXd &positions) const override
Joint covariance in Observation order [E; G_col0; ...; G_colD-1].
Eigen::MatrixXd jointEnergyGradientCrossCovariance(const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions) const override
Cross covariance in Observation order on each operand.
Pair-type inverse-distance squared-exponential primitive.
Definition SexpatCF.h:74
bool calculateGradOfCovMatrixFromGeometry(const FieldMatrixd &shared_kernel, const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, std::vector< FieldMatrixd > &DKff, const std::vector< Eigen::Index > *parameter_indices=nullptr) const
Geometry-path replacement for calculateGradOfCovMatrix. Produces DKff[0] = K (untruncated kernel),...
void predictMeanAlphaKPrepared(const PreparedAlphaK &prepared, const Coord &x_test, Eigen::Ref< Eigen::VectorXd > mu_E_out, Eigen::Ref< Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > > mu_G_out) const
bool calculateGradOfCovMatrixWithDerivativesFromGeometry(const CrossBlockGeometry &geometry, const FieldMatrixd &shared_kernel, const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, std::vector< FieldMatrixd > &DKff, const std::vector< Eigen::Index > *parameter_indices=nullptr) const
Geometry-path replacement for calculateGradOfCovMatrixWithDerivatives (Kdf block dK).
bool buildCrossBlockGeometry(const Coord &x1, const Coord &x2, uint8_t derivative_options, const FieldMatrixIdx &dims1, const FieldMatrixIdx &dims2, CrossBlockGeometry &geometry) const
Build theta-independent pairtype geometry for a covariance block.
Definition SexpatCF.cpp:806
bool calculateDirectionalCovarianceMatrixWithDerivatives2FromGeometry(const CrossBlockGeometry &geometry, const FieldMatrixd &shared_kernel, const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, const Eigen::VectorXd &direction, FieldMatrixd &first, FieldMatrixd &second) const
Directional first and second derivatives for a D/Kdf2 block from shared training geometry.
FieldMatrixd manifoldJointEnergyGradientCovariance(const Coord &positions) const
Definition SexpatCF.cpp:751
bool calculateGradOfCovMatrixWithDerivatives2FromGeometry(const CrossBlockGeometry &geometry, const FieldMatrixd &shared_kernel, const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, std::vector< FieldMatrixd > &DKff, const std::vector< Eigen::Index > *parameter_indices=nullptr) const
Geometry-path replacement for calculateGradOfCovMatrixWithDerivatives2 (D and Kdf2 blocks).
void calculateDirectionalCovarianceMatrix(const Coord &x1, Coord &x2, const Eigen::VectorXd &direction, FieldMatrixd &first, FieldMatrixd &second)
Evaluate the directional first and second derivatives of the covariance matrix along a parameter-spac...
bool evaluateCrossBlockGeometryShared(const CrossBlockGeometry &geometry, const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, FieldMatrixd &out) const
Same as evaluateCrossBlockGeometry but reads the per-pairtype distance from an externally-shared tens...
void ginput2(const Coord &x1, Coord &x2, FieldMatrixIdx &dims, std::vector< FieldMatrixd > &DKff, ExpDistArray *out_expdist=nullptr)
void clearGeodesicHeatKernel() noexcept
Definition SexpatCF.cpp:723
double calculateDirectionalLogPriorCurvature(const Eigen::VectorXd &direction) const
Evaluate the second directional derivative of log p(theta) along the packed log-parameter direction.
bool calculateDirectionalCovarianceMatrixWithDerivativesFromGeometry(const CrossBlockGeometry &geometry, const FieldMatrixd &shared_kernel, const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, const Eigen::VectorXd &direction, FieldMatrixd &first, FieldMatrixd &second) const
Directional first and second derivatives for a Kdf block from shared training geometry.
void setGeodesicHeatKernel(std::shared_ptr< const GeodesicHeatEnergyForceKernel > kernel)
Attach an immutable heat component with its own reference and metric.
Definition SexpatCF.cpp:519
void calculateGradOfCovMatrix(const Coord &x1, Coord &x2, std::vector< FieldMatrixd > &DKff)
Evaluate gradient of covariance function with respect to the parameters.
double hierarchicalPriorVariance(Eigen::Index n) const noexcept
Variance of packed parameter ~n~ under the hierarchical prior.
Definition SexpatCF.h:799
bool buildSharedDistanceForTrainingGeometry(const Coord &x_loc, std::vector< FieldMatrixd > &shared_distance_neg_per_pt) const
Build the per-pairtype distance tensor at unit lengthscale for a single coordinate slice (shared acro...
Definition SexpatCF.cpp:907
void cacheDistances(const Coord &x1, const Coord &x2)
Pre-compute and cache inverse distances for the given positions.
void correlationDistances(const Coord &left, const Coord &right, const AtomsConfiguration &configuration, FieldMatrixd &distances) const
FieldMatrixd calculateLogPriorGradient()
Evaluate the gradient of the log prior density of the parameters with respect to parameters.
Definition SexpatCF.cpp:370
void trainingGradientAlphaK(const Coord &x_train, const Eigen::Ref< const Eigen::VectorXd > &alpha_E, const Eigen::Ref< const Eigen::VectorXd > &alpha_G_flat, Eigen::Ref< Eigen::VectorXd > quad_out, bool distributed=false, std::size_t *local_pair_count=nullptr, const linalg::MpiContext *process_group=nullptr)
void calculateTrainingCovarianceMatrix(const Coord &x, FieldMatrixd &C)
Evaluate the prior variance for each training input.
Definition SexpatCF.cpp:786
bool calculateDirectionalCovarianceMatrixFromGeometry(const FieldMatrixd &shared_kernel, const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, const Eigen::VectorXd &direction, FieldMatrixd &first, FieldMatrixd &second) const
Directional first and second derivatives for the Kff block from shared training geometry.
std::shared_ptr< const KernelOperator > assembledOperator() const
The configured base and optional additive heat component.
Definition SexpatCF.cpp:585
Sexpat::PreparedAlphaK PreparedAlphaK
Definition SexpatCF.h:82
bool usesManifoldChart() const noexcept
Definition SexpatCF.h:616
Eigen::Index manifoldDimensions() const noexcept
Definition SexpatCF.h:626
FieldMatrixd geodesicHeatJointEnergyGradientCovariance(const Coord &positions) const
Definition SexpatCF.cpp:729
bool meanHessianVector(const Coord &training, const Eigen::VectorXd &weights, const Eigen::VectorXd &position, const Eigen::VectorXd &direction, Eigen::VectorXd &action) const
Definition SexpatCF.cpp:609
void predictMeanAlphaK(const Coord &x_train, const Coord &x_test, const Eigen::Ref< const Eigen::VectorXd > &alpha_E, const Eigen::Ref< const Eigen::VectorXd > &alpha_G_flat, Eigen::Ref< Eigen::VectorXd > mu_E_out, Eigen::Ref< Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > > mu_G_out)
Per-test-point predict mean (energy + gradient) via the Schmitz/Chmiela JPCL 2022 eq....
friend class Sexpat
Definition SexpatCF.h:75
bool applyCrossBlockGeometryToVector(const CrossBlockGeometry &geometry, const Eigen::VectorXd &theta, const Eigen::VectorXd &weights, bool transpose_field, Eigen::VectorXd &out) const
Apply a cross-block geometry directly to a vector.
void ginput4(const Coord &x1, Coord &x2, FieldMatrixIdx &dims, std::vector< FieldMatrixd > &DKff, ExpDistArray *out_expdist=nullptr)
Evaluate gradient of covariance function with respect to x.
FieldMatrixd manifoldJointEnergyGradientCrossCovariance(const Coord &left_positions, const Coord &right_positions) const
Definition SexpatCF.cpp:768
Derivatives< std::vector< FieldMatrixd > > SharedDerivatives
Evaluate gradient of covariance function with respect to both input variables x1 and x2 (in different...
Definition SexpatCF.h:502
void calculateCovarianceMatrix(const Coord &x1, Coord &x2, FieldMatrixd &C)
Evaluate covariance matrix between two input vectors.
Definition SexpatCF.cpp:461
bool evaluateCrossBlockGeometryWithSharedKernel(const CrossBlockGeometry &geometry, const FieldMatrixd &shared_kernel, const Eigen::VectorXd &theta, FieldMatrixd &out) const
Evaluate a derivative-only block against a pre-computed shared kernel matrix (from buildSharedKernel)...
bool buildCrossBlockDerivativesOnly(const Coord &x1, const Coord &x2, uint8_t derivative_options, const FieldMatrixIdx &dims1, const FieldMatrixIdx &dims2, CrossBlockGeometry &geometry) const
Populate only the derivative fields (d1, d2, d12) of a CrossBlockGeometry, skipping the per-pairtype ...
Definition SexpatCF.cpp:931
void calculateGradOfCovMatrixWithDerivatives2(const Coord &x1, Coord &x2, FieldMatrixIdx &dims1, FieldMatrixIdx &dims2, std::vector< FieldMatrixd > &DKff)
Evaluate gradient of covariance function, of which has been taken partial derivatives with respect to...
void ginput3(const Coord &x1, Coord &x2, FieldMatrixIdx &dims1, FieldMatrixIdx &dims2, std::vector< FieldMatrixd > &DKff, ExpDistArray *out_expdist=nullptr, const SharedDerivatives *precomputed=nullptr)
void rescaleGeodesicHeatCovariance(double factor)
Convert the additive component to a different output variance unit.
Definition SexpatCF.cpp:710
void clearManifoldChart()
Definition SexpatCF.cpp:513
FieldMatrixd geodesicHeatJointEnergyGradientCrossCovariance(const Coord &left_positions, const Coord &right_positions) const
Definition SexpatCF.cpp:740
FieldMatrixd & getLengthScaleRef()
Definition SexpatCF.inl:58
void setManifoldChart(std::shared_ptr< const geometry::InternalCoordinateChart > chart, double length_scale)
Definition SexpatCF.cpp:495
bool evaluateCrossBlockGeometry(const CrossBlockGeometry &geometry, const Eigen::VectorXd &theta, FieldMatrixd &out) const
Evaluate a cross-block geometry at packed Sexpat log parameters.
bool usesGeodesicHeatKernel() const noexcept
Definition SexpatCF.h:664
void calculateDirectionalCovarianceMatrixWithDerivatives2(const Coord &x1, Coord &x2, FieldMatrixIdx &dims1, FieldMatrixIdx &dims2, const Eigen::VectorXd &direction, FieldMatrixd &first, FieldMatrixd &second)
Evaluate directional first and second derivatives of the derivative-vs-derivative covariance block.
virtual ~SexpatCF()
Definition SexpatCF.cpp:250
bool hierarchicalAnchored(Eigen::Index n) const noexcept
Definition SexpatCF.h:792
void calculateGradOfCovMatrixWithDerivatives(const Coord &x1, Coord &x2, FieldMatrixIdx &dims, std::vector< FieldMatrixd > &DKff)
Evaluate gradient of covariance function, of which has been taken partial derivative with respect to ...
void calculateDirectionalCovarianceMatrixWithDerivatives(const Coord &x1, Coord &x2, FieldMatrixIdx &dims, const Eigen::VectorXd &direction, FieldMatrixd &first, FieldMatrixd &second)
Evaluate directional first and second derivatives of the derivative-vs-value covariance block.
double calculateLogPrior()
Evaluate the log prior density of the parameters.
Definition SexpatCF.cpp:255
Eigen::Array< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > ExpDistArray
Calculates covariances between the derivatives.
Definition SexpatCF.h:472
bool buildSharedKernel(const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, FieldMatrixd &kernel_out) const
Apply theta to a shared distance to produce the kernel value K(theta)[n, m] = exp(theta(0)) * exp(-0....
void setGeodesicHeatReferencePath(const Coord &reference_path, double covariance_weight)
Definition SexpatCF.cpp:530
void clearDistanceCache()
Invalidate the distance cache.
bool prepareAlphaK(const Coord &x_train, const Eigen::Ref< const Eigen::VectorXd > &alpha_E, const Eigen::Ref< const Eigen::VectorXd > &alpha_G_flat, PreparedAlphaK &prepared) const
Eigen::VectorXd energyDiagonal(const Eigen::MatrixXd &positions) const override
Energy self covariance at each geometry, without an all-pairs matrix.
Definition SexpatCF.cpp:691
Eigen::MatrixXd covarianceBlock(const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions, Eigen::Index left_channel, Eigen::Index right_channel) const override
Covariance between one channel at each set of geometry rows.
Definition SexpatCF.cpp:701
HessianPrecision hessianPrecision() const noexcept
Sexpat(const SexpatCF &primitive)
Definition SexpatCF.cpp:661
Responsible for errors handling.
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
void parallelFor(long count, F &&fn)
parallelFor(count, fn): see TilePool::run.
double lgamma(double x) noexcept
double log(double x) noexcept
double exp(double x) noexcept
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
Eigen::Matrix< Index_t, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixIdx
Definition Macros.h:29
bool sexpat_local_oracle_active
Definition SexpatCF.cpp:35
FieldMatrixd Coord
Definition Macros.h:35
bool usesClassicJointEnergyForcePrior(GPModelProfile profile) noexcept
Definition Structures.h:206
uint32_t Index_t
Definition Macros.h:17
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
STL namespace.
Stores configurations of all atoms in the system.
Definition Structures.h:832
Structure of directional derivatives.
Definition Structures.h:63