eigen/unsupported/Eigen/src/NonLinearOptimization/covar.h

70 lines
1.8 KiB
C
Raw Normal View History

namespace Eigen {
namespace internal {
2010-01-26 20:20:24 +08:00
template <typename Scalar>
void covar(
2009-08-24 23:47:35 +08:00
Matrix< Scalar, Dynamic, Dynamic > &r,
const VectorXi &ipvt,
Scalar tol = sqrt(NumTraits<Scalar>::epsilon()) )
{
typedef DenseIndex Index;
/* Local variables */
Index i, j, k, l, ii, jj;
bool sing;
2009-08-24 23:47:35 +08:00
Scalar temp;
/* Function Body */
const Index n = r.cols();
const Scalar tolr = tol * abs(r(0,0));
2009-08-24 23:47:35 +08:00
Matrix< Scalar, Dynamic, 1 > wa(n);
assert(ipvt.size()==n);
2010-01-28 11:19:39 +08:00
/* form the inverse of r in the full upper triangle of r. */
2009-08-24 23:47:35 +08:00
l = -1;
for (k = 0; k < n; ++k)
if (abs(r(k,k)) > tolr) {
2009-08-24 23:47:35 +08:00
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.;
2010-01-28 11:19:39 +08:00
r.col(k).head(j+1) -= r.col(j).head(j+1) * temp;
2009-08-24 23:47:35 +08:00
}
2009-08-24 22:49:38 +08:00
l = k;
}
2010-01-28 11:19:39 +08:00
/* form the full upper triangle of the inverse of (r transpose)*r */
/* in the full upper triangle of r. */
2009-08-24 23:47:35 +08:00
for (k = 0; k <= l; ++k) {
2010-01-28 11:19:39 +08:00
for (j = 0; j <= k-1; ++j)
r.col(j).head(j+1) += r.col(k).head(j+1) * r(j,k);
r.col(k).head(k+1) *= r(k,k);
2009-08-24 23:47:35 +08:00
}
2010-01-28 11:19:39 +08:00
/* form the full lower triangle of the covariance matrix */
/* in the strict lower triangle of r and in wa. */
2009-08-24 23:47:35 +08:00
for (j = 0; j < n; ++j) {
2009-08-24 23:49:37 +08:00
jj = ipvt[j];
2009-08-24 22:49:38 +08:00
sing = j > l;
2009-08-24 23:47:35 +08:00
for (i = 0; i <= j; ++i) {
2009-08-24 22:49:38 +08:00
if (sing)
2009-08-24 23:47:35 +08:00
r(i,j) = 0.;
2009-08-24 23:49:37 +08:00
ii = ipvt[i];
2009-08-24 22:49:38 +08:00
if (ii > jj)
2009-08-24 23:47:35 +08:00
r(ii,jj) = r(i,j);
2009-08-24 22:49:38 +08:00
if (ii < jj)
2009-08-24 23:47:35 +08:00
r(jj,ii) = r(i,j);
2009-08-24 22:49:38 +08:00
}
2009-08-24 23:47:35 +08:00
wa[jj] = r(j,j);
}
2010-01-28 11:19:39 +08:00
/* symmetrize the covariance matrix in r. */
r.topLeftCorner(n,n).template triangularView<StrictlyUpper>() = r.topLeftCorner(n,n).transpose();
2010-01-28 11:19:39 +08:00
r.diagonal() = wa;
2009-08-24 22:49:38 +08:00
}
} // end namespace internal
} // end namespace Eigen