Jacobi.h 15.5 KB
Newer Older
LM's avatar
LM committed
1 2 3 4 5 6
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
Don Gagne's avatar
Don Gagne committed
7 8 9
// 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
10 11 12 13

#ifndef EIGEN_JACOBI_H
#define EIGEN_JACOBI_H

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

LM's avatar
LM committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
/** \ingroup Jacobi_Module
  * \jacobi_module
  * \class JacobiRotation
  * \brief Rotation given by a cosine-sine pair.
  *
  * This class represents a Jacobi or Givens rotation.
  * This is a 2D rotation in the plane \c J of angle \f$ \theta \f$ defined by
  * its cosine \c c and sine \c s as follow:
  * \f$ J = \left ( \begin{array}{cc} c & \overline s \\ -s  & \overline c \end{array} \right ) \f$
  *
  * You can apply the respective counter-clockwise rotation to a column vector \c v by
  * applying its adjoint on the left: \f$ v = J^* v \f$ that translates to the following Eigen code:
  * \code
  * v.applyOnTheLeft(J.adjoint());
  * \endcode
  *
  * \sa MatrixBase::applyOnTheLeft(), MatrixBase::applyOnTheRight()
  */
template<typename Scalar> class JacobiRotation
{
  public:
    typedef typename NumTraits<Scalar>::Real RealScalar;

    /** Default constructor without any initialization. */
    JacobiRotation() {}

    /** Construct a planar rotation from a cosine-sine pair (\a c, \c s). */
    JacobiRotation(const Scalar& c, const Scalar& s) : m_c(c), m_s(s) {}

    Scalar& c() { return m_c; }
    Scalar c() const { return m_c; }
    Scalar& s() { return m_s; }
    Scalar s() const { return m_s; }

    /** Concatenates two planar rotation */
    JacobiRotation operator*(const JacobiRotation& other)
    {
Don Gagne's avatar
Don Gagne committed
53 54 55
      using numext::conj;
      return JacobiRotation(m_c * other.m_c - conj(m_s) * other.m_s,
                            conj(m_c * conj(other.m_s) + conj(m_s) * conj(other.m_c)));
LM's avatar
LM committed
56 57 58
    }

    /** Returns the transposed transformation */
Don Gagne's avatar
Don Gagne committed
59
    JacobiRotation transpose() const { using numext::conj; return JacobiRotation(m_c, -conj(m_s)); }
LM's avatar
LM committed
60 61

    /** Returns the adjoint transformation */
Don Gagne's avatar
Don Gagne committed
62
    JacobiRotation adjoint() const { using numext::conj; return JacobiRotation(conj(m_c), -m_s); }
LM's avatar
LM committed
63 64

    template<typename Derived>
65
    bool makeJacobi(const MatrixBase<Derived>&, Index p, Index q);
Don Gagne's avatar
Don Gagne committed
66
    bool makeJacobi(const RealScalar& x, const Scalar& y, const RealScalar& z);
LM's avatar
LM committed
67

68
    void makeGivens(const Scalar& p, const Scalar& q, Scalar* r=0);
LM's avatar
LM committed
69 70

  protected:
71 72
    void makeGivens(const Scalar& p, const Scalar& q, Scalar* r, internal::true_type);
    void makeGivens(const Scalar& p, const Scalar& q, Scalar* r, internal::false_type);
LM's avatar
LM committed
73 74 75 76 77 78 79 80 81 82

    Scalar m_c, m_s;
};

/** Makes \c *this as a Jacobi rotation \a J such that applying \a J on both the right and left sides of the selfadjoint 2x2 matrix
  * \f$ B = \left ( \begin{array}{cc} x & y \\ \overline y & z \end{array} \right )\f$ yields a diagonal matrix \f$ A = J^* B J \f$
  *
  * \sa MatrixBase::makeJacobi(const MatrixBase<Derived>&, Index, Index), MatrixBase::applyOnTheLeft(), MatrixBase::applyOnTheRight()
  */
