Eigen  5.0.1-dev+master
 
Loading...
Searching...
No Matches
StableNorm.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
5//
6// This Source Code Form is subject to the terms of the Mozilla
7// Public License v. 2.0. If a copy of the MPL was not distributed
8// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9// SPDX-License-Identifier: MPL-2.0
10
11#ifndef EIGEN_STABLENORM_H
12#define EIGEN_STABLENORM_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19namespace internal {
20
21template <typename Accumulator, bool = std::is_floating_point<Accumulator>::value>
22struct stable_norm_unscaled_predicate {
23 static inline bool run(const Accumulator&, const Accumulator&) { return false; }
24};
25
26template <typename Accumulator>
27struct stable_norm_unscaled_predicate<Accumulator, true> {
28 static inline bool run(const Accumulator& maxCoeff, const Accumulator& invScale) {
29 using std::sqrt;
30 // A block has at most 8192 real components. These bounds keep the error
31 // from flushed component squares below one epsilon.
32 static const Accumulator kSqrtMin =
33 sqrt((numext::numeric_limits<Accumulator>::min)() * (Accumulator(16384) / NumTraits<Accumulator>::epsilon()));
34 static const Accumulator kSqrtMax = sqrt(NumTraits<Accumulator>::highest() / Accumulator(16384));
35 // A normal invScale avoids fast-math flushing invScale^2.
36 static const Accumulator kSqrtNormalMin = sqrt((numext::numeric_limits<Accumulator>::min)());
37 return maxCoeff >= kSqrtMin && maxCoeff <= kSqrtMax && invScale >= kSqrtNormalMin;
38 }
39};
40
41template <typename ExpressionType, typename Accumulator>
42inline Accumulator stable_norm_squared_norm(const ExpressionType& block, const Accumulator& invScale,
43 const Accumulator& maxCoeff) {
44 if (stable_norm_unscaled_predicate<Accumulator>::run(maxCoeff, invScale)) {
45 return block.realView().template cast<Accumulator>().squaredNorm() * numext::abs2(invScale);
46 }
47 return (block.realView().template cast<Accumulator>() * invScale).squaredNorm();
48}
49
50template <typename ExpressionType, typename Accumulator>
51inline void stable_norm_kernel(const ExpressionType& block, Accumulator& ssq, Accumulator& scale,
52 Accumulator& invScale) {
53 // Component-wise maxima give the required scale without complex hypot calls.
54 Accumulator maxCoeff = block.realView().template cast<Accumulator>().cwiseAbs().template maxCoeff<PropagateNaN>();
55
56 if (maxCoeff > scale) {
57 if (maxCoeff > NumTraits<Accumulator>::highest()) // we got an INF
58 {
59 invScale = Accumulator(1);
60 scale = maxCoeff;
61 } else {
62 const auto factors = safe_scaling<Accumulator>::compute_ceiling_factors_with_normal_reciprocal(maxCoeff);
63 if (scale > Accumulator(0)) ssq = ssq * numext::abs2(scale * factors.invScale);
64 scale = factors.scale;
65 invScale = factors.invScale;
66 }
67 } else if (maxCoeff != maxCoeff) // we got a NaN
68 {
69 scale = maxCoeff;
70 }
71
72 // TODO: skip sub-vector when maxCoeff << current scale.
73 if (scale > Accumulator(0)) // if scale==0, then block is 0
74 ssq += stable_norm_squared_norm(block, invScale, maxCoeff);
75}
76
77template <typename VectorType, typename Accumulator>
78void stable_norm_impl_inner_step(const VectorType& vec, Accumulator& ssq, Accumulator& scale, Accumulator& invScale) {
79 const Index blockSize = 4096;
80
81 Index n = vec.size();
82 Index blockEnd = numext::round_down(n, blockSize);
83 for (Index i = 0; i < blockEnd; i += blockSize) {
84 internal::stable_norm_kernel(vec.template segment<blockSize>(i), ssq, scale, invScale);
85 }
86 if (n > blockEnd) {
87 internal::stable_norm_kernel(vec.tail(n - blockEnd), ssq, scale, invScale);
88 }
89}
90
91template <typename VectorType, typename Accumulator,
92 bool = bool(traits<VectorType>::Flags & DirectAccessBit) &&
93 (int(inner_stride_at_compile_time<VectorType>::value) != 1)>
94struct stable_norm_vector_dispatch {
95 static inline void run(const VectorType& vec, Accumulator& ssq, Accumulator& scale, Accumulator& invScale) {
96 stable_norm_impl_inner_step(vec, ssq, scale, invScale);
97 }
98};
99
100template <typename VectorType, typename Accumulator>
101struct stable_norm_vector_dispatch<VectorType, Accumulator, true> {
102 static inline void run(const VectorType& vec, Accumulator& ssq, Accumulator& scale, Accumulator& invScale) {
103 if (vec.innerStride() == 1) {
104 using Scalar = typename traits<VectorType>::Scalar;
105 using PlainVector = Matrix<Scalar, VectorType::SizeAtCompileTime, 1, 0, VectorType::MaxSizeAtCompileTime, 1>;
106 using ContiguousMap = Map<const PlainVector, evaluator<VectorType>::Alignment>;
107 const ContiguousMap contiguous(vec.data(), vec.size());
108 stable_norm_impl_inner_step(contiguous, ssq, scale, invScale);
109 return;
110 }
111 stable_norm_impl_inner_step(vec, ssq, scale, invScale);
112 }
113};
114
115template <typename VectorType, typename Accumulator>
116inline void stable_norm_impl_inner_dispatch(const VectorType& vec, Accumulator& ssq, Accumulator& scale,
117 Accumulator& invScale) {
118 stable_norm_vector_dispatch<VectorType, Accumulator>::run(vec, ssq, scale, invScale);
119}
120
121template <typename MatrixType, typename Accumulator>
122inline void stable_norm_impl_outer_steps(const MatrixType& mat, Accumulator& ssq, Accumulator& scale,
123 Accumulator& invScale) {
124 for (Index j = 0; j < mat.outerSize(); ++j) {
125 stable_norm_impl_inner_dispatch(mat.innerVector(j), ssq, scale, invScale);
126 }
127}
128
129template <typename MatrixType, typename Accumulator, bool = bool(traits<MatrixType>::Flags & DirectAccessBit)>
130struct stable_norm_matrix_dispatch {
131 static inline void run(const MatrixType& mat, Accumulator& ssq, Accumulator& scale, Accumulator& invScale) {
132 stable_norm_impl_outer_steps(mat, ssq, scale, invScale);
133 }
134};
135
136template <typename MatrixType, typename Accumulator>
137struct stable_norm_matrix_dispatch<MatrixType, Accumulator, true> {
138 static inline void run(const MatrixType& mat, Accumulator& ssq, Accumulator& scale, Accumulator& invScale) {
139 if (mat.innerStride() == 1 && (mat.outerSize() == 1 || mat.outerStride() == mat.innerSize())) {
140 using Scalar = typename traits<MatrixType>::Scalar;
141 using PlainVector = Matrix<Scalar, MatrixType::SizeAtCompileTime, 1, 0, MatrixType::MaxSizeAtCompileTime, 1>;
142 using ContiguousMap = Map<const PlainVector, evaluator<MatrixType>::Alignment>;
143 const ContiguousMap contiguous(mat.data(), mat.size());
144 stable_norm_impl_inner_step(contiguous, ssq, scale, invScale);
145 return;
146 }
147 stable_norm_impl_outer_steps(mat, ssq, scale, invScale);
148 }
149};
150
151// Avoid instantiating block reductions for statically empty inputs, including in C++14.
152template <typename Derived, std::enable_if_t<Derived::MaxSizeAtCompileTime == 0, int> = 0>
153typename Derived::RealScalar stable_norm_impl(const Derived&) {
154 return typename Derived::RealScalar(0);
155}
156
157// floor(sqrt(sum x_i^2)), saturated at the highest value of the type. The sum is accumulated in double: squaring in
158// the integer type, as norm() does, overflows where the norm is representable. For a sum s < 2^53 (exact in double) the
159// root is corrected to the exact floor, since sqrt(n^2 - 1) rounds up to n; beyond it, it is a truncated estimate. A
160// single coefficient gives |x|, exact where x is not representable in double.
161template <typename Derived>
162inline typename Derived::RealScalar integer_l2_norm(const Derived& vec, std::true_type /* is_integral */) {
163 using RealScalar = typename Derived::RealScalar;
164 decltype(auto) components = vec.realView();
165 if (components.size() == 1) {
166 const RealScalar x = components.coeff(0, 0);
167 return (NumTraits<RealScalar>::IsSigned && x == NumTraits<RealScalar>::lowest()) ? NumTraits<RealScalar>::highest()
168 : numext::abs(x);
169 }
170 const double sum = components.template cast<double>().squaredNorm();
171 const double root = numext::floor(numext::sqrt(sum));
172 if (root >= static_cast<double>(NumTraits<RealScalar>::highest())) return NumTraits<RealScalar>::highest();
173 unsigned long long result = static_cast<unsigned long long>(root);
174 if (sum < 9007199254740992.0) { // 2^53
175 const unsigned long long squares = static_cast<unsigned long long>(sum);
176 while (result * result > squares) --result;
177 while ((result + 1) * (result + 1) <= squares) ++result;
178 }
179 return static_cast<RealScalar>(result);
180}
181
182// Other integer types: norm().
183template <typename Derived>
184inline typename Derived::RealScalar integer_l2_norm(const Derived& vec, std::false_type /* is_integral */) {
185 return vec.norm();
186}
187
188template <typename Derived>
189inline typename Derived::RealScalar integer_l2_norm(const Derived& vec) {
190 return integer_l2_norm(vec, bool_constant<std::is_integral<typename Derived::RealScalar>::value>());
192
193// The scaling below guards floating-point accumulation against over- and underflow, and is meaningless for integers.
194template <
195 typename Derived,
196 std::enable_if_t<NumTraits<typename Derived::Scalar>::IsInteger && Derived::MaxSizeAtCompileTime != 0, int> = 0>
197typename Derived::RealScalar stable_norm_impl(const Derived& vec) {
198 return integer_l2_norm(vec);
199}
200
201template <typename VectorType,
202 std::enable_if_t<VectorType::IsVectorAtCompileTime && VectorType::MaxSizeAtCompileTime != 0 &&
203 !NumTraits<typename VectorType::Scalar>::IsInteger,
204 int> = 0>
205typename VectorType::RealScalar stable_norm_impl(const VectorType& vec) {
206 Index n = vec.size();
207 if (EIGEN_PREDICT_FALSE(n == 1)) return numext::abs(vec.coeff(0));
208
209 using RealScalar = typename VectorType::RealScalar;
210 using Accumulator = typename stable_norm_accumulator<RealScalar>::type;
211 Accumulator scale(0);
212 Accumulator invScale(1);
213 Accumulator ssq(0); // sum of squares
214
215 stable_norm_vector_dispatch<VectorType, Accumulator>::run(vec, ssq, scale, invScale);
216
217 return RealScalar(scale * numext::sqrt(ssq));
218}
219
220template <typename MatrixType,
221 std::enable_if_t<!MatrixType::IsVectorAtCompileTime && MatrixType::MaxSizeAtCompileTime != 0 &&
222 !NumTraits<typename MatrixType::Scalar>::IsInteger,
223 int> = 0>
224typename MatrixType::RealScalar stable_norm_impl(const MatrixType& mat) {
225 using RealScalar = typename MatrixType::RealScalar;
226 using Accumulator = typename stable_norm_accumulator<RealScalar>::type;
227 Accumulator scale(0);
228 Accumulator invScale(1);
229 Accumulator ssq(0); // sum of squares
230
231 stable_norm_matrix_dispatch<MatrixType, Accumulator>::run(mat, ssq, scale, invScale);
232 return RealScalar(scale * numext::sqrt(ssq));
233}
234
235inline int stable_norm_floor_div2(int value) { return value / 2 - ((value < 0 && value % 2 != 0) ? 1 : 0); }
236
237inline int stable_norm_ceil_div2(int value) { return value / 2 + ((value > 0 && value % 2 != 0) ? 1 : 0); }
238
239template <typename Accumulator>
240inline void blue_norm_accumulate_component(const Accumulator& ax, const Accumulator& tsml, const Accumulator& tbig,
241 const Accumulator& ssml, const Accumulator& sbig, bool& notBig,
242 Accumulator& asml, Accumulator& amed, Accumulator& abig) {
243 if (ax > tbig) {
244 abig += numext::abs2(ax * sbig);
245 notBig = false;
246 } else if (ax < tsml) {
247 if (notBig) asml += numext::abs2(ax * ssml);
248 } else {
249 amed += numext::abs2(ax);
250 }
251}
252
253template <typename Scalar, typename Accumulator, bool = NumTraits<Scalar>::IsComplex>
254struct blue_norm_accumulate_scalar {
255 static inline void run(const Scalar& value, const Accumulator& tsml, const Accumulator& tbig, const Accumulator& ssml,
256 const Accumulator& sbig, bool& notBig, Accumulator& asml, Accumulator& amed,
257 Accumulator& abig) {
258 const Accumulator ax = numext::abs(Accumulator(value));
259 blue_norm_accumulate_component(ax, tsml, tbig, ssml, sbig, notBig, asml, amed, abig);
260 }
261};
262
263template <typename Scalar, typename Accumulator>
264struct blue_norm_accumulate_scalar<Scalar, Accumulator, true> {
265 static inline void run(const Scalar& value, const Accumulator& tsml, const Accumulator& tbig, const Accumulator& ssml,
266 const Accumulator& sbig, bool& notBig, Accumulator& asml, Accumulator& amed,
267 Accumulator& abig) {
268 const Accumulator real = numext::abs(Accumulator(numext::real(value)));
269 const Accumulator imag = numext::abs(Accumulator(numext::imag(value)));
270 blue_norm_accumulate_component(real, tsml, tbig, ssml, sbig, notBig, asml, amed, abig);
271 blue_norm_accumulate_component(imag, tsml, tbig, ssml, sbig, notBig, asml, amed, abig);
272 }
273};
274
275template <typename Derived, std::enable_if_t<NumTraits<typename traits<Derived>::Scalar>::IsInteger, int> = 0>
276inline typename NumTraits<typename traits<Derived>::Scalar>::Real blueNorm_impl(const EigenBase<Derived>& vec) {
277 return integer_l2_norm(vec.derived());
278}
279
280template <typename Derived, std::enable_if_t<!NumTraits<typename traits<Derived>::Scalar>::IsInteger, int> = 0>
281inline typename NumTraits<typename traits<Derived>::Scalar>::Real blueNorm_impl(const EigenBase<Derived>& _vec) {
282 using RealScalar = typename Derived::RealScalar;
283 using Accumulator = typename stable_norm_accumulator<RealScalar>::type;
284 using Scalar = typename traits<Derived>::Scalar;
285 using std::pow;
286
287 const Derived& vec(_vec.derived());
288 if (vec.size() == 0) return RealScalar(0);
289
290 // Blue, ACM TOMS 4(1), 1978, https://doi.org/10.1145/355769.355771.
291 // The small-value multiplier includes Anderson's denormal correction from
292 // Algorithm 978, ACM TOMS 44(1), 2017, https://doi.org/10.1145/3061665.
293 // These thresholds and the three-accumulator merge follow Reference BLAS
294 // xNRM2 (LAPACK 3.12.1), expressed independently for Eigen scalar types.
295 static const int ibeta = std::numeric_limits<Accumulator>::radix;
296 static const int it = NumTraits<Accumulator>::digits();
297 static const int iemin = NumTraits<Accumulator>::min_exponent();
298 static const int iemax = NumTraits<Accumulator>::max_exponent();
299 static const Accumulator tsml = Accumulator(pow(Accumulator(ibeta), Accumulator(stable_norm_ceil_div2(iemin - 1))));
300 static const Accumulator tbig =
301 Accumulator(pow(Accumulator(ibeta), Accumulator(stable_norm_floor_div2(iemax - it + 1))));
302 static const Accumulator ssml =
303 Accumulator(pow(Accumulator(ibeta), Accumulator(-stable_norm_floor_div2(iemin - it))));
304 static const Accumulator sbig =
305 Accumulator(pow(Accumulator(ibeta), Accumulator(-stable_norm_ceil_div2(iemax + it - 1))));
306
307 bool notBig = true;
308 Accumulator asml(0);
309 Accumulator amed(0);
310 Accumulator abig(0);
311
312 for (Index j = 0; j < vec.outerSize(); ++j) {
313 for (typename Derived::InnerIterator iter(vec, j); iter; ++iter) {
314 blue_norm_accumulate_scalar<Scalar, Accumulator>::run(iter.value(), tsml, tbig, ssml, sbig, notBig, asml, amed,
315 abig);
316 }
317 }
318
319 Accumulator scale(1);
320 Accumulator sumsq(0);
321 if (abig > Accumulator(0)) {
322 if (amed > Accumulator(0) || amed > NumTraits<Accumulator>::highest() || amed != amed) abig += (amed * sbig) * sbig;
323 scale = Accumulator(1) / sbig;
324 sumsq = abig;
325 } else if (asml > Accumulator(0)) {
326 if (amed > Accumulator(0) || amed > NumTraits<Accumulator>::highest() || amed != amed) {
327 amed = numext::sqrt(amed);
328 asml = numext::sqrt(asml) / ssml;
329 // Spell this as in xNRM2 rather than with min/max: when amed is NaN,
330 // it must become ymax so that the final result remains NaN.
331 const bool smallIsLarger = asml > amed;
332 const Accumulator ymin = smallIsLarger ? amed : asml;
333 const Accumulator ymax = smallIsLarger ? asml : amed;
334 sumsq = numext::abs2(ymax) * (Accumulator(1) + numext::abs2(ymin / ymax));
335 } else {
336 scale = Accumulator(1) / ssml;
337 sumsq = asml;
338 }
339 } else {
340 sumsq = amed;
341 }
342 return RealScalar(scale * numext::sqrt(sumsq));
343}
344
345template <typename Derived>
346inline typename Derived::RealScalar hypot_norm_impl(const Derived& vec, std::true_type /* IsInteger */) {
347 return integer_l2_norm(vec);
348}
349
350template <typename Derived>
351inline typename Derived::RealScalar hypot_norm_impl(const Derived& vec, std::false_type /* IsInteger */) {
352 using RealScalar = typename Derived::RealScalar;
353 using Accumulator = typename stable_norm_accumulator<RealScalar>::type;
354 // Component reduction avoids rounded complex magnitudes and permits promoted accumulation.
355 return RealScalar(redux_with_identity(vec.realView().template cast<Accumulator>().cwiseAbs(),
356 scalar_hypot_op<Accumulator>(), Accumulator(0)));
357}
358
359} // end namespace internal
360
376template <typename Derived>
378 using Nested = typename internal::nested_eval<Derived, 2>::type;
379 Nested nested(derived());
380 return internal::stable_norm_impl(nested);
381}
382
395template <typename Derived>
397 return internal::blueNorm_impl(*this);
398}
399
407template <typename Derived>
409 return internal::hypot_norm_impl(derived(), internal::bool_constant<NumTraits<Scalar>::IsInteger>());
410}
411
412} // end namespace Eigen
413
414#endif // EIGEN_STABLENORM_H
RealScalar blueNorm() const
Definition StableNorm.h:396
RealScalar hypotNorm() const
Definition StableNorm.h:408
RealScalar stableNorm() const
Definition StableNorm.h:377
constexpr unsigned int DirectAccessBit
Definition Constants.h:160
Holds information about the various numeric (i.e. scalar) types allowed by Eigen.
Definition NumTraits.h:267