TriangularSolver.h 9.43 KB
Newer Older
LM's avatar
LM committed
1 2 3 4 5
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
Don Gagne's avatar
Don Gagne committed
6 7 8
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
LM's avatar
LM committed
9 10 11 12

#ifndef EIGEN_SPARSETRIANGULARSOLVER_H
#define EIGEN_SPARSETRIANGULARSOLVER_H

Don Gagne's avatar
Don Gagne committed
13 14
namespace Eigen { 

LM's avatar
LM committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
namespace internal {

template<typename Lhs, typename Rhs, int Mode,
  int UpLo = (Mode & Lower)
           ? Lower
           : (Mode & Upper)
           ? Upper
           : -1,
  int StorageOrder = int(traits<Lhs>::Flags) & RowMajorBit>
struct sparse_solve_triangular_selector;

// forward substitution, row-major
template<typename Lhs, typename Rhs, int Mode>
struct sparse_solve_triangular_selector<Lhs,Rhs,Mode,Lower,RowMajor>
{
  typedef typename Rhs::Scalar Scalar;
31 32
  typedef evaluator<Lhs> LhsEval;
  typedef typename evaluator<Lhs>::InnerIterator LhsIterator;
LM's avatar
LM committed
33 34
  static void run(const Lhs& lhs, Rhs& other)
  {
35 36
    LhsEval lhsEval(lhs);
    for(Index col=0 ; col<other.cols() ; ++col)
LM's avatar
LM committed
37
    {
38
      for(Index i=0; i<lhs.rows(); ++i)
LM's avatar
LM committed
39 40
      {
        Scalar tmp = other.coeff(i,col);
Don Gagne's avatar
Don Gagne committed
41
        Scalar lastVal(0);
42 43
        Index lastIndex = 0;
        for(LhsIterator it(lhsEval, i); it; ++it)
LM's avatar
LM committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
        {
          lastVal = it.value();
          lastIndex = it.index();
          if(lastIndex==i)
            break;
          tmp -= lastVal * other.coeff(lastIndex,col);
        }
        if (Mode & UnitDiag)
          other.coeffRef(i,col) = tmp;
        else
        {
          eigen_assert(lastIndex==i);
          other.coeffRef(i,col) = tmp/lastVal;
        }
      }
    }
  }
};

// backward substitution, row-major
template<typename Lhs, typename Rhs, int Mode>
struct sparse_solve_triangular_selector<Lhs,Rhs,Mode,Upper,RowMajor>
{
  typedef typename Rhs::Scalar Scalar;
68 69
  typedef evaluator<Lhs> LhsEval;
  typedef typename evaluator<Lhs>::InnerIterator LhsIterator;
LM's avatar
LM committed
70 71
  static void run(const Lhs& lhs, Rhs& other)
  {
72 73
    LhsEval lhsEval(lhs);
    for(Index col=0 ; col<other.cols() ; ++col)
LM's avatar
LM committed
74
    {
75
      for(Index i=lhs.rows()-1 ; i>=0 ; --i)
LM's avatar
LM committed
76 77
      {
        Scalar tmp = other.coeff(i,col);
78
        Scalar l_ii(0);
79
        LhsIterator it(lhsEval, i);
Don Gagne's avatar
Don Gagne committed
80 81 82 83 84 85 86 87 88
        while(it && it.index()<i)
          ++it;
        if(!(Mode & UnitDiag))
        {
          eigen_assert(it && it.index()==i);
          l_ii = it.value();
          ++it;
        }
        else if (it && it.index() == i)
LM's avatar
LM committed
89 90 91 92 93 94
          ++it;
        for(; it; ++it)
        {
          tmp -= it.value() * other.coeff(it.index(),col);
        }

95 96
        if (Mode & UnitDiag)  other.coeffRef(i,col) = tmp;
        else                  other.coeffRef(i,col) = tmp/l_ii;
LM's avatar
LM committed
97 98 99 100 101 102 103 104 105 106
      }
    }
  }
};

// forward substitution, col-major
template<typename Lhs, typename Rhs, int Mode>
struct sparse_solve_triangular_selector<Lhs,Rhs,Mode,Lower,ColMajor>
{
  typedef typename Rhs::Scalar Scalar;
107 108
  typedef evaluator<Lhs> LhsEval;
  typedef typename evaluator<Lhs>::InnerIterator LhsIterator;
LM's avatar
LM committed
109 110
  static void run(const Lhs& lhs, Rhs& other)
  {
111 112
    LhsEval lhsEval(lhs);
    for(Index col=0 ; col<other.cols() ; ++col)
LM's avatar
LM committed
113
    {
114
      for(Index i=0; i<lhs.cols(); ++i)
LM's avatar
LM committed
115 116 117 118
      {
        Scalar& tmp = other.coeffRef(i,col);
        if (tmp!=Scalar(0)) // optimization when other is actually sparse
        {
119
          LhsIterator it(lhsEval, i);
Don Gagne's avatar
Don Gagne committed
120 121
          while(it && it.index()<i)
            ++it;
LM's avatar
LM committed
122 123
          if(!(Mode & UnitDiag))
          {
Don Gagne's avatar
Don Gagne committed
124
            eigen_assert(it && it.index()==i);
LM's avatar
LM committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
            tmp /= it.value();
          }
          if (it && it.index()==i)
            ++it;
          for(; it; ++it)
            other.coeffRef(it.index(), col) -= tmp * it.value();
        }
      }
    }
  }
};

// backward substitution, col-major
template<typename Lhs, typename Rhs, int Mode>
struct sparse_solve_triangular_selector<Lhs,Rhs,Mode,Upper,ColMajor>
{
  typedef typename Rhs::Scalar Scalar;
142 143
  typedef evaluator<Lhs> LhsEval;
  typedef typename evaluator<Lhs>::InnerIterator LhsIterator;
LM's avatar
LM committed
144 145
  static void run(const Lhs& lhs, Rhs& other)
  {
146 147
    LhsEval lhsEval(lhs);
    for(Index col=0 ; col<other.cols() ; ++col)
LM's avatar
LM committed
148
    {
149
      for(Index i=lhs.cols()-1; i>=0; --i)
LM's avatar
LM committed
150 151 152 153 154 155
      {
        Scalar& tmp = other.coeffRef(i,col);
        if (tmp!=Scalar(0)) // optimization when other is actually sparse
        {
          if(!(Mode & UnitDiag))
          {
Don Gagne's avatar
Don Gagne committed
156
            // TODO replace this by a binary search. make sure the binary search is safe for partially sorted elements
157
            LhsIterator it(lhsEval, i);
Don Gagne's avatar
Don Gagne committed
158
            while(it && it.index()!=i)
159
              ++it;
Don Gagne's avatar
Don Gagne committed
160 161
            eigen_assert(it && it.index()==i);
            other.coeffRef(i,col) /= it.value();
LM's avatar
LM committed
162
          }
163
          LhsIterator it(lhsEval, i);
LM's avatar
LM committed
164 165 166 167 168 169 170 171 172 173
          for(; it && it.index()<i; ++it)
            other.coeffRef(it.index(), col) -= tmp * it.value();
        }
      }
    }
  }
};

} // end namespace internal

174 175 176
#ifndef EIGEN_PARSED_BY_DOXYGEN

template<typename ExpressionType,unsigned int Mode>
LM's avatar
LM committed
177
template<typename OtherDerived>
178
void TriangularViewImpl<ExpressionType,Mode,Sparse>::solveInPlace(MatrixBase<OtherDerived>& other) const
LM's avatar
LM committed
179
{
180
  eigen_assert(derived().cols() == derived().rows() && derived().cols() == other.rows());
Don Gagne's avatar
Don Gagne committed
181
  eigen_assert((!(Mode & ZeroDiag)) && bool(Mode & (Upper|Lower)));
LM's avatar
LM committed
182 183 184 185 186 187 188

  enum { copy = internal::traits<OtherDerived>::Flags & RowMajorBit };

  typedef typename internal::conditional<copy,
    typename internal::plain_matrix_type_column_major<OtherDerived>::type, OtherDerived&>::type OtherCopy;
  OtherCopy otherCopy(other.derived());

189
  internal::sparse_solve_triangular_selector<ExpressionType, typename internal::remove_reference<OtherCopy>::type, Mode>::run(derived().nestedExpression(), otherCopy);
LM's avatar
LM committed
190 191 192 193

  if (copy)
    other = otherCopy;
}
194
#endif
LM's avatar
LM committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

// pure sparse path

namespace internal {

template<typename Lhs, typename Rhs, int Mode,
  int UpLo = (Mode & Lower)
           ? Lower
           : (Mode & Upper)
           ? Upper
           : -1,
  int StorageOrder = int(Lhs::Flags) & (RowMajorBit)>
struct sparse_solve_triangular_sparse_selector;

// forward substitution, col-major
template<typename Lhs, typename Rhs, int Mode, int UpLo>
struct sparse_solve_triangular_sparse_selector<Lhs,Rhs,Mode,UpLo,ColMajor>
{
  typedef typename Rhs::Scalar Scalar;
214 215
  typedef typename promote_index_type<typename traits<Lhs>::StorageIndex,
                                      typename traits<Rhs>::StorageIndex>::type StorageIndex;
LM's avatar
LM committed
216 217 218
  static void run(const Lhs& lhs, Rhs& other)
  {
    const bool IsLower = (UpLo==Lower);
219
    AmbiVector<Scalar,StorageIndex> tempVector(other.rows()*2);
LM's avatar
LM committed
220 221 222 223 224
    tempVector.setBounds(0,other.rows());

    Rhs res(other.rows(), other.cols());
    res.reserve(other.nonZeros());

225
    for(Index col=0 ; col<other.cols() ; ++col)
LM's avatar
LM committed
226 227 228 229 230 231 232 233 234 235
    {
      // FIXME estimate number of non zeros
      tempVector.init(.99/*float(other.col(col).nonZeros())/float(other.rows())*/);
      tempVector.setZero();
      tempVector.restart();
      for (typename Rhs::InnerIterator rhsIt(other, col); rhsIt; ++rhsIt)
      {
        tempVector.coeffRef(rhsIt.index()) = rhsIt.value();
      }

236
      for(Index i=IsLower?0:lhs.cols()-1;
LM's avatar
LM committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
          IsLower?i<lhs.cols():i>=0;
          i+=IsLower?1:-1)
      {
        tempVector.restart();
        Scalar& ci = tempVector.coeffRef(i);
        if (ci!=Scalar(0))
        {
          // find
          typename Lhs::InnerIterator it(lhs, i);
          if(!(Mode & UnitDiag))
          {
            if (IsLower)
            {
              eigen_assert(it.index()==i);
              ci /= it.value();
            }
            else
              ci /= lhs.coeff(i,i);
          }
          tempVector.restart();
          if (IsLower)
          {
            if (it.index()==i)
              ++it;
            for(; it; ++it)
              tempVector.coeffRef(it.index()) -= ci * it.value();
          }
          else
          {
            for(; it && it.index()<i; ++it)
              tempVector.coeffRef(it.index()) -= ci * it.value();
          }
        }
      }


273
      Index count = 0;
LM's avatar
LM committed
274
      // FIXME compute a reference value to filter zeros
275
      for (typename AmbiVector<Scalar,StorageIndex>::Iterator it(tempVector/*,1e-12*/); it; ++it)
LM's avatar
LM committed
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
      {
        ++ count;
//         std::cerr << "fill " << it.index() << ", " << col << "\n";
//         std::cout << it.value() << "  ";
        // FIXME use insertBack
        res.insert(it.index(), col) = it.value();
      }
//       std::cout << "tempVector.nonZeros() == " << int(count) << " / " << (other.rows()) << "\n";
    }
    res.finalize();
    other = res.markAsRValue();
  }
};

} // end namespace internal

292 293
#ifndef EIGEN_PARSED_BY_DOXYGEN
template<typename ExpressionType,unsigned int Mode>
LM's avatar
LM committed
294
template<typename OtherDerived>
295
void TriangularViewImpl<ExpressionType,Mode,Sparse>::solveInPlace(SparseMatrixBase<OtherDerived>& other) const
LM's avatar
LM committed
296
{
297
  eigen_assert(derived().cols() == derived().rows() && derived().cols() == other.rows());
Don Gagne's avatar
Don Gagne committed
298
  eigen_assert( (!(Mode & ZeroDiag)) && bool(Mode & (Upper|Lower)));
LM's avatar
LM committed
299 300 301 302 303 304 305

//   enum { copy = internal::traits<OtherDerived>::Flags & RowMajorBit };

//   typedef typename internal::conditional<copy,
//     typename internal::plain_matrix_type_column_major<OtherDerived>::type, OtherDerived&>::type OtherCopy;
//   OtherCopy otherCopy(other.derived());

306
  internal::sparse_solve_triangular_sparse_selector<ExpressionType, OtherDerived, Mode>::run(derived().nestedExpression(), other.derived());
LM's avatar
LM committed
307 308 309 310

//   if (copy)
//     other = otherCopy;
}
311
#endif
LM's avatar
LM committed
312

Don Gagne's avatar
Don Gagne committed
313 314
} // end namespace Eigen

LM's avatar
LM committed
315
#endif // EIGEN_SPARSETRIANGULARSOLVER_H