template<typename Scalar>
Don Gagne's avatar
Don Gagne committed
83
bool JacobiRotation<Scalar>::makeJacobi(const RealScalar& x, const Scalar& y, const RealScalar& z)
LM's avatar
LM committed
84
{
Don Gagne's avatar
Don Gagne committed
85 86
  using std::sqrt;
  using std::abs;
87 88
  RealScalar deno = RealScalar(2)*abs(y);
  if(deno < (std::numeric_limits<RealScalar>::min)())
LM's avatar
LM committed
89 90 91 92 93 94 95
  {
    m_c = Scalar(1);
    m_s = Scalar(0);
    return false;
  }
  else
  {
96
    RealScalar tau = (x-z)/deno;
Don Gagne's avatar
Don Gagne committed
97
    RealScalar w = sqrt(numext::abs2(tau) + RealScalar(1));
LM's avatar
LM committed
98 99 100 101 102 103 104 105 106 107
    RealScalar t;
    if(tau>RealScalar(0))
    {
      t = RealScalar(1) / (tau + w);
    }
    else
    {
      t = RealScalar(1) / (tau - w);
    }
    RealScalar sign_t = t > RealScalar(0) ? RealScalar(1) : RealScalar(-1);
Don Gagne's avatar
Don Gagne committed
108 109
    RealScalar n = RealScalar(1) / sqrt(numext::abs2(t)+RealScalar(1));
    m_s = - sign_t * (numext::conj(y) / abs(y)) * abs(t) * n;
LM's avatar
LM committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    m_c = n;
    return true;
  }
}

/** Makes \c *this as a Jacobi rotation \c J such that applying \a J on both the right and left sides of the 2x2 selfadjoint matrix
  * \f$ B = \left ( \begin{array}{cc} \text{this}_{pp} & \text{this}_{pq} \\ (\text{this}_{pq})^* & \text{this}_{qq} \end{array} \right )\f$ yields
  * a diagonal matrix \f$ A = J^* B J \f$
  *
  * Example: \include Jacobi_makeJacobi.cpp
  * Output: \verbinclude Jacobi_makeJacobi.out
  *
  * \sa JacobiRotation::makeJacobi(RealScalar, Scalar, RealScalar), MatrixBase::applyOnTheLeft(), MatrixBase::applyOnTheRight()
  */
template<typename Scalar>
template<typename Derived>
126
inline bool JacobiRotation<Scalar>::makeJacobi(const MatrixBase<Derived>& m, Index p, Index q)
LM's avatar
LM committed
127
{
Don Gagne's avatar
Don Gagne committed
128
  return makeJacobi(numext::real(m.coeff(p,p)), m.coeff(p,q), numext::real(m.coeff(q,q)));
LM's avatar
LM committed
129 130 131 132 133 134
}

/** Makes \c *this as a Givens rotation \c G such that applying \f$ G^* \f$ to the left of the vector
  * \f$ V = \left ( \begin{array}{c} p \\ q \end{array} \right )\f$ yields:
  * \f$ G^* V = \left ( \begin{array}{c} r \\ 0 \end{array} \right )\f$.
  *
135
  * The value of \a r is returned if \a r is not null (the default is null).
LM's avatar
LM committed
136 137 138 139 140 141 142 143 144 145 146 147
  * Also note that G is built such that the cosine is always real.
  *
  * Example: \include Jacobi_makeGivens.cpp
  * Output: \verbinclude Jacobi_makeGivens.out
  *
  * This function implements the continuous Givens rotation generation algorithm
  * found in Anderson (2000), Discontinuous Plane Rotations and the Symmetric Eigenvalue Problem.
  * LAPACK Working Note 150, University of Tennessee, UT-CS-00-454, December 4, 2000.
  *
  * \sa MatrixBase::applyOnTheLeft(), MatrixBase::applyOnTheRight()
  */
template<typename Scalar>
148
void JacobiRotation<Scalar>::makeGivens(const Scalar& p, const Scalar& q, Scalar* r)
LM's avatar
LM committed
149
{
150
  makeGivens(p, q, r, typename internal::conditional<NumTraits<Scalar>::IsComplex, internal::true_type, internal::false_type>::type());
LM's avatar
LM committed
151 152 153 154 155 156 157
}


