Loading...
Searching...
No Matches
CalibrationBounds.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4#pragma once
5
6#include <Eigen/Core>
7#include <algorithm>
8#include <cmath>
9#include <limits>
10
11namespace gpr::detail {
12
16inline Eigen::VectorXd triangularPrecisionLowerBounds(
17 const Eigen::Ref<const Eigen::MatrixXd>& lower)
18{
19 const Eigen::Index order = lower.rows();
20 if (order == 0 || lower.cols() != order || !lower.allFinite() ||
21 (lower.diagonal().array() <= 0.0).any())
22 return {};
23 // Outward rounding requires gradual underflow. A process that flushes
24 // subnormal arithmetic uses the full precision calculation instead.
25 volatile double normal_min = std::numeric_limits<double>::min();
26 volatile double half_min = normal_min * 0.5;
27 if (!(half_min > 0.0)) return {};
28 const double infinity = std::numeric_limits<double>::infinity();
29 const auto down = [&](double value) {
30 return std::nextafter(value, -infinity);
31 };
32 const auto up = [&](double value) {
33 return std::nextafter(value, infinity);
34 };
35 Eigen::VectorXd bounds = Eigen::VectorXd::Zero(order);
36 Eigen::VectorXd lo(order), hi(order);
37 for (Eigen::Index column = 0; column < order; ++column) {
38 for (Eigen::Index row = column; row < order; ++row) {
39 double sum_lo = 0.0, sum_hi = 0.0;
40 for (Eigen::Index k = column; k < row; ++k) {
41 const double coefficient = lower(row, k);
42 const double product_lo =
43 coefficient * (coefficient >= 0.0 ? lo(k) : hi(k));
44 const double product_hi =
45 coefficient * (coefficient >= 0.0 ? hi(k) : lo(k));
46 sum_lo = down(sum_lo + down(product_lo));
47 sum_hi = up(sum_hi + up(product_hi));
48 }
49 const double rhs = row == column ? 1.0 : 0.0;
50 lo(row) = down(down(rhs - sum_hi) / lower(row, row));
51 hi(row) = up(up(rhs - sum_lo) / lower(row, row));
52 if (!std::isfinite(lo(row)) || !std::isfinite(hi(row))) return {};
53 const double minimum = lo(row) > 0.0 ? lo(row)
54 : hi(row) < 0.0 ? -hi(row)
55 : 0.0;
56 const double square = std::max(0.0, down(minimum * minimum));
57 bounds(column) = std::max(0.0, down(bounds(column) + square));
58 }
59 }
60 return bounds.allFinite() ? bounds : Eigen::VectorXd{};
61}
62
65inline bool precisionBoundsCertifyUnitCalibration(const Eigen::VectorXd& alpha,
66 const Eigen::VectorXd& bounds)
67{
68 if (alpha.size() < 2 || alpha.size() != bounds.size() ||
69 !alpha.allFinite() || !bounds.allFinite())
70 return false;
71 const double limit = std::sqrt(0.4549364231195727) *
72 (1.0 - 128.0 * std::numeric_limits<double>::epsilon());
73 Eigen::Index below = 0;
74 for (Eigen::Index i = 0; i < alpha.size(); ++i) {
75 if (bounds(i) > 0.0 &&
76 std::abs(alpha(i)) / std::sqrt(bounds(i)) < limit)
77 ++below;
78 }
79 return below > alpha.size() / 2;
80}
81
82} // namespace gpr::detail