AmbiVector.h 10.3 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_AMBIVECTOR_H
#define EIGEN_AMBIVECTOR_H

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

namespace internal {

LM's avatar
LM committed
17 18 19 20 21
/** \internal
  * Hybrid sparse/dense vector class designed for intensive read-write operations.
  *
  * See BasicSparseLLT and SparseProduct for usage examples.
  */
22
template<typename _Scalar, typename _StorageIndex>
LM's avatar
LM committed
23 24 25 26
class AmbiVector
{
  public:
    typedef _Scalar Scalar;
27
    typedef _StorageIndex StorageIndex;
LM's avatar
LM committed
28 29
    typedef typename NumTraits<Scalar>::Real RealScalar;

30
    explicit AmbiVector(Index size)
LM's avatar
LM committed
31 32 33 34 35 36 37 38 39 40 41
      : m_buffer(0), m_zero(0), m_size(0), m_allocatedSize(0), m_allocatedElements(0), m_mode(-1)
    {
      resize(size);
    }

    void init(double estimatedDensity);
    void init(int mode);

    Index nonZeros() const;

    /** Specifies a sub-vector to work on */
42
    void setBounds(Index start, Index end) { m_start = convert_index(start); m_end = convert_index(end); }
LM's avatar
LM committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

    void setZero();

    void restart();
    Scalar& coeffRef(Index i);
    Scalar& coeff(Index i);

    class Iterator;

    ~AmbiVector() { delete[] m_buffer; }

    void resize(Index size)
    {
      if (m_allocatedSize < size)
        reallocate(size);
58
      m_size = convert_index(size);
LM's avatar
LM committed
59 60
    }

61
    StorageIndex size() const { return m_size; }
LM's avatar
LM committed
62 63

  protected:
64 65 66 67
    StorageIndex convert_index(Index idx)
    {
      return internal::convert_index<StorageIndex>(idx);
    }
LM's avatar
LM committed
68 69 70 71 72 73 74 75

    void reallocate(Index size)
    {
      // if the size of the matrix is not too large, let's allocate a bit more than needed such
      // that we can handle dense vector even in sparse mode.
      delete[] m_buffer;
      if (size<1000)
      {
76
        Index allocSize = (size * sizeof(ListEl) + sizeof(Scalar) - 1)/sizeof(Scalar);
77
        m_allocatedElements = convert_index((allocSize*sizeof(Scalar))/sizeof(ListEl));
LM's avatar
LM committed
78 79 80 81
        m_buffer = new Scalar[allocSize];
      }
      else
      {
82
        m_allocatedElements = convert_index((size*sizeof(Scalar))/sizeof(ListEl));
LM's avatar
LM committed
83 84
        m_buffer = new Scalar[size];
      }
85
      m_size = convert_index(size);
LM's avatar
LM committed
86 87 88 89 90 91 92
      m_start = 0;
      m_end = m_size;
    }

    void reallocateSparse()
    {
      Index copyElements = m_allocatedElements;
93
      m_allocatedElements = (std::min)(StorageIndex(m_allocatedElements*1.5),m_size);
LM's avatar
LM committed
94
      Index allocSize = m_allocatedElements * sizeof(ListEl);
95
      allocSize = (allocSize + sizeof(Scalar) - 1)/sizeof(Scalar);
LM's avatar
LM committed
96
      Scalar* newBuffer = new Scalar[allocSize];
97
      std::memcpy(newBuffer,  m_buffer,  copyElements * sizeof(ListEl));
LM's avatar
LM committed
98 99 100 101 102 103 104 105
      delete[] m_buffer;
      m_buffer = newBuffer;
    }

  protected:
    // element type of the linked list
    struct ListEl
    {
106 107
      StorageIndex next;
      StorageIndex index;
LM's avatar
LM committed
108 109 110 111 112 113
      Scalar value;
    };

    // used to store data in both mode
    Scalar* m_buffer;
    Scalar m_zero;
114 115 116 117 118 119
    StorageIndex m_size;
    StorageIndex m_start;
    StorageIndex m_end;
    StorageIndex m_allocatedSize;
    StorageIndex m_allocatedElements;
    StorageIndex m_mode;
LM's avatar
LM committed
120 121