// specialization for complexes
template<typename Scalar>
void JacobiRotation<Scalar>::makeGivens(const Scalar& p, const Scalar& q, Scalar* r, internal::true_type)
{
Don Gagne's avatar
Don Gagne committed
158 159 160 161
  using std::sqrt;
  using std::abs;
  using numext::conj;
  
LM's avatar
LM committed
162 163
  if(q==Scalar(0))
  {
Don Gagne's avatar
Don Gagne committed
164
    m_c = numext::real(p)<0 ? Scalar(-1) : Scalar(1);
LM's avatar
LM committed
165 166 167 168 169 170
    m_s = 0;
    if(r) *r = m_c * p;
  }
  else if(p==Scalar(0))
  {
    m_c = 0;
Don Gagne's avatar
Don Gagne committed
171 172
    m_s = -q/abs(q);
    if(r) *r = abs(q);
LM's avatar
LM committed
173 174 175
  }
  else
  {
Don Gagne's avatar
Don Gagne committed
176 177
    RealScalar p1 = numext::norm1(p);
    RealScalar q1 = numext::norm1(q);
LM's avatar
LM committed
178 179 180
    if(p1>=q1)
    {
      Scalar ps = p / p1;
Don Gagne's avatar
Don Gagne committed
181
      RealScalar p2 = numext::abs2(ps);
LM's avatar
LM committed
182
      Scalar qs = q / p1;
Don Gagne's avatar
Don Gagne committed
183
      RealScalar q2 = numext::abs2(qs);
LM's avatar
LM committed
184

Don Gagne's avatar
Don Gagne committed
185 186
      RealScalar u = sqrt(RealScalar(1) + q2/p2);
      if(numext::real(p)<RealScalar(0))
LM's avatar
LM committed
187 188 189
        u = -u;

      m_c = Scalar(1)/u;
Don Gagne's avatar
Don Gagne committed
190
      m_s = -qs*conj(ps)*(m_c/p2);
LM's avatar
LM committed
191 192 193 194 195
      if(r) *r = p * u;
    }
    else
    {
      Scalar ps = p / q1;
Don Gagne's avatar
Don Gagne committed
196
      RealScalar p2 = numext::abs2(ps);
LM's avatar
LM committed
197
      Scalar qs = q / q1;
Don Gagne's avatar
Don Gagne committed
198
      RealScalar q2 = numext::abs2(qs);
LM's avatar
LM committed
199

Don Gagne's avatar
Don Gagne committed
200 201
      RealScalar u = q1 * sqrt(p2 + q2);
      if(numext::real(p)<RealScalar(0))
LM's avatar
LM committed
202 203
        u = -u;

Don Gagne's avatar
Don Gagne committed
204
      p1 = abs(p);
LM's avatar
LM committed
205 206
      ps = p/p1;
      m_c = p1/u;
Don Gagne's avatar
Don Gagne committed
207
      m_s = -conj(ps) * (q/u);
LM's avatar
LM committed
208 209 210 211 212 213 214 215 216
      if(r) *r = ps * u;
    }
  }
}

