Removed obsolete/deprecated stuff
[libdai.git] / include / dai / index.h
1 /* This file is part of libDAI - http://www.libdai.org/
2 *
3 * libDAI is licensed under the terms of the GNU General Public License version
4 * 2, or (at your option) any later version. libDAI is distributed without any
5 * warranty. See the file COPYING for more details.
6 *
7 * Copyright (C) 2002 Martijn Leisink [martijn@mbfys.kun.nl]
8 * Copyright (C) 2006-2009 Joris Mooij [joris dot mooij at libdai dot org]
9 * Copyright (C) 2002-2007 Radboud University Nijmegen, The Netherlands
10 */
11
12
13 /// \file
14 /// \brief Defines the IndexFor, multifor, Permute and State classes, which all deal with indexing multi-dimensional arrays
15
16
17 #ifndef __defined_libdai_index_h
18 #define __defined_libdai_index_h
19
20
21 #include <vector>
22 #include <algorithm>
23 #include <map>
24 #include <dai/varset.h>
25
26
27 namespace dai {
28
29
30 /// Tool for looping over the states of several variables.
31 /** The class IndexFor is an important tool for indexing Factor entries.
32 * Its usage can best be explained by an example.
33 * Assume \a indexVars, \a forVars are both VarSet 's.
34 * Then the following code:
35 * \code
36 * IndexFor i( indexVars, forVars );
37 * size_t iter = 0;
38 * for( ; i.valid(); i++, iter++ ) {
39 * cout << "State of forVars: " << calcState( forVars, iter ) << "; ";
40 * cout << "state of indexVars: " << calcState( indexVars, long(i) ) << endl;
41 * }
42 * \endcode
43 * loops over all joint states of the variables in \a forVars,
44 * and <tt>(long)i</tt> equals the linear index of the corresponding
45 * state of \a indexVars, where the variables in \a indexVars that are
46 * not in \a forVars assume their zero'th value.
47 * \idea Optimize all indices as follows: keep a cache of all (or only
48 * relatively small) indices that have been computed (use a hash). Then,
49 * instead of computing on the fly, use the precomputed ones. Here the
50 * labels of the variables don't matter, but the ranges of the variables do.
51 */
52 class IndexFor {
53 private:
54 /// The current linear index corresponding to the state of indexVars
55 long _index;
56
57 /// For each variable in forVars, the amount of change in _index
58 std::vector<long> _sum;
59
60 /// For each variable in forVars, the current state
61 std::vector<size_t> _state;
62
63 /// For each variable in forVars, its number of possible values
64 std::vector<size_t> _ranges;
65
66 public:
67 /// Default constructor
68 IndexFor() : _index(-1) {}
69
70 /// Construct IndexFor object from \a indexVars and \a forVars
71 IndexFor( const VarSet& indexVars, const VarSet& forVars ) : _state( forVars.size(), 0 ) {
72 long sum = 1;
73
74 _ranges.reserve( forVars.size() );
75 _sum.reserve( forVars.size() );
76
77 VarSet::const_iterator j = forVars.begin();
78 for( VarSet::const_iterator i = indexVars.begin(); i != indexVars.end(); ++i ) {
79 for( ; j != forVars.end() && *j <= *i; ++j ) {
80 _ranges.push_back( j->states() );
81 _sum.push_back( (*i == *j) ? sum : 0 );
82 }
83 sum *= i->states();
84 }
85 for( ; j != forVars.end(); ++j ) {
86 _ranges.push_back( j->states() );
87 _sum.push_back( 0 );
88 }
89 _index = 0;
90 }
91
92 /// Resets the state
93 IndexFor& reset() {
94 fill( _state.begin(), _state.end(), 0 );
95 _index = 0;
96 return( *this );
97 }
98
99 /// Conversion to \c size_t: returns linear index of the current state of indexVars
100 operator size_t() const {
101 DAI_ASSERT( valid() );
102 return( _index );
103 }
104
105 /// Increments the current state of \a forVars (prefix)
106 IndexFor& operator++ () {
107 if( _index >= 0 ) {
108 size_t i = 0;
109
110 while( i < _state.size() ) {
111 _index += _sum[i];
112 if( ++_state[i] < _ranges[i] )
113 break;
114 _index -= _sum[i] * _ranges[i];
115 _state[i] = 0;
116 i++;
117 }
118
119 if( i == _state.size() )
120 _index = -1;
121 }
122 return( *this );
123 }
124
125 /// Increments the current state of \a forVars (postfix)
126 void operator++( int ) {
127 operator++();
128 }
129
130 /// Returns \c true if the current state is valid
131 bool valid() const {
132 return( _index >= 0 );
133 }
134 };
135
136
137 /// Tool for calculating permutations of linear indices of multi-dimensional arrays.
138 /** \note This is mainly useful for converting indices into multi-dimensional arrays
139 * corresponding to joint states of variables to and from the canonical ordering used in libDAI.
140 */
141 class Permute {
142 private:
143 /// Stores the number of possible values of all indices
144 std::vector<size_t> _ranges;
145 /// Stores the permutation
146 std::vector<size_t> _sigma;
147
148 public:
149 /// Default constructor
150 Permute() : _ranges(), _sigma() {}
151
152 /// Construct from vector of index ranges and permutation
153 Permute( const std::vector<size_t> &rs, const std::vector<size_t> &sigma ) : _ranges(rs), _sigma(sigma) {
154 DAI_ASSERT( _ranges.size() == _sigma.size() );
155 }
156
157 /// Construct from vector of variables.
158 /** The implied permutation maps the index of each variable in \a vars according to the canonical ordering
159 * (i.e., sorted ascendingly according to their label) to the index it has in \a vars.
160 */
161 Permute( const std::vector<Var> &vars ) : _ranges(vars.size()), _sigma(vars.size()) {
162 for( size_t i = 0; i < vars.size(); ++i )
163 _ranges[i] = vars[i].states();
164 VarSet vs( vars.begin(), vars.end(), vars.size() );
165 VarSet::const_iterator vs_i = vs.begin();
166 for( size_t i = 0; i < vs.size(); ++i, ++vs_i )
167 _sigma[i] = find( vars.begin(), vars.end(), *vs_i ) - vars.begin();
168 }
169
170 /// Calculates a permuted linear index.
171 /** Converts the linear index \a li to a vector index, permutes its
172 * components, and converts it back to a linear index.
173 */
174 size_t convertLinearIndex( size_t li ) const {
175 size_t N = _ranges.size();
176
177 // calculate vector index corresponding to linear index
178 std::vector<size_t> vi;
179 vi.reserve( N );
180 size_t prod = 1;
181 for( size_t k = 0; k < N; k++ ) {
182 vi.push_back( li % _ranges[k] );
183 li /= _ranges[k];
184 prod *= _ranges[k];
185 }
186
187 // convert permuted vector index to corresponding linear index
188 prod = 1;
189 size_t sigma_li = 0;
190 for( size_t k = 0; k < N; k++ ) {
191 sigma_li += vi[_sigma[k]] * prod;
192 prod *= _ranges[_sigma[k]];
193 }
194
195 return sigma_li;
196 }
197
198 /// Returns const reference to the permutation
199 const std::vector<size_t>& sigma() const { return _sigma; }
200
201 /// Returns reference to the permutation
202 std::vector<size_t>& sigma() { return _sigma; }
203
204 /// Returns the result of applying the permutation on \a i
205 size_t operator[]( size_t i ) const {
206 #ifdef DAI_DEBUG
207 return _sigma.at(i);
208 #else
209 return _sigma[i];
210 #endif
211 }
212 };
213
214
215 /// multifor makes it easy to perform a dynamic number of nested \c for loops.
216 /** An example of the usage is as follows:
217 * \code
218 * std::vector<size_t> ranges;
219 * ranges.push_back( 3 );
220 * ranges.push_back( 4 );
221 * ranges.push_back( 5 );
222 * for( multifor s(ranges); s.valid(); ++s )
223 * cout << "linear index: " << (size_t)s << " corresponds to indices " << s[2] << ", " << s[1] << ", " << s[0] << endl;
224 * \endcode
225 * which would be equivalent to:
226 * \code
227 * size_t s = 0;
228 * for( size_t s2 = 0; s2 < 5; s2++ )
229 * for( size_t s1 = 0; s1 < 4; s1++ )
230 * for( size_t s0 = 0; s0 < 3; s++, s0++ )
231 * cout << "linear index: " << (size_t)s << " corresponds to indices " << s2 << ", " << s1 << ", " << s0 << endl;
232 * \endcode
233 */
234 class multifor {
235 private:
236 /// Stores the number of possible values of all indices
237 std::vector<size_t> _ranges;
238 /// Stores the current values of all indices
239 std::vector<size_t> _indices;
240 /// Stores the current linear index
241 long _linear_index;
242
243 public:
244 /// Default constructor
245 multifor() : _ranges(), _indices(), _linear_index(0) {}
246
247 /// Initialize from vector of index ranges
248 multifor( const std::vector<size_t> &d ) : _ranges(d), _indices(d.size(),0), _linear_index(0) {}
249
250 /// Returns linear index (i.e., the index in the Cartesian product space)
251 operator size_t() const {
252 DAI_DEBASSERT( valid() );
253 return( _linear_index );
254 }
255
256 /// Returns \a k 'th index
257 size_t operator[]( size_t k ) const {
258 DAI_DEBASSERT( valid() );
259 DAI_DEBASSERT( k < _indices.size() );
260 return _indices[k];
261 }
262
263 /// Increments the current indices (prefix)
264 multifor & operator++() {
265 if( valid() ) {
266 _linear_index++;
267 size_t i;
268 for( i = 0; i != _indices.size(); i++ ) {
269 if( ++(_indices[i]) < _ranges[i] )
270 break;
271 _indices[i] = 0;
272 }
273 if( i == _indices.size() )
274 _linear_index = -1;
275 }
276 return *this;
277 }
278
279 /// Increments the current indices (postfix)
280 void operator++( int ) {
281 operator++();
282 }
283
284 /// Returns \c true if the current indices are valid
285 bool valid() const {
286 return( _linear_index >= 0 );
287 }
288 };
289
290
291 /// Makes it easy to iterate over all possible joint states of variables within a VarSet.
292 /** A joint state of several variables can be represented in two different ways, by a map that maps each variable
293 * to its own state, or by an integer that gives the index of the joint state in the canonical enumeration.
294 *
295 * Both representations are useful, and the main functionality provided by the State class is to simplify iterating
296 * over the various joint states of a VarSet and to provide access to the current state in both representations.
297 *
298 * As an example, consider the following code snippet which iterates over all joint states of variables \a x0 and \a x1:
299 * \code
300 * VarSet vars( x0, x1 );
301 * for( State S(vars); S.valid(); S++ ) {
302 * cout << "Linear state: " << S.get() << ", x0 = " << S(x0) << ", x1 = " << S(x1) << endl;
303 * }
304 * \endcode
305 *
306 * \note The same functionality could be achieved by simply iterating over the linear state and using dai::calcState(),
307 * but the State class offers a more efficient implementation.
308 *
309 * \note A State is very similar to a \link multifor \endlink, but tailored for Var 's and VarSet 's.
310 *
311 * \see dai::calcLinearState(), dai::calcState()
312 *
313 * \idea Make the State class a more prominent part of libDAI
314 * (and document it clearly, explaining the concept of state);
315 * add more optimized variants of the State class like IndexFor
316 * (e.g. for TFactor<>::slice()).
317 */
318 class State {
319 private:
320 /// Type for representing a joint state of some variables as a map, which maps each variable to its state
321 typedef std::map<Var, size_t> states_type;
322
323 /// Current state (represented linearly)
324 long state;
325
326 /// Current state (represented as a map)
327 states_type states;
328
329 public:
330 /// Default constructor
331 State() : state(0), states() {}
332
333 /// Construct from VarSet \a vs and corresponding linear state \a linearState
334 State( const VarSet &vs, size_t linearState=0 ) : state(linearState), states() {
335 if( linearState == 0 )
336 for( VarSet::const_iterator v = vs.begin(); v != vs.end(); v++ )
337 states[*v] = 0;
338 else {
339 for( VarSet::const_iterator v = vs.begin(); v != vs.end(); v++ ) {
340 states[*v] = linearState % v->states();
341 linearState /= v->states();
342 }
343 DAI_ASSERT( linearState == 0 );
344 }
345 }
346
347 /// Construct from a std::map<Var, size_t>
348 State( const std::map<Var, size_t> &s ) : state(0), states() {
349 insert( s.begin(), s.end() );
350 }
351
352 /// Constant iterator over the values
353 typedef states_type::const_iterator const_iterator;
354
355 /// Returns constant iterator that points to the first item
356 const_iterator begin() const { return states.begin(); }
357
358 /// Returns constant iterator that points beyond the last item
359 const_iterator end() const { return states.end(); }
360
361 /// Return current linear state
362 operator size_t() const {
363 DAI_ASSERT( valid() );
364 return( state );
365 }
366
367 /// Inserts a range of variable-state pairs, changing the current state
368 template<typename InputIterator>
369 void insert( InputIterator b, InputIterator e ) {
370 states.insert( b, e );
371 VarSet vars;
372 for( const_iterator it = begin(); it != end(); it++ )
373 vars |= it->first;
374 state = 0;
375 state = this->operator()( vars );
376 }
377
378 /// Return current state represented as a map
379 const std::map<Var,size_t>& get() const { return states; }
380
381 /// Cast into std::map<Var, size_t>
382 operator const std::map<Var,size_t>& () const { return states; }
383
384 /// Return current state of variable \a v, or 0 if \a v is not in \c *this
385 size_t operator() ( const Var &v ) const {
386 DAI_ASSERT( valid() );
387 states_type::const_iterator entry = states.find( v );
388 if( entry == states.end() )
389 return 0;
390 else
391 return entry->second;
392 }
393
394 /// Return linear state of variables in \a vs, assuming that variables that are not in \c *this are in state 0
395 size_t operator() ( const VarSet &vs ) const {
396 DAI_ASSERT( valid() );
397 size_t vs_state = 0;
398 size_t prod = 1;
399 for( VarSet::const_iterator v = vs.begin(); v != vs.end(); v++ ) {
400 states_type::const_iterator entry = states.find( *v );
401 if( entry != states.end() )
402 vs_state += entry->second * prod;
403 prod *= v->states();
404 }
405 return vs_state;
406 }
407
408 /// Increments the current state (prefix)
409 void operator++( ) {
410 if( valid() ) {
411 state++;
412 states_type::iterator entry = states.begin();
413 while( entry != states.end() ) {
414 if( ++(entry->second) < entry->first.states() )
415 break;
416 entry->second = 0;
417 entry++;
418 }
419 if( entry == states.end() )
420 state = -1;
421 }
422 }
423
424 /// Increments the current state (postfix)
425 void operator++( int ) {
426 operator++();
427 }
428
429 /// Returns \c true if the current state is valid
430 bool valid() const {
431 return( state >= 0 );
432 }
433
434 /// Resets the current state (to the joint state represented by linear state 0)
435 void reset() {
436 state = 0;
437 for( states_type::iterator s = states.begin(); s != states.end(); s++ )
438 s->second = 0;
439 }
440 };
441
442
443 } // end of namespace dai
444
445
446 /** \example example_permute.cpp
447 * This example shows how to use the Permute, multifor and State classes.
448 *
449 * \section Output
450 * \verbinclude examples/example_permute.out
451 *
452 * \section Source
453 */
454
455
456 #endif