    // linked list mode
122 123 124
    StorageIndex m_llStart;
    StorageIndex m_llCurrent;
    StorageIndex m_llSize;
LM's avatar
LM committed
125 126 127
};

/** \returns the number of non zeros in the current sub vector */
128 129
template<typename _Scalar,typename _StorageIndex>
Index AmbiVector<_Scalar,_StorageIndex>::nonZeros() const
LM's avatar
LM committed
130 131 132 133 134 135 136
{
  if (m_mode==IsSparse)
    return m_llSize;
  else
    return m_end - m_start;
}

137 138
template<typename _Scalar,typename _StorageIndex>
void AmbiVector<_Scalar,_StorageIndex>::init(double estimatedDensity)
LM's avatar
LM committed
139 140 141 142 143 144 145
{
  if (estimatedDensity>0.1)
    init(IsDense);
  else
    init(IsSparse);
}

146 147
template<typename _Scalar,typename _StorageIndex>
void AmbiVector<_Scalar,_StorageIndex>::init(int mode)
LM's avatar
LM committed
148 149 150 151 152 153 154 155 156 157 158 159 160 161
{
  m_mode = mode;
  if (m_mode==IsSparse)
  {
    m_llSize = 0;
    m_llStart = -1;
  }
}

/** Must be called whenever we might perform a write access
  * with an index smaller than the previous one.
  *
  * Don't worry, this function is extremely cheap.
  */
162 163
template<typename _Scalar,typename _StorageIndex>
void AmbiVector<_Scalar,_StorageIndex>::restart()
LM's avatar
LM committed
164 165 166 167 168
{
  m_llCurrent = m_llStart;
}

/** Set all coefficients of current subvector to zero */
169 170
template<typename _Scalar,typename _StorageIndex>
void AmbiVector<_Scalar,_StorageIndex>::setZero()
LM's avatar
LM committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184
{
  if (m_mode==IsDense)
  {
    for (Index i=m_start; i<m_end; ++i)
      m_buffer[i] = Scalar(0);
  }
  else
  {
    eigen_assert(m_mode==IsSparse);
    m_llSize = 0;
    m_llStart = -1;
  }
}

185 186
template<typename _Scalar,typename _StorageIndex>
_Scalar& AmbiVector<_Scalar,_StorageIndex>::coeffRef(Index i)
LM's avatar
LM committed
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
{
  if (m_mode==IsDense)
    return m_buffer[i];
  else
  {
    ListEl* EIGEN_RESTRICT llElements = reinterpret_cast<ListEl*>(m_buffer);
    // TODO factorize the following code to reduce code generation
    eigen_assert(m_mode==IsSparse);
    if (m_llSize==0)
    {
      // this is the first element
      m_llStart = 0;
      m_llCurrent = 0;
      ++m_llSize;
      llElements[0].value = Scalar(0);
202
      llElements[0].index = convert_index(i);
LM's avatar
LM committed
203 204 205 206 207 208 209 210
      llElements[0].next = -1;
      return llElements[0].value;
    }
    else if (i<llElements[m_llStart].index)
    {
      // this is going to be the new first element of the list
      ListEl& el = llElements[m_llSize];
      el.value = Scalar(0);
211
      el.index = convert_index(i);
LM's avatar
LM committed
212 213 214 215 216 217 218 219
      el.next = m_llStart;
      m_llStart = m_llSize;
      ++m_llSize;
      m_llCurrent = m_llStart;
      return el.value;
    }
    else
    {
220
      StorageIndex nextel = llElements[m_llCurrent].next;
LM's avatar
LM committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
      eigen_assert(i>=llElements[m_llCurrent].index && "you must call restart() before inserting an element with lower or equal index");
      while (nextel >= 0 && llElements[nextel].index<=i)
      {
        m_llCurrent = nextel;
        nextel = llElements[nextel].next;
      }

      if (llElements[m_llCurrent].index==i)
      {
        // the coefficient already exists and we found it !
        return llElements[m_llCurrent].value;
      }
      else
      {
        if (m_llSize>=m_allocatedElements)
        {
          reallocateSparse();
          llElements = reinterpret_cast<ListEl*>(m_buffer);
        }
        eigen_internal_assert(m_llSize<m_allocatedElements && "internal error: overflow in sparse mode");
        // let's insert a new coefficient
        ListEl& el = llElements[m_llSize];
        el.value = Scalar(0);
244
        el.index = convert_index(i);
LM's avatar
LM committed
245 246 247 248 249 250 251 252 253
        el.next = llElements[m_llCurrent].next;
        llElements[m_llCurrent].next = m_llSize;
        ++m_llSize;
        return el.value;
      }
    }
  }
}

254 255
template<typename _Scalar,typename _StorageIndex>
_Scalar& AmbiVector<_Scalar,_StorageIndex>::coeff(Index i)
LM's avatar
LM committed
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
{
  if (m_mode==IsDense)
    return m_buffer[i];
  else
  {
    ListEl* EIGEN_RESTRICT llElements = reinterpret_cast<ListEl*>(m_buffer);
    eigen_assert(m_mode==IsSparse);
    if ((m_llSize==0) || (i<llElements[m_llStart].index))
    {
      return m_zero;
    }
    else
    {
      Index elid = m_llStart;
      while (elid >= 0 && llElements[elid].index<i)
        elid = llElements[elid].next;

      if (llElements[elid].index==i)
        return llElements[m_llCurrent].value;
      else
        return m_zero;
    }
  }
}

/** Iterator over the nonzero coefficients */
282 283
template<typename _Scalar,typename _StorageIndex>
class AmbiVector<_Scalar,_StorageIndex>::Iterator
LM's avatar
LM committed
284 285 286 287 288 289 290 291 292 293 294
{
  public:
    typedef _Scalar Scalar;
    typedef typename NumTraits<Scalar>::Real RealScalar;

    /** Default constructor
      * \param vec the vector on which we iterate
      * \param epsilon the minimal value used to prune zero coefficients.
      * In practice, all coefficients having a magnitude smaller than \a epsilon
      * are skipped.
      */
295
    explicit Iterator(const AmbiVector& vec, const RealScalar& epsilon = 0)
LM's avatar
LM committed
296 297
      : m_vector(vec)
    {
Don Gagne's avatar
Don Gagne committed
298
      using std::abs;
LM's avatar
LM committed
299 300 301 302 303 304 305 306 307 308 309 310 311
      m_epsilon = epsilon;
      m_isDense = m_vector.m_mode==IsDense;
      if (m_isDense)
      {
        m_currentEl = 0;   // this is to avoid a compilation warning
        m_cachedValue = 0; // this is to avoid a compilation warning
        m_cachedIndex = m_vector.m_start-1;
        ++(*this);
      }
      else
      {
        ListEl* EIGEN_RESTRICT llElements = reinterpret_cast<ListEl*>(m_vector.m_buffer);
        m_currentEl = m_vector.m_llStart;
Don Gagne's avatar
Don Gagne committed
312
        while (m_currentEl>=0 && abs(llElements[m_currentEl].value)<=m_epsilon)
LM's avatar
LM committed
313 314 315 316 317 318 319 320 321 322 323 324 325 326
          m_currentEl = llElements[m_currentEl].next;
        if (m_currentEl<0)
        {
          m_cachedValue = 0; // this is to avoid a compilation warning
          m_cachedIndex = -1;
        }
        else
        {
          m_cachedIndex = llElements[m_currentEl].index;
          m_cachedValue = llElements[m_currentEl].value;
        }
      }
    }

327
    StorageIndex index() const { return m_cachedIndex; }
LM's avatar
LM committed
328 329 330 331 332 333
    Scalar value() const { return m_cachedValue; }

    operator bool() const { return m_cachedIndex>=0; }

    Iterator& operator++()
    {
Don Gagne's avatar
Don Gagne committed
334
      using std::abs;
LM's avatar
LM committed
335 336 337 338
      if (m_isDense)
      {
        do {
          ++m_cachedIndex;
339
        } while (m_cachedIndex<m_vector.m_end && abs(m_vector.m_buffer[m_cachedIndex])<=m_epsilon);
LM's avatar
LM committed
340 341 342 343 344 345 346 347 348 349
        if (m_cachedIndex<m_vector.m_end)
          m_cachedValue = m_vector.m_buffer[m_cachedIndex];
        else
          m_cachedIndex=-1;
      }
      else
      {
        ListEl* EIGEN_RESTRICT llElements = reinterpret_cast<ListEl*>(m_vector.m_buffer);
        do {
          m_currentEl = llElements[m_currentEl].next;
350
        } while (m_currentEl>=0 && abs(llElements[m_currentEl].value)<=m_epsilon);
LM's avatar
LM committed
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
        if (m_currentEl<0)
        {
          m_cachedIndex = -1;
        }
        else
        {
          m_cachedIndex = llElements[m_currentEl].index;
          m_cachedValue = llElements[m_currentEl].value;
        }
      }
      return *this;
    }

  protected:
    const AmbiVector& m_vector; // the target vector
366
    StorageIndex m_currentEl;   // the current element in sparse/linked-list mode
LM's avatar
LM committed
367
    RealScalar m_epsilon;       // epsilon used to prune zero coefficients
368
    StorageIndex m_cachedIndex; // current coordinate
LM's avatar
LM committed
369 370 371 372
    Scalar m_cachedValue;       // current value
    bool m_isDense;             // mode of the vector
};

Don Gagne's avatar
Don Gagne committed
373 374 375
} // end namespace internal

} // end namespace Eigen
LM's avatar
LM committed
376 377

#endif // EIGEN_AMBIVECTOR_H