// specialization for reals
template<typename Scalar>
void JacobiRotation<Scalar>::makeGivens(const Scalar& p, const Scalar& q, Scalar* r, internal::false_type)
{
Don Gagne's avatar
Don Gagne committed
217 218
  using std::sqrt;
  using std::abs;
LM's avatar
LM committed
219 220 221 222
  if(q==Scalar(0))
  {
    m_c = p<Scalar(0) ? Scalar(-1) : Scalar(1);
    m_s = Scalar(0);
Don Gagne's avatar
Don Gagne committed
223
    if(r) *r = abs(p);
LM's avatar
LM committed
224 225 226 227 228
  }
  else if(p==Scalar(0))
  {
    m_c = Scalar(0);
    m_s = q<Scalar(0) ? Scalar(1) : Scalar(-1);
Don Gagne's avatar
Don Gagne committed
229
    if(r) *r = abs(q);
LM's avatar
LM committed
230
  }
Don Gagne's avatar
Don Gagne committed
231
  else if(abs(p) > abs(q))
LM's avatar
LM committed
232 233
  {
    Scalar t = q/p;
Don Gagne's avatar
Don Gagne committed
234
    Scalar u = sqrt(Scalar(1) + numext::abs2(t));
LM's avatar
LM committed
235 236 237 238 239 240 241 242 243
    if(p<Scalar(0))
      u = -u;
    m_c = Scalar(1)/u;
    m_s = -t * m_c;
    if(r) *r = p * u;
  }
  else
  {
    Scalar t = p/q;
Don Gagne's avatar
Don Gagne committed
244
    Scalar u = sqrt(Scalar(1) + numext::abs2(t));
LM's avatar
LM committed
245 246 247 248 249 250 251 252 253 254 255 256 257
    if(q<Scalar(0))
      u = -u;
    m_s = -Scalar(1)/u;
    m_c = -t * m_s;
    if(r) *r = q * u;
  }

}

/****************************************************************************************
*   Implementation of MatrixBase methods
****************************************************************************************/

258
namespace internal {
LM's avatar
LM committed
259 260 261 262 263 264 265
/** \jacobi_module
  * Applies the clock wise 2D rotation \a j to the set of 2D vectors of cordinates \a x and \a y:
  * \f$ \left ( \begin{array}{cc} x \\ y \end{array} \right )  =  J \left ( \begin{array}{cc} x \\ y \end{array} \right ) \f$
  *
  * \sa MatrixBase::applyOnTheLeft(), MatrixBase::applyOnTheRight()
  */
template<typename VectorX, typename VectorY, typename OtherScalar>
266
void apply_rotation_in_the_plane(DenseBase<VectorX>& xpr_x, DenseBase<VectorY>& xpr_y, const JacobiRotation<OtherScalar>& j);
LM's avatar
LM committed
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
}

/** \jacobi_module
  * Applies the rotation in the plane \a j to the rows \a p and \a q of \c *this, i.e., it computes B = J * B,
  * with \f$ B = \left ( \begin{array}{cc} \text{*this.row}(p) \\ \text{*this.row}(q) \end{array} \right ) \f$.
  *
  * \sa class JacobiRotation, MatrixBase::applyOnTheRight(), internal::apply_rotation_in_the_plane()
  */
template<typename Derived>
template<typename OtherScalar>
inline void MatrixBase<Derived>::applyOnTheLeft(Index p, Index q, const JacobiRotation<OtherScalar>& j)
{
  RowXpr x(this->row(p));
  RowXpr y(this->row(q));
  internal::apply_rotation_in_the_plane(x, y, j);
}

/** \ingroup Jacobi_Module
  * Applies the rotation in the plane \a j to the columns \a p and \a q of \c *this, i.e., it computes B = B * J
  * with \f$ B = \left ( \begin{array}{cc} \text{*this.col}(p) & \text{*this.col}(q) \end{array} \right ) \f$.
  *
  * \sa class JacobiRotation, MatrixBase::applyOnTheLeft(), internal::apply_rotation_in_the_plane()
  */
template<typename Derived>
template<typename OtherScalar>
inline void MatrixBase<Derived>::applyOnTheRight(Index p, Index q, const JacobiRotation<OtherScalar>& j)
{
  ColXpr x(this->col(p));
  ColXpr y(this->col(q));
  internal::apply_rotation_in_the_plane(x, y, j.transpose());
}

