Contrib bug fixes: SpecialFunctions, AutoDiff, FFT and the MINPACK ports libeigen/eigen!3315 Co-authored-by: Rasmus Munk Larsen <rmlarsen@gmail.com>
diff --git a/contrib/Eigen/src/AutoDiff/AutoDiffScalar.h b/contrib/Eigen/src/AutoDiff/AutoDiffScalar.h index dc54b10..382edac 100644 --- a/contrib/Eigen/src/AutoDiff/AutoDiffScalar.h +++ b/contrib/Eigen/src/AutoDiff/AutoDiffScalar.h
@@ -520,7 +520,9 @@ Scalar squared_hypot = a.value() * a.value() + b.value() * b.value(); // if (squared_hypot==0) the derivation is undefined and the following results in a NaN: - ret.derivatives() = (a.derivatives() * b.value() - a.value() * b.derivatives()) / squared_hypot; + ret.derivatives() = internal::MakeCoherentCwiseBinaryOp<internal::scalar_difference_op<Scalar>>( + a.derivatives() * b.value(), b.derivatives() * a.value()) / + squared_hypot; return ret; }
diff --git a/contrib/Eigen/src/AutoDiff/CoherentPadOp.h b/contrib/Eigen/src/AutoDiff/CoherentPadOp.h index e97378f..b3d2dfb 100644 --- a/contrib/Eigen/src/AutoDiff/CoherentPadOp.h +++ b/contrib/Eigen/src/AutoDiff/CoherentPadOp.h
@@ -94,11 +94,11 @@ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const { EIGEN_IF_CONSTEXPR (XprType::IsRowMajor) { if (col < m_size.value()) { - return m_argImpl.coeff(1, col); + return m_argImpl.coeff(0, col); } } else { if (row < m_size.value()) { - return m_argImpl.coeff(row, 1); + return m_argImpl.coeff(row, 0); } } return CoeffReturnType(0);
diff --git a/contrib/Eigen/src/FFT/kissfft_impl.h b/contrib/Eigen/src/FFT/kissfft_impl.h index b6643f8..a467e08 100644 --- a/contrib/Eigen/src/FFT/kissfft_impl.h +++ b/contrib/Eigen/src/FFT/kissfft_impl.h
@@ -121,6 +121,8 @@ // recombine the p smaller DFTs switch (p) { + case 1: // nfft == 1: the copy above is the whole transform + break; case 2: bfly2(xout, fstride, m); break;
diff --git a/contrib/Eigen/src/LevenbergMarquardt/LMcovar.h b/contrib/Eigen/src/LevenbergMarquardt/LMcovar.h index cf1b3c4..45fce3b 100644 --- a/contrib/Eigen/src/LevenbergMarquardt/LMcovar.h +++ b/contrib/Eigen/src/LevenbergMarquardt/LMcovar.h
@@ -37,16 +37,17 @@ /* form the inverse of r in the full upper triangle of r. */ l = -1; - for (k = 0; k < n; ++k) - if (abs(r(k, k)) > tolr) { - r(k, k) = 1. / r(k, k); - for (j = 0; j <= k - 1; ++j) { - temp = r(k, k) * r(j, k); - r(j, k) = 0.; - r.col(k).head(j + 1) -= r.col(j).head(j + 1) * temp; - } - l = k; + for (k = 0; k < n; ++k) { + // MINPACK's test: the rank ends at the first negligible pivot, and a NaN pivot propagates. + if (abs(r(k, k)) <= tolr) break; + r(k, k) = 1. / r(k, k); + for (j = 0; j <= k - 1; ++j) { + temp = r(k, k) * r(j, k); + r(j, k) = 0.; + r.col(k).head(j + 1) -= r.col(j).head(j + 1) * temp; } + l = k; + } /* form the full upper triangle of the inverse of (r transpose)*r */ /* in the full upper triangle of r. */
diff --git a/contrib/Eigen/src/LevenbergMarquardt/LMonestep.h b/contrib/Eigen/src/LevenbergMarquardt/LMonestep.h index 821cff3..d67c8e1 100644 --- a/contrib/Eigen/src/LevenbergMarquardt/LMonestep.h +++ b/contrib/Eigen/src/LevenbergMarquardt/LMonestep.h
@@ -30,7 +30,8 @@ eigen_assert(x.size() == n); // check the caller is not cheating us temp = 0.0; - xnorm = 0.0; + // MINPACK keeps xnorm from the last accepted step; x has not moved since, nor has m_diag. + xnorm = m_iter > 1 ? m_diag.cwiseProduct(x).stableNorm() : RealScalar(0); /* calculate the jacobian matrix. */ Index df_ret = m_functor.df(x, m_fjac); if (df_ret < 0) return LevenbergMarquardtSpace::UserAsked;
diff --git a/contrib/Eigen/src/NonLinearOptimization/LevenbergMarquardt.h b/contrib/Eigen/src/NonLinearOptimization/LevenbergMarquardt.h index 08d1252..a2d6866 100644 --- a/contrib/Eigen/src/NonLinearOptimization/LevenbergMarquardt.h +++ b/contrib/Eigen/src/NonLinearOptimization/LevenbergMarquardt.h
@@ -417,7 +417,7 @@ sing = false; for (j = 0; j < n; ++j) { if (fjac(j, j) == 0.) sing = true; - wa2[j] = fjac.col(j).head(j).stableNorm(); + wa2[j] = fjac.col(j).head(j + 1).stableNorm(); } permutation.setIdentity(n); if (sing) {
diff --git a/contrib/Eigen/src/NonLinearOptimization/covar.h b/contrib/Eigen/src/NonLinearOptimization/covar.h index 808893d..b27feaf 100644 --- a/contrib/Eigen/src/NonLinearOptimization/covar.h +++ b/contrib/Eigen/src/NonLinearOptimization/covar.h
@@ -30,16 +30,17 @@ /* form the inverse of r in the full upper triangle of r. */ l = -1; - for (k = 0; k < n; ++k) - if (abs(r(k, k)) > tolr) { - r(k, k) = 1. / r(k, k); - for (j = 0; j <= k - 1; ++j) { - temp = r(k, k) * r(j, k); - r(j, k) = 0.; - r.col(k).head(j + 1) -= r.col(j).head(j + 1) * temp; - } - l = k; + for (k = 0; k < n; ++k) { + // MINPACK's test: the rank ends at the first negligible pivot, and a NaN pivot propagates. + if (abs(r(k, k)) <= tolr) break; + r(k, k) = 1. / r(k, k); + for (j = 0; j <= k - 1; ++j) { + temp = r(k, k) * r(j, k); + r(j, k) = 0.; + r.col(k).head(j + 1) -= r.col(j).head(j + 1) * temp; } + l = k; + } /* form the full upper triangle of the inverse of (r transpose)*r */ /* in the full upper triangle of r. */
diff --git a/contrib/Eigen/src/NonLinearOptimization/dogleg.h b/contrib/Eigen/src/NonLinearOptimization/dogleg.h index ed0c472..3363095 100644 --- a/contrib/Eigen/src/NonLinearOptimization/dogleg.h +++ b/contrib/Eigen/src/NonLinearOptimization/dogleg.h
@@ -37,7 +37,7 @@ for (j = n - 1; j >= 0; --j) { temp = qrfac(j, j); if (temp == 0.) { - temp = epsmch * qrfac.col(j).head(j + 1).maxCoeff(); + temp = epsmch * qrfac.col(j).head(j + 1).cwiseAbs().maxCoeff(); if (temp == 0.) temp = epsmch; } if (j == n - 1)
diff --git a/contrib/Eigen/src/SpecialFunctions/BesselFunctionsImpl.h b/contrib/Eigen/src/SpecialFunctions/BesselFunctionsImpl.h index 05690d3..331211f 100644 --- a/contrib/Eigen/src/SpecialFunctions/BesselFunctionsImpl.h +++ b/contrib/Eigen/src/SpecialFunctions/BesselFunctionsImpl.h
@@ -194,7 +194,9 @@ // so we need to tell it not to. EIGEN_OPTIMIZATION_BARRIER(scaled) #endif - return pmul(half_exp, scaled); + // i0e(inf) = 0 would turn exp(inf) * i0e(inf) into NaN; i0(+-inf) = +inf. + const T inf = pinf<T>(); + return pselect(pcmp_eq(ax, inf), inf, pmul(half_exp, scaled)); } }; @@ -353,7 +355,8 @@ // Reassociating back to (exp(|x|/2) * exp(|x|/2)) * i1e(x) would reintroduce the overflow. EIGEN_OPTIMIZATION_BARRIER(scaled) #endif - return pmul(half_exp, scaled); + // i1(+-inf) = +-inf; the scaled product would be inf * 0 = NaN. + return pselect(pcmp_eq(ax, pinf<T>()), x, pmul(half_exp, scaled)); } }; @@ -1440,7 +1443,7 @@ T z = pmul(x, x); T x_le_two = pmul(psub(z, YO1), internal::ppolevl<T, 4>::run(z, YP)); x_le_two = pmadd(x_le_two, x, pmul(TWOOPI, pmadd(generic_j1<T, float>::run(x), plog(x), pdiv(pset1<T>(-1.0f), x)))); - x_le_two = pselect(pcmp_lt(x, pset1<T>(0.0f)), NEG_MAXNUM, x_le_two); + x_le_two = pselect(pcmp_le(x, pset1<T>(0.0f)), NEG_MAXNUM, x_le_two); T q = pdiv(pset1<T>(1.0), x); T w = prsqrt(x);
diff --git a/contrib/Eigen/src/SpecialFunctions/SpecialFunctionsImpl.h b/contrib/Eigen/src/SpecialFunctions/SpecialFunctionsImpl.h index 22db1be..c8cfb06 100644 --- a/contrib/Eigen/src/SpecialFunctions/SpecialFunctionsImpl.h +++ b/contrib/Eigen/src/SpecialFunctions/SpecialFunctionsImpl.h
@@ -1168,13 +1168,13 @@ const Scalar one = 1; const Scalar nan = NumTraits<Scalar>::quiet_NaN(); - if (x == zero) return zero; - - if ((x < zero) || (a <= zero)) { // domain error + if ((numext::isnan)(a) || (numext::isnan)(x)) { // propagate nans return nan; } - if ((numext::isnan)(a) || (numext::isnan)(x)) { // propagate nans + if (x == zero) return zero; + + if ((x < zero) || (a <= zero)) { // domain error return nan; } @@ -1345,7 +1345,7 @@ EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE bool run(float& a, float& b, float& s, const float x, const float machep) { int i = 0; - while (i < 9) { + while ((i < 9) || (a <= 9.0f)) { i += 1; a += 1.0f; b = numext::pow(a, -x); @@ -1825,6 +1825,7 @@ const float nan = NumTraits<float>::quiet_NaN(); float ans, t; + if ((numext::isnan)(a) || (numext::isnan)(b) || (numext::isnan)(x)) return nan; if (a == 0.0f && b == 0.0f) return nan; if (x < 0.0f || x > 1.0f) return nan; if (a < 0.0f) return nan; @@ -1894,6 +1895,7 @@ double a, b, t, x, xc, w, y; bool reversed_a_b = false; + if ((numext::isnan)(aa) || (numext::isnan)(bb) || (numext::isnan)(xx)) return nan; if (aa == 0.0 && bb == 0.0) return nan; if (xx < 0.0 || xx > 1.0) return nan; if (aa < 0.0) return nan;
diff --git a/contrib/test/NonLinearOptimization.cpp b/contrib/test/NonLinearOptimization.cpp index 0ee6f7b..6e2ea8a 100644 --- a/contrib/test/NonLinearOptimization.cpp +++ b/contrib/test/NonLinearOptimization.cpp
@@ -438,6 +438,38 @@ VERIFY_IS_APPROX(x, x_ref); } +// The first lmstr step scales by the column norms of R, which equal those of the Jacobian (MINPACK). +void testLmstrScaling() { + lmstr_functor functor; + VectorXd x = VectorXd::Ones(3), row(3); + MatrixXd jac(15, 3); + for (int i = 0; i < 15; ++i) { + functor.df(x, row, i + 2); + jac.row(i) = row.transpose(); + } + LevenbergMarquardt<lmstr_functor> lm(functor); + lm.minimizeOptimumStorageInit(x); + lm.minimizeOptimumStorageOneStep(x); + VERIFY_IS_APPROX(lm.diag, VectorXd(jac.colwise().norm().transpose())); +} + +// covar() takes the rank to end at the first pivot below tol * |r(0,0)| (MINPACK) and zeroes the rest; +// a NaN pivot is not negligible, so it reaches the result instead of reading as zero variance. +void testCovarRankDeficient() { + MatrixXd r(3, 3); + r << 2, 1, 1, 0, 1e-20, 1, 0, 0, 3; + VectorXi ipvt(3); + ipvt << 0, 1, 2; + internal::covar(r, ipvt); + MatrixXd expected = MatrixXd::Zero(3, 3); + expected(0, 0) = 0.25; + VERIFY_IS_APPROX(r, expected); + + r << 2, 1, 1, 0, NumTraits<double>::quiet_NaN(), 1, 0, 0, 3; + internal::covar(r, ipvt); + VERIFY(r.hasNaN()); +} + void testLmdif1() { const int n = 3; int info; @@ -1231,8 +1263,19 @@ VERIFY_IS_APPROX(qtf.transpose(), expected.row(0)); } +// dogleg() replaces a zero pivot r(j,j) by epsmch * max_i |r(i,j)| (MINPACK), not by the signed maximum. +void testDoglegZeroPivot() { + MatrixXd r(2, 2); + r << -4, -2, 0, 0; + VectorXd diag = VectorXd::Ones(2), qtb = VectorXd::Ones(2), x(2); + internal::dogleg<double>(r, diag, qtb, 1e300, x); + const double x1 = 1 / (2 * NumTraits<double>::epsilon()); + VERIFY_IS_APPROX(x, Vector2d(-(1 + 2 * x1) / 4, x1)); +} + EIGEN_DECLARE_TEST(NonLinearOptimization) { CALL_SUBTEST /*_2*/ (testR1mpyq()); + CALL_SUBTEST /*_2*/ (testDoglegZeroPivot()); // Tests using the examples provided by (c)minpack CALL_SUBTEST /*_1*/ (testChkder()); @@ -1244,6 +1287,8 @@ CALL_SUBTEST /*_2*/ (testHybrd()); CALL_SUBTEST /*_3*/ (testLmstr1()); CALL_SUBTEST /*_3*/ (testLmstr()); + CALL_SUBTEST /*_3*/ (testLmstrScaling()); + CALL_SUBTEST /*_3*/ (testCovarRankDeficient()); CALL_SUBTEST /*_3*/ (testLmdif1()); CALL_SUBTEST /*_3*/ (testLmdif());
diff --git a/contrib/test/autodiff.cpp b/contrib/test/autodiff.cpp index 2f54c72..3e3c719 100644 --- a/contrib/test/autodiff.cpp +++ b/contrib/test/autodiff.cpp
@@ -367,6 +367,26 @@ return (y1 + y2 + y3).value(); } +// atan2 must pad the empty derivatives of a constant, as the arithmetic operators do. +void test_autodiff_atan2_constant() { + typedef AutoDiffScalar<VectorXd> AD; + const AD x(1.0, 2, 0), c(2.0); + VERIFY_IS_APPROX(atan2(x, c).derivatives(), Vector2d(0.4, 0)); + VERIFY_IS_APPROX(atan2(c, x).derivatives(), Vector2d(-0.4, 0)); +} + +// The zero-padded derivatives of a sum must read column 0 of a non-plain derivative expression. +void test_autodiff_padded_block_derivatives() { + using ColMajorMatrixXd = Matrix<double, Dynamic, Dynamic, ColMajor>; + ColMajorMatrixXd store(3, 2); + store << 1, 10, 2, 20, 3, 30; + AutoDiffScalar<Block<ColMajorMatrixXd, Dynamic, 1, true>> a(1.0, store.col(0)); + AutoDiffScalar<VectorXd> b(2.0); + MatrixXd jac = MatrixXd::Zero(3, 2); + jac.topRows(3).leftCols(1) = (a + b).derivatives(); + VERIFY_IS_EQUAL(jac.col(0), store.col(0)); +} + // LLT stores the 1-norm of its input for rcond(); the sum of AutoDiffScalars is an expression, so // the norm must materialize its column totals before comparing them. void test_autodiff_selfadjoint_l1norm() { @@ -493,6 +513,8 @@ CALL_SUBTEST_5(bug_1261()); CALL_SUBTEST_5(bug_1281()); CALL_SUBTEST_5(test_autodiff_selfadjoint_l1norm()); + CALL_SUBTEST_5(test_autodiff_padded_block_derivatives()); + CALL_SUBTEST_5(test_autodiff_atan2_constant()); CALL_SUBTEST_6(test_autodiff_makegivens<Vector2d>()); CALL_SUBTEST_6(test_autodiff_makegivens<VectorXd>()); CALL_SUBTEST_7(test_autodiff_householder_qr<Vector4d>());
diff --git a/contrib/test/bessel_functions.cpp b/contrib/test/bessel_functions.cpp index 9202973..99701cf 100644 --- a/contrib/test/bessel_functions.cpp +++ b/contrib/test/bessel_functions.cpp
@@ -250,6 +250,25 @@ CALL_SUBTEST(res = bessel_y1(x); verify_component_wise(res, expected);); } + + // y1 has a pole at 0: y1(0) = -inf. + { + typedef typename ArrayType::Scalar Scalar; + const ArrayType zeros = ArrayType::Zero(8); + VERIFY_IS_EQUAL(numext::bessel_y1(Scalar(0)), -NumTraits<Scalar>::infinity()); + VERIFY((bessel_y1(zeros) == -NumTraits<Scalar>::infinity()).all()); + } + + // i0(+-inf) = +inf and i1(+-inf) = +-inf, although i0e and i1e vanish there. + { + typedef typename ArrayType::Scalar Scalar; + const Scalar inf = NumTraits<Scalar>::infinity(); + const ArrayType infs = ArrayType::Constant(8, inf); + VERIFY_IS_EQUAL(numext::bessel_i0(-inf), inf); + VERIFY_IS_EQUAL(numext::bessel_i1(-inf), -inf); + VERIFY((bessel_i0(infs) == inf).all() && (bessel_i0(-infs) == inf).all()); + VERIFY((bessel_i1(infs) == inf).all() && (bessel_i1(-infs) == -inf).all()); + } } // exp(|x|) overflows above |x| ~ 88.7228 (float) / ~709.7827 (double), while i0/i1 stay finite up to
diff --git a/contrib/test/fft_test_shared.h b/contrib/test/fft_test_shared.h index 6f47725..c6a444c 100644 --- a/contrib/test/fft_test_shared.h +++ b/contrib/test/fft_test_shared.h
@@ -624,6 +624,8 @@ CALL_SUBTEST(test_inplace_complex<double>(256)); CALL_SUBTEST(test_fwd_padding<float>(16)); CALL_SUBTEST(test_fwd_padding<double>(16)); + CALL_SUBTEST(test_complex<double>(1)); + CALL_SUBTEST(test_scalar<double>(1)); CALL_SUBTEST(test_complex<float>(32)); CALL_SUBTEST(test_complex<double>(32)); CALL_SUBTEST(test_complex<float>(256));
diff --git a/contrib/test/levenberg_marquardt.cpp b/contrib/test/levenberg_marquardt.cpp index 02e717c..b20d5f1 100644 --- a/contrib/test/levenberg_marquardt.cpp +++ b/contrib/test/levenberg_marquardt.cpp
@@ -334,9 +334,8 @@ misra1d_functor functor; LevenbergMarquardt<misra1d_functor> lm(functor); info = lm.minimize(x); - EIGEN_UNUSED_VARIABLE(info); - // check return value - // VERIFY_IS_EQUAL(info, 1); + // check return value: MINPACK's, which needs xnorm to carry over from the last accepted step + VERIFY_IS_EQUAL(info, LevenbergMarquardtSpace::RelativeErrorAndReductionTooSmall); // VERIFY_IS_EQUAL(lm.nfev(), 9); // VERIFY_IS_EQUAL(lm.njev(), 7); // check norm^2 @@ -889,6 +888,23 @@ VERIFY_IS_APPROX(x[2], 4.5154121844E+02); } +// covar() takes the rank to end at the first pivot below tol * |r(0,0)| (MINPACK) and zeroes the rest; +// a NaN pivot is not negligible, so it reaches the result instead of reading as zero variance. +void testCovarRankDeficient() { + MatrixXd r(3, 3); + r << 2, 1, 1, 0, 1e-20, 1, 0, 0, 3; + VectorXi ipvt(3); + ipvt << 0, 1, 2; + internal::covar(r, ipvt); + MatrixXd expected = MatrixXd::Zero(3, 3); + expected(0, 0) = 0.25; + VERIFY_IS_APPROX(r, expected); + + r << 2, 1, 1, 0, NumTraits<double>::quiet_NaN(), 1, 0, 0, 3; + internal::covar(r, ipvt); + VERIFY(r.hasNaN()); +} + // lmqrsolv() must minimize ||[R; D] z - [qtb; 0]|| and leave the eliminated // factor in the strict lower triangle of s for lmpar2(). Issue #657: the QR is // rank-revealing, so R carries zeros above the diagonal, and the Givens @@ -982,6 +998,7 @@ EIGEN_DECLARE_TEST(levenberg_marquardt) { CALL_SUBTEST(testLmqrsolv()); + CALL_SUBTEST(testCovarRankDeficient()); CALL_SUBTEST(testSparseFunctor()); // Tests using the examples provided by (c)minpack
diff --git a/contrib/test/special_functions.cpp b/contrib/test/special_functions.cpp index 5d4d03c..1cd0b29 100644 --- a/contrib/test/special_functions.cpp +++ b/contrib/test/special_functions.cpp
@@ -561,6 +561,23 @@ VERIFY_IS_EQUAL(numext::erfc(-plusinf), Scalar(2.0)); VERIFY((numext::isnan)(numext::erfc(nan))); + // NaN propagates through the x = 0 shortcut of igamma and its derivatives. + VERIFY((numext::isnan)(numext::igamma(nan, Scalar(0)))); + VERIFY((numext::isnan)(numext::igamma_der_a(nan, Scalar(0)))); + VERIFY((numext::isnan)(numext::gamma_sample_der_alpha(nan, Scalar(0)))); + + // betainc propagates NaN past its a = 0 and b = 0 shortcuts. + VERIFY((numext::isnan)(numext::betainc(Scalar(0), Scalar(0.5), nan))); + VERIFY((numext::isnan)(numext::betainc(Scalar(0.5), Scalar(0), nan))); + VERIFY((numext::isnan)(numext::betainc(nan, Scalar(0.5), Scalar(0)))); + + // A negative q sums until n + q > 9. zeta(2, -20.5) = pi^2/2 + sum_{j=0}^{20} (j + 1/2)^-2. + { + double ref = EIGEN_PI * EIGEN_PI / 2; + for (int j = 0; j <= 20; ++j) ref += 1 / ((j + 0.5) * (j + 0.5)); + VERIFY_IS_APPROX(numext::zeta(Scalar(2), Scalar(-20.5)), Scalar(ref)); + } + if (sizeof(Scalar) >= 8) { VERIFY_IS_EQUAL(numext::erf(Scalar(1e200)), Scalar(1.0)); VERIFY_IS_EQUAL(numext::erf(Scalar(-1e200)), Scalar(-1.0));