66 static_assert(Degree >= 1 && Degree <= 11 && Degree % 2 == 1);
67 static_assert(MomentCount >= 1 && MomentCount <= 8);
68 static_assert(Degree + MomentCount <= 16);
69 using Moments = std::array<double, MomentCount>;
70 static constexpr bool rational =
71 C == Curve::GoldenRatio || C == Curve::SymmetricKnee || C == Curve::AsymmetricKnee;
72 static constexpr int count = Degree + 1;
73 static constexpr double referenceSlope = NativeSlope ? clipperSmallSignalSlope<C, double>() : 1.;
74 using Poly = std::array<double, count>;
75 std::array<Poly, count> matrix_{}, bernsteinMatrix_{};
79 double reconstructionBound_ = 1;
80 double arithmeticBound_ = 1;
81 std::array<double, 11> levels_{};
83 static double value(
const Poly &p,
double t)
86 for (
int i = Degree - 1; i >= 0; --i)
90 static double slope(
const Poly &p,
double t)
92 double v = Degree * p[Degree];
93 for (
int i = Degree - 1; i >= 1; --i)
97 static void add(Moments &a,
const Moments &b)
99 for (
int i = 0; i < MomentCount; ++i)
107 double at = 0, weight = 0;
110 Moments quadrature(
const Poly &p,
double a,
double b,
const Gauss<N> &q,
bool fixed =
false,
111 double fixedValue = 0, Pole pole = {})
const
114 for (
int i = 0; i < N; ++i)
116 const double t = a + (b - a) * q.
nodes[i], x = value(p, t);
117 const double reference = SubtractLinear ? referenceSlope * x : 0.;
118 double f = fixed ? fixedValue - reference : clipperShape<C>(x, ceiling_) - reference;
119 if (pole.weight != 0)
120 f -= pole.weight / (t - pole.at);
121 double v = (b - a) * q.
weights[i] * f;
122 for (
int j = 0; j < MomentCount; ++j)
130 std::array<Moments, 2> tanhQuadrature(
const Poly &p,
double a,
double b)
const
135 static constexpr std::array<double, 8> nodes{
136 .99145537112081263921, .94910791234275852453, .86486442335976907279,
137 .74153118559939443986, .58608723546769113029, .40584515137739716691,
138 .20778495500789846760, 0.};
139 static constexpr std::array<double, 8> fineWeights{
140 .02293532201052922496, .06309209262997855329, .10479001032225018384,
141 .14065325971552591875, .16900472663926790283, .19035057806478540991,
142 .20443294007529889241, .20948214108472782801};
143 static constexpr std::array<double, 4> coarseWeights{
144 .12948496616886969327, .27970539148927666790,
145 .38183005050511894495, .41795918367346938776};
146 std::array<Moments, 2> result{};
147 const double half = (b - a) * .5, center = a + half;
148 const auto accumulate = [&](
double t,
double fineWeight,
double coarseWeight)
150 const double x = value(p, t);
151 const double reference = SubtractLinear ? referenceSlope * x : 0.;
152 double v = half * (clipperShape<C>(x, ceiling_) - reference);
153 for (
int j = 0; j < MomentCount; ++j)
155 result[1][j] += fineWeight * v;
156 if (coarseWeight != 0.) result[0][j] += coarseWeight * v;
160 accumulate(center, fineWeights[7], coarseWeights[3]);
161 for (
int i = 0; i < 7; ++i)
163 const double coarseWeight = i % 2 ? coarseWeights[i / 2] : 0.;
164 accumulate(center - half * nodes[i], fineWeights[i], coarseWeight);
165 accumulate(center + half * nodes[i], fineWeights[i], coarseWeight);
169 Moments adaptive(
const Poly &p,
double a,
double b,
int depth = 0, Pole pole = {})
const
171 const auto estimates = [&] {
172 if constexpr (C == Curve::Tanh)
return tanhQuadrature(p, a, b);
173 else return std::array<Moments, 2>{quadrature(p, a, b, linearQuadrature_,
false, 0, pole),
174 quadrature(p, a, b, nonlinearQuadrature_,
false, 0, pole)};
176 const auto &coarse = estimates[0], &fine = estimates[1];
178 1 + std::abs(value(p, a)) + std::abs(value(p, b)) + std::abs(value(p, (a + b) / 2));
179 const double tolerance = (b - a) * 1e-13 * scale;
181 for (
int i = 0; i < MomentCount; ++i)
182 error = std::max(error, std::abs(fine[i] - coarse[i]));
183 if (error <= tolerance)
186 return {std::numeric_limits<double>::quiet_NaN()};
187 auto out = adaptive(p, a, (a + b) / 2, depth + 1, pole);
188 add(out, adaptive(p, (a + b) / 2, b, depth + 1, pole));
191 Moments linearMoments(
const Poly &p,
double a,
double b)
const
195 if constexpr (MomentCount != 4)
197 if (a == 0 && b == 1)
199 static constexpr auto weights = [] {
200 std::array<Poly, MomentCount> result{};
201 for (
int j = 0; j < MomentCount; ++j)
202 for (
int k = 0; k < count; ++k)
203 result[j][k] = 1. / (j + k + 1);
207 for (
int j = 0; j < MomentCount; ++j)
208 for (
int k = 0; k < count; ++k)
209 out[j] += p[k] * weights[j][k];
213 return quadrature(p, a, b, linearQuadrature_);
225 Moments rationalSegment(
const Poly &p,
double a,
double b,
double x)
const
227 const auto limits = clipperLinearLimits<C>(ceiling_);
228 const double sign = x >= 0 ? 1. : -1.;
229 const double knee = x >= 0 ? limits[1] : -limits[0];
230 const double level = 2 * knee - ceiling_, range = ceiling_ - knee, width = b - a;
231 const double ra = sign * slope(p, a), rb = -sign * slope(p, b);
232 const double da = ra > 0 ? (sign * value(p, a) - level) / ra : std::numeric_limits<double>::infinity();
233 const double db = rb > 0 ? (sign * value(p, b) - level) / rb : std::numeric_limits<double>::infinity();
234 const bool fromA = da <= db;
235 const double d = fromA ? da : db;
236 if (!(d > 0) || !(d < .25 * width))
237 return adaptive(p, a, b);
238 const double end = fromA ? a : b, outward = fromA ? -1. : 1.;
239 double root = end + outward * d, derivative = 0;
240 bool converged =
false;
241 for (
int it = 0; it < 16 && !converged; ++it)
243 const double f = sign * value(p, root) - level;
244 derivative = sign * slope(p, root);
245 if (!(derivative != 0) || !std::isfinite(f))
247 const double step = f / derivative;
249 converged = std::abs(step) <= 4 * std::numeric_limits<double>::epsilon() * (1 + std::abs(root));
251 derivative = sign * slope(p, root);
252 if (!converged || !(outward * (root - end) > 0) || !(outward * (root - end) < width) ||
253 !(std::abs(derivative) > 0) || !std::isfinite(derivative))
254 return adaptive(p, a, b);
255 const Pole pole{root, -sign * range * range / derivative};
256 auto out = adaptive(p, a, b, 0, pole);
259 const double logarithm = std::log((b - root) / (a - root));
260 double rootPower = 1;
261 std::array<double, MomentCount> powerSums{};
262 double pa = a, pb = b;
263 for (
int m = 0; m < MomentCount; ++m)
265 powerSums[m] = (pb - pa) / (m + 1);
269 for (
int j = 0; j < MomentCount; ++j)
272 for (
int m = j - 1; m >= 0; --m)
277 out[j] += pole.weight * (
polynomial + rootPower * logarithm);
282 Moments segment(
const Poly &p,
double a,
double b)
const
284 const double x = value(p, (a + b) / 2);
285 if constexpr (C == Curve::Hard)
287 if (std::abs(x) <= ceiling_)
289 if constexpr (SubtractLinear)
return {};
290 else return linearMoments(p, a, b);
292 return quadrature(p, a, b, linearQuadrature_,
true, std::copysign(ceiling_, x));
294 else if constexpr (C == Curve::Sine)
296 if (std::abs(x) >= ceiling_ * halfPi<double>)
297 return quadrature(p, a, b, linearQuadrature_,
true, clipperShape<C>(x, ceiling_));
299 else if constexpr (rational)
301 const auto limits = clipperLinearLimits<C>(ceiling_);
302 if (x >= limits[0] && x <= limits[1])
304 if constexpr (SubtractLinear)
return {};
305 else return linearMoments(p, a, b);
308 else if constexpr (C == Curve::Tanh)
310 if (std::abs(x) >= 24 * ceiling_)
311 return quadrature(p, a, b, linearQuadrature_,
true, std::copysign(ceiling_, x));
313 if constexpr (rational)
314 return rationalSegment(p, a, b, x);
315 else if constexpr (C == Curve::Tanh)
316 return adaptive(p, a, b);
318 return quadrature(p, a, b, nonlinearQuadrature_);
320 double root(
const Poly &p,
double a,
double b,
double target)
const
322 double fa = value(p, a) - target, fb = value(p, b) - target;
327 if ((fa > 0) == (fb > 0))
328 return std::numeric_limits<double>::quiet_NaN();
329 double x = a + (b - a) * (-fa) / (fb - fa);
330 for (
int i = 0; i < 64; ++i)
332 const double f = value(p, x) - target;
333 if (std::abs(f) <= 2e-15 || b - a < 2e-14)
335 if ((f > 0) == (fa > 0))
345 const double d = slope(p, x);
346 const double candidate = d != 0 ? x - f / d : (a + b) / 2;
347 x = candidate > a && candidate < b ? candidate : (a + b) / 2;
349 return std::numeric_limits<double>::quiet_NaN();
351 Moments recurse(
const Poly &p,
const Poly &bernstein,
double a,
double b,
int depth)
const
353 const auto bounds = std::minmax_element(bernstein.begin(), bernstein.end());
354 const double low = *bounds.first, high = *bounds.second;
355 if constexpr (C == Curve::Hard)
357 if (low >= -ceiling_ && high <= ceiling_)
359 if constexpr (SubtractLinear)
return {};
360 else return linearMoments(p, a, b);
363 if constexpr (rational)
365 const auto limits = clipperLinearLimits<C>(ceiling_);
366 if (low >= limits[0] && high <= limits[1])
368 if constexpr (SubtractLinear)
return {};
369 else return linearMoments(p, a, b);
372 bool crosses =
false;
373 for (
int i = 0; i < levelCount_; ++i)
374 crosses = crosses || (low < levels_[i] && levels_[i] < high);
376 return segment(p, a, b);
379 if (high - low < 1e-13)
380 return quadrature(p, a, b, nonlinearQuadrature_);
381 bool increasing =
true, decreasing =
true;
382 for (
int i = 1; i < count; ++i)
384 increasing = increasing && bernstein[i] >= bernstein[i - 1];
385 decreasing = decreasing && bernstein[i] <= bernstein[i - 1];
387 if (increasing || decreasing)
389 std::array<double, 13> edges{};
392 const double va = value(p, a), vb = value(p, b);
393 for (
int i = 0; i < levelCount_; ++i)
394 if (levels_[i] > std::min(va, vb) && levels_[i] < std::max(va, vb))
396 const double crossing = root(p, a, b, levels_[i]);
397 if (!std::isfinite(crossing))
398 return {std::numeric_limits<double>::quiet_NaN()};
399 edges[n++] = crossing;
404 for (
int i = 1; i < n; ++i)
406 const double edge = edges[i];
408 for (; j > 0 && edges[j - 1] > edge; --j)
409 edges[j] = edges[j - 1];
413 for (
int i = 0; i + 1 < n; ++i)
414 add(out, segment(p, edges[i], edges[i + 1]));
418 return {std::numeric_limits<double>::quiet_NaN()};
419 Poly work = bernstein, left{}, right{};
421 right[Degree] = work[Degree];
422 for (
int level = 1; level < count; ++level)
424 for (
int i = 0; i < count - level; ++i)
425 work[i] = (work[i] + work[i + 1]) * .5;
426 left[level] = work[0];
427 right[Degree - level] = work[Degree - level];
429 auto out = recurse(p, left, a, (a + b) / 2, depth + 1);
430 add(out, recurse(p, right, (a + b) / 2, b, depth + 1));
437 static_assert(MomentCount == 4);
438 constexpr std::array<Moments, 4> kernels{
439 {{1, -3, 3, -1}, {4, 0, -6, 3}, {1, 3, 3, -3}, {0, 0, 0, 1}}};
440 std::vector<double> result(Degree + 4);
441 for (
int i = 0; i < count; ++i)
444 for (
int j = 0; j < 4; ++j)
445 for (
int k = 0; k < count; ++k)
446 moments[j] += matrix_[i][k] / (k + j + 1);
447 for (
int lag = 0; lag < 4; ++lag)
448 for (
int j = 0; j < 4; ++j)
449 result[Degree - i + lag] += moments[j] * kernels[lag][j] / 6;
453 explicit Interval(
double ceiling) : ceiling_(ceiling)
455 constexpr int begin = -(Degree - 1) / 2;
456 for (
int node = 0; node < count; ++node)
458 std::array<long double, count> p{};
461 const int x = begin + node;
462 for (
int other = 0; other < count; ++other)
465 const int y = begin + other;
466 std::array<long double, count> next{};
467 for (
int j = 0; j <= order; ++j)
469 next[j] -= p[j] * y / (x - y);
470 next[j + 1] += p[j] / (x - y);
475 for (
int j = 0; j < count; ++j)
476 matrix_[node][j] =
static_cast<double>(p[j]);
478 for (
int i = 0; i < count; ++i)
479 for (
int j = 0; j <= i; ++j)
480 bernsteinMatrix_[i][j] =
choose(i, j) /
choose(Degree, j);
483 for (
int row = 0; row < count; ++row)
485 long double norm = 0, arithmeticNorm = 0;
486 for (
int node = 0; node < count; ++node)
488 long double coefficient = 0;
489 for (
int column = 0; column <= row; ++column)
491 coefficient +=
static_cast<long double>(bernsteinMatrix_[row][column]) *
492 matrix_[node][column];
494 std::abs(
static_cast<long double>(bernsteinMatrix_[row][column]) *
495 matrix_[node][column]);
497 norm += std::abs(coefficient);
499 reconstructionBound_ = std::max(reconstructionBound_,
static_cast<double>(norm));
500 arithmeticBound_ = std::max(arithmeticBound_,
static_cast<double>(arithmeticNorm));
507 if constexpr (C == Curve::Tanh)
509 levels_ = {-24 * ceiling, -12 * ceiling, -6 * ceiling, -3 * ceiling, -ceiling, 0,
510 ceiling, 3 * ceiling, 6 * ceiling, 12 * ceiling, 24 * ceiling};
513 else if constexpr (rational)
515 const auto limits = clipperLinearLimits<C>(ceiling);
516 levels_[0] = limits[0];
517 levels_[1] = limits[1];
522 const double limit = C == Curve::Sine ? ceiling * halfPi<double> : ceiling;
532 return reconstructionBound_;
540 [[nodiscard]] Moments
polynomial(
const Poly &power)
const noexcept
543 for (
double coefficient : power)
544 if (!std::isfinite(coefficient))
545 return {std::numeric_limits<double>::quiet_NaN()};
546 if (std::all_of(power.begin(), power.end(), [](
double value) { return value == 0; }))
548 for (
int i = 0; i < count; ++i)
549 for (
int j = 0; j <= i; ++j)
550 bernstein[i] += power[j] * bernsteinMatrix_[i][j];
551 return recurse(power, bernstein, 0, 1, 0);
553 Moments
operator()(
const std::array<double, count> &samples)
const noexcept
555 if (std::all_of(samples.begin(), samples.end(), [](
double value) { return value == 0; }))
557 if constexpr (SubtractLinear && (C == Curve::Hard || rational))
559 double low = samples[0], high = samples[0];
560 for (
double sample : samples)
562 if (!std::isfinite(sample))
563 return {std::numeric_limits<double>::quiet_NaN()};
564 low = std::min(low, sample);
565 high = std::max(high, sample);
567 const double center = 0.5 * low + 0.5 * high;
568 const double radius = (0.5 * high - 0.5 * low) * reconstructionBound_;
571 const double margin = 128 * std::numeric_limits<double>::epsilon() * arithmeticBound_ *
572 (std::abs(center) + radius) +
573 256 * std::numeric_limits<double>::denorm_min();
574 const auto limits = [&] {
575 if constexpr (rational)
576 return clipperLinearLimits<C>(ceiling_);
578 return std::array<double, 2>{-ceiling_, ceiling_};
580 if (center - radius - margin >= limits[0] && center + radius + margin <= limits[1])
583 Poly power{}, bernstein{};
584 for (
int i = 0; i < count; ++i)
585 for (
int j = 0; j < count; ++j)
586 power[j] += samples[i] * matrix_[i][j];
587 for (
int i = 0; i < count; ++i)
588 for (
int j = 0; j <= i; ++j)
589 bernstein[i] += power[j] * bernsteinMatrix_[i][j];
590 return recurse(power, bernstein, 0, 1, 0);