namespace internal {

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
template<typename Scalar, typename OtherScalar,
         int SizeAtCompileTime, int MinAlignment, bool Vectorizable>
struct apply_rotation_in_the_plane_selector
{
  static inline void run(Scalar *x, Index incrx, Scalar *y, Index incry, Index size, OtherScalar c, OtherScalar s)
  {
    for(Index i=0; i<size; ++i)
    {
      Scalar xi = *x;
      Scalar yi = *y;
      *x =  c * xi + numext::conj(s) * yi;
      *y = -s * xi + numext::conj(c) * yi;
      x += incrx;
      y += incry;
    }
  }
};
LM's avatar
LM committed
318

319 320 321 322 323
template<typename Scalar, typename OtherScalar,
         int SizeAtCompileTime, int MinAlignment>
struct apply_rotation_in_the_plane_selector<Scalar,OtherScalar,SizeAtCompileTime,MinAlignment,true /* vectorizable */>
{
  static inline void run(Scalar *x, Index incrx, Scalar *y, Index incry, Index size, OtherScalar c, OtherScalar s)
LM's avatar
LM committed
324
  {
325 326 327 328 329 330 331 332 333 334 335 336
    enum {
      PacketSize = packet_traits<Scalar>::size,
      OtherPacketSize = packet_traits<OtherScalar>::size
    };
    typedef typename packet_traits<Scalar>::type Packet;
    typedef typename packet_traits<OtherScalar>::type OtherPacket;

    /*** dynamic-size vectorized paths ***/
    if(SizeAtCompileTime == Dynamic && ((incrx==1 && incry==1) || PacketSize == 1))
    {
      // both vectors are sequentially stored in memory => vectorization
      enum { Peeling = 2 };
LM's avatar
LM committed
337

338 339
      Index alignedStart = internal::first_default_aligned(y, size);
      Index alignedEnd = alignedStart + ((size-alignedStart)/PacketSize)*PacketSize;
LM's avatar
LM committed
340

341 342 343 344
      const OtherPacket pc = pset1<OtherPacket>(c);
      const OtherPacket ps = pset1<OtherPacket>(s);
      conj_helper<OtherPacket,Packet,NumTraits<OtherScalar>::IsComplex,false> pcj;
      conj_helper<OtherPacket,Packet,false,false> pm;
LM's avatar
LM committed
345

346 347 348 349 350 351 352
      for(Index i=0; i<alignedStart; ++i)
      {
        Scalar xi = x[i];
        Scalar yi = y[i];
        x[i] =  c * xi + numext::conj(s) * yi;
        y[i] = -s * xi + numext::conj(c) * yi;
      }
LM's avatar
LM committed
353

354 355
      Scalar* EIGEN_RESTRICT px = x + alignedStart;
      Scalar* EIGEN_RESTRICT py = y + alignedStart;
LM's avatar
LM committed
356

357
      if(internal::first_default_aligned(x, size)==alignedStart)
LM's avatar
LM committed
358
      {
359 360 361 362 363 364 365 366 367
        for(Index i=alignedStart; i<alignedEnd; i+=PacketSize)
        {
          Packet xi = pload<Packet>(px);
          Packet yi = pload<Packet>(py);
          pstore(px, padd(pm.pmul(pc,xi),pcj.pmul(ps,yi)));
          pstore(py, psub(pcj.pmul(pc,yi),pm.pmul(ps,xi)));
          px += PacketSize;
          py += PacketSize;
        }
LM's avatar
LM committed
368
      }
369
      else
LM's avatar
LM committed
370
      {
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
        Index peelingEnd = alignedStart + ((size-alignedStart)/(Peeling*PacketSize))*(Peeling*PacketSize);
        for(Index i=alignedStart; i<peelingEnd; i+=Peeling*PacketSize)
        {
          Packet xi   = ploadu<Packet>(px);
          Packet xi1  = ploadu<Packet>(px+PacketSize);
          Packet yi   = pload <Packet>(py);
          Packet yi1  = pload <Packet>(py+PacketSize);
          pstoreu(px, padd(pm.pmul(pc,xi),pcj.pmul(ps,yi)));
          pstoreu(px+PacketSize, padd(pm.pmul(pc,xi1),pcj.pmul(ps,yi1)));
          pstore (py, psub(pcj.pmul(pc,yi),pm.pmul(ps,xi)));
          pstore (py+PacketSize, psub(pcj.pmul(pc,yi1),pm.pmul(ps,xi1)));
          px += Peeling*PacketSize;
          py += Peeling*PacketSize;
        }
        if(alignedEnd!=peelingEnd)
        {
          Packet xi = ploadu<Packet>(x+peelingEnd);
          Packet yi = pload <Packet>(y+peelingEnd);
          pstoreu(x+peelingEnd, padd(pm.pmul(pc,xi),pcj.pmul(ps,yi)));
          pstore (y+peelingEnd, psub(pcj.pmul(pc,yi),pm.pmul(ps,xi)));
        }
LM's avatar
LM committed
392
      }
393 394

      for(Index i=alignedEnd; i<size; ++i)
LM's avatar
LM committed
395
      {
396 397 398 399
        Scalar xi = x[i];
        Scalar yi = y[i];
        x[i] =  c * xi + numext::conj(s) * yi;
        y[i] = -s * xi + numext::conj(c) * yi;
LM's avatar
LM committed
400 401 402
      }
    }

403 404
    /*** fixed-size vectorized path ***/
    else if(SizeAtCompileTime != Dynamic && MinAlignment>0) // FIXME should be compared to the required alignment
LM's avatar
LM committed
405
    {
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
      const OtherPacket pc = pset1<OtherPacket>(c);
      const OtherPacket ps = pset1<OtherPacket>(s);
      conj_helper<OtherPacket,Packet,NumTraits<OtherPacket>::IsComplex,false> pcj;
      conj_helper<OtherPacket,Packet,false,false> pm;
      Scalar* EIGEN_RESTRICT px = x;
      Scalar* EIGEN_RESTRICT py = y;
      for(Index i=0; i<size; i+=PacketSize)
      {
        Packet xi = pload<Packet>(px);
        Packet yi = pload<Packet>(py);
        pstore(px, padd(pm.pmul(pc,xi),pcj.pmul(ps,yi)));
        pstore(py, psub(pcj.pmul(pc,yi),pm.pmul(ps,xi)));
        px += PacketSize;
        py += PacketSize;
      }
LM's avatar
LM committed
421 422
    }

423 424
    /*** non-vectorized path ***/
    else
LM's avatar
LM committed
425
    {
426
      apply_rotation_in_the_plane_selector<Scalar,OtherScalar,SizeAtCompileTime,MinAlignment,false>::run(x,incrx,y,incry,size,c,s);
LM's avatar
LM committed
427 428
    }
  }
429
};
LM's avatar
LM committed
430

431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
template<typename VectorX, typename VectorY, typename OtherScalar>
void /*EIGEN_DONT_INLINE*/ apply_rotation_in_the_plane(DenseBase<VectorX>& xpr_x, DenseBase<VectorY>& xpr_y, const JacobiRotation<OtherScalar>& j)
{
  typedef typename VectorX::Scalar Scalar;
  const bool Vectorizable =    (VectorX::Flags & VectorY::Flags & PacketAccessBit)
                            && (int(packet_traits<Scalar>::size) == int(packet_traits<OtherScalar>::size));

  eigen_assert(xpr_x.size() == xpr_y.size());
  Index size = xpr_x.size();
  Index incrx = xpr_x.derived().innerStride();
  Index incry = xpr_y.derived().innerStride();

  Scalar* EIGEN_RESTRICT x = &xpr_x.derived().coeffRef(0);
  Scalar* EIGEN_RESTRICT y = &xpr_y.derived().coeffRef(0);
  
  OtherScalar c = j.c();
  OtherScalar s = j.s();
  if (c==OtherScalar(1) && s==OtherScalar(0))
    return;

  apply_rotation_in_the_plane_selector<
    Scalar,OtherScalar,
    VectorX::SizeAtCompileTime,
    EIGEN_PLAIN_ENUM_MIN(evaluator<VectorX>::Alignment, evaluator<VectorY>::Alignment),
    Vectorizable>::run(x,incrx,y,incry,size,c,s);
LM's avatar
LM committed
456
}
Don Gagne's avatar
Don Gagne committed
457 458 459 460

} // end namespace internal

} // end namespace Eigen
LM's avatar
LM committed
461 462

#endif // EIGEN_JACOBI_H