KASKADE 7 development version
Loading...
Searching...
No Matches
bddcZeroQuantization.hh
Go to the documentation of this file.
1/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2/* This file is part of the library KASKADE 7 */
3/* https://www.zib.de/research/projects/kaskade7-finite-element-toolbox */
4/* Copyright (C) 2026 Zuse Institute Berlin */
5/* KASKADE 7 is distributed under the terms of the ZIB Academic License. */
6/* see $KASKADE/academic.txt */
7/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
8
9#ifndef KASKADE_BDDC_ZERO_QUANTIZATION_HH
10#define KASKADE_BDDC_ZERO_QUANTIZATION_HH
11
12#include <algorithm>
13#include <cmath>
14#include <limits>
15#include <stdexcept>
16
17namespace Kaskade::BDDC
18{
35 {
36 static double scaleForRange(double maxAbs, double maxCode)
37 {
38 int exponent = 0;
39 double const fraction = std::frexp(maxCode+1,&exponent);
40 if (maxCode<3 || maxCode>4294967295.0 || fraction!=0.5 ||
41 !std::isfinite(maxAbs) || maxAbs<0)
42 throw std::invalid_argument("Zero-preserving restriction requires 2..32 bits and finite data");
43 if (maxAbs==0) return 1;
44 long double const requested = (static_cast<long double>((maxCode+1)/2)-1)/maxAbs;
45 float wire = static_cast<float>(std::min(requested,
46 static_cast<long double>(std::numeric_limits<float>::max())));
47 if (static_cast<long double>(wire)>requested)
48 wire = std::nextafter(wire,0.0f);
49 if (!(wire>0) || !std::isfinite(wire))
50 throw std::runtime_error("Zero-preserving restriction scale is outside float32 metadata range");
51 return wire;
52 }
53
54 static double encode(double value, double maxCode, double scale)
55 {
56 if (!std::isfinite(value) || !(scale>0) || !std::isfinite(scale))
57 throw std::runtime_error("Nonfinite zero-preserving restriction input or scale");
58 long double const zero = (maxCode+1)/2;
59 long double const limit = zero-1;
60 // Round the signed value BEFORE adding Z, preserving sign symmetry at ties.
61 long double const signedCode = std::round(static_cast<long double>(value)*scale);
62 return static_cast<double>(zero+std::clamp(signedCode,-limit,limit));
63 }
64
65 static double decode(double code, double maxCode, double scale)
66 {
67 if (!std::isfinite(code) || !(scale>0) || !std::isfinite(scale))
68 throw std::runtime_error("Invalid zero-preserving restriction payload");
69 return static_cast<double>((static_cast<long double>(code)-(maxCode+1)/2)/scale);
70 }
71 };
72}
73#endif
Experimental symmetric transfer quantization with exact zero.
static double decode(double code, double maxCode, double scale)
static double encode(double value, double maxCode, double scale)
static double scaleForRange(double maxAbs, double maxCode)