Eigen-Contrib  5.0.1-dev+master
 
Loading...
Searching...
No Matches
PolynomialSolver.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
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_POLYNOMIAL_SOLVER_H
12#define EIGEN_POLYNOMIAL_SOLVER_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
32template <typename Scalar_, int Deg_>
33class PolynomialSolverBase {
34 public:
35 EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(Scalar_, Deg_ == Dynamic ? Dynamic : Deg_)
36
37 using Scalar = Scalar_;
38 using RealScalar = typename NumTraits<Scalar>::Real;
39 using RootType = internal::make_complex_t<Scalar>;
40 using RootsType = Matrix<RootType, Deg_, 1>;
41
42 using Index = DenseIndex;
43
44 protected:
45 template <typename OtherPolynomial>
46 inline void setPolynomial(const OtherPolynomial& poly) {
47 m_roots.resize(poly.size() - 1);
48 }
49
50 public:
51 template <typename OtherPolynomial>
52 inline PolynomialSolverBase(const OtherPolynomial& poly) {
53 setPolynomial(poly());
54 }
55
56 inline PolynomialSolverBase() {}
57
58 public:
60 inline const RootsType& roots() const { return m_roots; }
61
62 public:
73 template <typename Stl_back_insertion_sequence>
74 inline void realRoots(Stl_back_insertion_sequence& bi_seq,
75 const RealScalar& absImaginaryThreshold = NumTraits<Scalar>::dummy_precision()) const {
76 using std::abs;
77 bi_seq.clear();
78 for (Index i = 0; i < m_roots.size(); ++i) {
79 if (abs(m_roots[i].imag()) < absImaginaryThreshold) {
80 bi_seq.push_back(m_roots[i].real());
81 }
82 }
83 }
84
85 protected:
86 template <typename Predicate>
87 inline const RootType& selectComplexRoot_withRespectToNorm(Predicate& pred) const {
88 Index res = 0;
89 RealScalar norm2 = numext::abs2(m_roots[0]);
90 for (Index i = 1; i < m_roots.size(); ++i) {
91 const RealScalar currNorm2 = numext::abs2(m_roots[i]);
92 if (pred(currNorm2, norm2)) {
93 res = i;
94 norm2 = currNorm2;
95 }
96 }
97 return m_roots[res];
98 }
99
100 public:
104 inline const RootType& greatestRoot() const {
105 std::greater<RealScalar> greater;
106 return selectComplexRoot_withRespectToNorm(greater);
107 }
108
112 inline const RootType& smallestRoot() const {
113 std::less<RealScalar> less;
114 return selectComplexRoot_withRespectToNorm(less);
115 }
116
117 protected:
118 template <typename Predicate>
119 inline const RealScalar& selectRealRoot_withRespectToAbsRealPart(
120 Predicate& pred, bool& hasArealRoot,
121 const RealScalar& absImaginaryThreshold = NumTraits<Scalar>::dummy_precision()) const {
122 using std::abs;
123 hasArealRoot = false;
124 Index res = 0;
125 RealScalar val(0);
126
127 for (Index i = 0; i < m_roots.size(); ++i) {
128 if (abs(m_roots[i].imag()) <= absImaginaryThreshold) {
129 if (!hasArealRoot) {
130 hasArealRoot = true;
131 res = i;
132 val = abs(m_roots[i].real());
133 } else {
134 const RealScalar curr = abs(m_roots[i].real());
135 if (pred(curr, val)) {
136 val = curr;
137 res = i;
138 }
139 }
140 } else if (!hasArealRoot) {
141 if (abs(m_roots[i].imag()) < abs(m_roots[res].imag())) {
142 res = i;
143 }
144 }
145 }
146 return numext::real_ref(m_roots[res]);
147 }
148
149 template <typename Predicate>
150 inline const RealScalar& selectRealRoot_withRespectToRealPart(
151 Predicate& pred, bool& hasArealRoot,
152 const RealScalar& absImaginaryThreshold = NumTraits<Scalar>::dummy_precision()) const {
153 using std::abs;
154 hasArealRoot = false;
155 Index res = 0;
156 RealScalar val(0);
157
158 for (Index i = 0; i < m_roots.size(); ++i) {
159 if (abs(m_roots[i].imag()) <= absImaginaryThreshold) {
160 if (!hasArealRoot) {
161 hasArealRoot = true;
162 res = i;
163 val = m_roots[i].real();
164 } else {
165 const RealScalar curr = m_roots[i].real();
166 if (pred(curr, val)) {
167 val = curr;
168 res = i;
169 }
170 }
171 } else {
172 if (abs(m_roots[i].imag()) < abs(m_roots[res].imag())) {
173 res = i;
174 }
175 }
176 }
177 return numext::real_ref(m_roots[res]);
178 }
179
180 public:
195 inline const RealScalar& absGreatestRealRoot(
196 bool& hasArealRoot, const RealScalar& absImaginaryThreshold = NumTraits<Scalar>::dummy_precision()) const {
197 std::greater<RealScalar> greater;
198 return selectRealRoot_withRespectToAbsRealPart(greater, hasArealRoot, absImaginaryThreshold);
199 }
200
215 inline const RealScalar& absSmallestRealRoot(
216 bool& hasArealRoot, const RealScalar& absImaginaryThreshold = NumTraits<Scalar>::dummy_precision()) const {
217 std::less<RealScalar> less;
218 return selectRealRoot_withRespectToAbsRealPart(less, hasArealRoot, absImaginaryThreshold);
219 }
220
235 inline const RealScalar& greatestRealRoot(
236 bool& hasArealRoot, const RealScalar& absImaginaryThreshold = NumTraits<Scalar>::dummy_precision()) const {
237 std::greater<RealScalar> greater;
238 return selectRealRoot_withRespectToRealPart(greater, hasArealRoot, absImaginaryThreshold);
239 }
240
255 inline const RealScalar& smallestRealRoot(
256 bool& hasArealRoot, const RealScalar& absImaginaryThreshold = NumTraits<Scalar>::dummy_precision()) const {
257 std::less<RealScalar> less;
258 return selectRealRoot_withRespectToRealPart(less, hasArealRoot, absImaginaryThreshold);
259 }
260
261 protected:
262 RootsType m_roots;
263};
264
265#define EIGEN_POLYNOMIAL_SOLVER_BASE_INHERITED_TYPES(BASE) \
266 using Scalar = typename BASE::Scalar; \
267 using RealScalar = typename BASE::RealScalar; \
268 using RootType = typename BASE::RootType; \
269 using RootsType = typename BASE::RootsType;
270
304template <typename Scalar_, int Deg_>
305class PolynomialSolver : public PolynomialSolverBase<Scalar_, Deg_> {
306 public:
307 EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(Scalar_, Deg_ == Dynamic ? Dynamic : Deg_)
308
309 using PS_Base = PolynomialSolverBase<Scalar_, Deg_>;
310 EIGEN_POLYNOMIAL_SOLVER_BASE_INHERITED_TYPES(PS_Base)
311
312 using CompanionMatrixType = Matrix<Scalar, Deg_, Deg_>;
313 using EigenSolverType = std::conditional_t<NumTraits<Scalar>::IsComplex, ComplexEigenSolver<CompanionMatrixType>,
315 using ComplexScalar = internal::make_complex_t<Scalar_>;
316
317 public:
320 template <typename OtherPolynomial>
321 void compute(const OtherPolynomial& poly, bool refine = false) {
322 eigen_assert(Scalar(0) != poly[poly.size() - 1]);
323 eigen_assert(poly.size() > 1);
324 if (poly.size() > 2) {
325 internal::companion<Scalar, Deg_> companion(poly);
326 companion.balance();
327 m_eigenSolver.compute(companion.denseMatrix());
328 if (m_eigenSolver.info() != Eigen::Success) {
329 // A companion entry a_k / a_n that overflows, or a non-finite coefficient: one NaN root per degree.
330 m_roots.setConstant(poly.size() - 1,
332 return;
333 }
334 m_roots = m_eigenSolver.eigenvalues();
335 // Uniform coefficient scaling must not overflow or underflow the refinement's Horner recurrences.
336 const RealScalar scale = poly.realView().cwiseAbs().maxCoeff();
337 const auto scaledPoly = (poly / scale).eval();
338 if (refine) refineRoots(scaledPoly);
339 cleanUpRoots(scaledPoly);
340 } else if (poly.size() == 2) {
341 m_roots.resize(1);
342 m_roots[0] = -poly[0] / poly[1];
343 }
344 }
345
346 public:
347 template <typename OtherPolynomial>
348 inline PolynomialSolver(const OtherPolynomial& poly, bool refine = false) {
349 compute(poly, refine);
350 }
351
352 inline PolynomialSolver() {}
353
354 protected:
355 // Evaluates p(z) and p'(z) by Horner's rule. With withBound, returns Higham's running bound on the rounding error
356 // of the value (Higham 2002, Algorithm 5.1), otherwise zero: the moduli it needs cost more than the recurrence.
357 // The real bound is u (2 mu - |p(z)|), u = eps / 2; a complex product rounds by at most 2 sqrt(2) u |z| |y| and a
358 // complex sum by u |y|, so the complex bound is sqrt(2) eps (2 mu - |p(z)|).
359 template <typename OtherPolynomial>
360 static RealScalar evaluate(const OtherPolynomial& poly, const RootType& z, RootType& value, RootType& derivative,
361 bool withBound) {
362 const Index degree = poly.size() - 1;
363 value = RootType(poly[degree]);
364 derivative = RootType(0);
365 if (!withBound) {
366 for (Index k = degree - 1; k >= 0; --k) {
367 derivative = derivative * z + value;
368 value = value * z + RootType(poly[k]);
369 }
370 return RealScalar(0);
371 }
372 const RealScalar absz = numext::abs(z);
373 RealScalar mu = numext::abs(value) / RealScalar(2);
374 for (Index k = degree - 1; k >= 0; --k) {
375 derivative = derivative * z + value;
376 value = value * z + RootType(poly[k]);
377 mu = mu * absz + numext::abs(value);
378 }
379 const RealScalar errorScale = numext::sqrt(RealScalar(2)) * NumTraits<RealScalar>::epsilon();
380 return (RealScalar(2) * errorScale) * mu - errorScale * numext::abs(value);
381 }
382
391 template <typename OtherPolynomial>
392 void refineRoots(const OtherPolynomial& poly) {
393 const Index n = m_roots.size();
394 const RealScalar eps = NumTraits<RealScalar>::epsilon();
395 // Convergence is not guaranteed for clustered roots; retain the eigenvalue estimates as a fallback.
396 const int maxSweeps = NumTraits<RealScalar>::digits();
397 EIGEN_IF_CONSTEXPR (!NumTraits<Scalar>::IsComplex) {
398 for (Index i = 0; i < n; ++i) {
399 // Real iterates cannot reach a nonreal root; perturb by +/- i eps |z|.
400 if (numext::imag(m_roots[i]) == RealScalar(0)) {
401 const RealScalar perturbation = eps * numext::abs(m_roots[i]);
402 m_roots[i] += RootType(0, i % 2 == 0 ? perturbation : -perturbation);
403 }
404 }
405 }
406 // Cauchy's bound on the moduli of the roots: |z| <= 1 + max_k |a_k / a_n|.
407 const RealScalar rootBound = (RealScalar(1) + (poly.head(n).cwiseAbs() / numext::abs(poly[n])).maxCoeff()) *
408 (RealScalar(1) + RealScalar(4) * eps); // margin for the rounding of the sum
411 RootType value, derivative;
412 for (int sweep = 0; sweep < maxSweeps; ++sweep) {
413 bool moving = false;
414 for (Index i = 0; i < n; ++i) {
415 if (!active[i]) continue;
416 const RootType z = m_roots[i];
417 // The eigenvalues can pass the rounding test with a backward error of ~10 eps, while one step from them
418 // lands near eps, so the test applies from the second sweep on.
419 const bool testResidual = sweep > 0;
420 const RealScalar bound = evaluate(poly, z, value, derivative, testResidual);
421 if ((testResidual && !(numext::abs(value) > bound)) || !(numext::isfinite)(bound) ||
422 derivative == RootType(0)) {
423 active[i] = false;
424 continue;
425 }
426 const RootType newton = value / derivative;
427 if (!(numext::abs(newton) > eps * numext::abs(z))) {
428 active[i] = false;
429 continue;
430 }
431 // The repulsion sum has no term for a coincident estimate (the zero eigenvalues of a polynomial with a tiny
432 // cluster of roots), so the step would no longer separate the iterates: the denominator can vanish or the
433 // iterate can land on another root. Such an estimate keeps its eigenvalue, as does a pole of the correction.
434 RootType repulsion(0);
435 bool coincident = false;
436 for (Index j = 0; j < n; ++j) {
437 const RootType gap = z - m_roots[j];
438 if (j == i) continue;
439 if (gap == RootType(0)) {
440 coincident = true;
441 break;
442 }
443 repulsion += RootType(1) / gap;
444 }
445 const RootType denominator = RootType(1) - newton * repulsion;
446 if (coincident || denominator == RootType(0)) {
447 active[i] = false;
448 continue;
449 }
450 const RootType refined = z - RootType(newton / denominator);
451 if ((numext::isfinite)(numext::abs(refined)) && !(numext::abs(refined) > rootBound)) {
452 m_roots[i] = refined;
453 stepped[i] = true;
454 moving = true;
455 } else {
456 active[i] = false;
457 }
458 }
459 if (!moving) break;
460 }
461 // Keep improvements, but never return an estimate whose residual is larger than that of its eigenvalue.
462 for (Index i = 0; i < n; ++i) {
463 if (!stepped[i]) {
464 m_roots[i] = m_eigenSolver.eigenvalues()[i]; // drops the synthetic perturbation
465 continue;
466 }
467 RootType initialValue;
468 evaluate(poly, m_roots[i], value, derivative, false);
469 evaluate(poly, m_eigenSolver.eigenvalues()[i], initialValue, derivative, false);
470 if (!(numext::abs(value) <= numext::abs(initialValue))) m_roots[i] = m_eigenSolver.eigenvalues()[i];
471 }
472 }
473
478 template <typename OtherPolynomial>
479 void cleanUpRoots(const OtherPolynomial& poly) {
480 const Index n = m_roots.size();
481 constexpr bool realPolynomial = !NumTraits<Scalar>::IsComplex;
483 EIGEN_IF_CONSTEXPR (realPolynomial) {
484 for (Index i = 0; i < n; ++i) {
485 if (!(numext::imag(m_roots[i]) > RealScalar(0))) continue;
486 Index partner = n;
487 RealScalar distance = numext::imag(m_roots[i]);
488 for (Index j = 0; j < n; ++j) {
489 if (paired[j] || !(numext::imag(m_roots[j]) < RealScalar(0))) continue;
490 const RealScalar d = numext::abs(m_roots[j] - numext::conj(m_roots[i]));
491 if (d < distance) {
492 distance = d;
493 partner = j;
494 }
495 }
496 if (partner < n) {
497 paired[i] = paired[partner] = true;
498 const RootType mean = (m_roots[i] + numext::conj(m_roots[partner])) / RealScalar(2);
499 m_roots[i] = mean;
500 m_roots[partner] = numext::conj(mean);
501 }
502 }
503 }
504 RootType value, derivative;
505 for (Index i = 0; i < n; ++i) {
506 if (numext::imag(m_roots[i]) == RealScalar(0)) continue;
507 const RootType realPart(numext::real(m_roots[i]));
508 if (realPolynomial && !paired[i]) {
509 m_roots[i] = realPart;
510 continue;
511 }
512 // A small residual at realPart can belong to a different root.
513 if (!(numext::abs(numext::imag(m_roots[i])) <=
514 numext::sqrt(NumTraits<RealScalar>::epsilon()) * numext::abs(realPart)))
515 continue;
516 const RealScalar bound = evaluate(poly, realPart, value, derivative, true);
517 if ((numext::isfinite)(bound) && numext::abs(value) <= bound) m_roots[i] = realPart;
518 }
519 }
520
521 using PS_Base::m_roots;
522 EigenSolverType m_eigenSolver;
523};
524
525template <typename Scalar_>
526class PolynomialSolver<Scalar_, 1> : public PolynomialSolverBase<Scalar_, 1> {
527 public:
528 using PS_Base = PolynomialSolverBase<Scalar_, 1>;
529 EIGEN_POLYNOMIAL_SOLVER_BASE_INHERITED_TYPES(PS_Base)
530
531 public:
533 template <typename OtherPolynomial>
534 void compute(const OtherPolynomial& poly, bool /*refine*/ = false) {
535 eigen_assert(poly.size() == 2);
536 eigen_assert(Scalar(0) != poly[1]);
537 m_roots[0] = -poly[0] / poly[1];
538 }
539
540 public:
541 template <typename OtherPolynomial>
542 inline PolynomialSolver(const OtherPolynomial& poly, bool refine = false) {
543 compute(poly, refine);
544 }
545
546 inline PolynomialSolver() {}
547
548 protected:
549 using PS_Base::m_roots;
550};
551
552} // end namespace Eigen
553
554#endif // EIGEN_POLYNOMIAL_SOLVER_H
constexpr void resize(Index rows, Index cols)
const RealScalar & smallestRealRoot(bool &hasArealRoot, const RealScalar &absImaginaryThreshold=NumTraits< Scalar >::dummy_precision()) const
Definition PolynomialSolver.h:255
const RealScalar & absGreatestRealRoot(bool &hasArealRoot, const RealScalar &absImaginaryThreshold=NumTraits< Scalar >::dummy_precision()) const
Definition PolynomialSolver.h:195
const RealScalar & absSmallestRealRoot(bool &hasArealRoot, const RealScalar &absImaginaryThreshold=NumTraits< Scalar >::dummy_precision()) const
Definition PolynomialSolver.h:215
void realRoots(Stl_back_insertion_sequence &bi_seq, const RealScalar &absImaginaryThreshold=NumTraits< Scalar >::dummy_precision()) const
Definition PolynomialSolver.h:74
const RootType & greatestRoot() const
Definition PolynomialSolver.h:104
const RealScalar & greatestRealRoot(bool &hasArealRoot, const RealScalar &absImaginaryThreshold=NumTraits< Scalar >::dummy_precision()) const
Definition PolynomialSolver.h:235
const RootType & smallestRoot() const
Definition PolynomialSolver.h:112
const RootsType & roots() const
Definition PolynomialSolver.h:60
A polynomial solver.
Definition PolynomialSolver.h:305
void refineRoots(const OtherPolynomial &poly)
Definition PolynomialSolver.h:392
void compute(const OtherPolynomial &poly, bool refine=false)
Definition PolynomialSolver.h:321
void cleanUpRoots(const OtherPolynomial &poly)
Definition PolynomialSolver.h:479
Namespace containing all symbols from the Eigen library.