Location: LEMON/LEMON-official/lemon/min_mean_cycle.h

Load file history
gravatar
kpeter (Peter Kovacs)
Port MinMeanCycle from SVN -r3524 (#179) with some doc improvements
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 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
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
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
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
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
456
457
458
459
460
461
462
/* -*- C++ -*-
*
* This file is a part of LEMON, a generic C++ optimization library
*
* Copyright (C) 2003-2008
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
* (Egervary Research Group on Combinatorial Optimization, EGRES).
*
* Permission to use, modify and distribute this software is granted
* provided that this copyright notice appears in all copies. For
* precise terms see the accompanying LICENSE file.
*
* This software is provided "AS IS" with no warranty of any kind,
* express or implied, and with no claim as to its suitability for any
* purpose.
*
*/
#ifndef LEMON_MIN_MEAN_CYCLE_H
#define LEMON_MIN_MEAN_CYCLE_H
/// \ingroup shortest_path
///
/// \file
/// \brief Howard's algorithm for finding a minimum mean cycle.
#include <vector>
#include <lemon/core.h>
#include <lemon/path.h>
#include <lemon/tolerance.h>
#include <lemon/connectivity.h>
namespace lemon {
/// \addtogroup shortest_path
/// @{
/// \brief Implementation of Howard's algorithm for finding a minimum
/// mean cycle.
///
/// \ref MinMeanCycle implements Howard's algorithm for finding a
/// directed cycle of minimum mean length (cost) in a digraph.
///
/// \tparam GR The type of the digraph the algorithm runs on.
/// \tparam LEN The type of the length map. The default
/// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
///
/// \warning \c LEN::Value must be convertible to \c double.
#ifdef DOXYGEN
template <typename GR, typename LEN>
#else
template < typename GR,
typename LEN = typename GR::template ArcMap<int> >
#endif
class MinMeanCycle
{
public:
/// The type of the digraph the algorithm runs on
typedef GR Digraph;
/// The type of the length map
typedef LEN LengthMap;
/// The type of the arc lengths
typedef typename LengthMap::Value Value;
/// The type of the paths
typedef lemon::Path<Digraph> Path;
private:
TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
// The digraph the algorithm runs on
const Digraph &_gr;
// The length of the arcs
const LengthMap &_length;
// The total length of the found cycle
Value _cycle_length;
// The number of arcs on the found cycle
int _cycle_size;
// The found cycle
Path *_cycle_path;
bool _local_path;
bool _cycle_found;
Node _cycle_node;
typename Digraph::template NodeMap<bool> _reached;
typename Digraph::template NodeMap<double> _dist;
typename Digraph::template NodeMap<Arc> _policy;
typename Digraph::template NodeMap<int> _comp;
int _comp_num;
std::vector<Node> _nodes;
std::vector<Arc> _arcs;
Tolerance<double> _tol;
public:
/// \brief Constructor.
///
/// The constructor of the class.
///
/// \param digraph The digraph the algorithm runs on.
/// \param length The lengths (costs) of the arcs.
MinMeanCycle( const Digraph &digraph,
const LengthMap &length ) :
_gr(digraph), _length(length), _cycle_length(0), _cycle_size(-1),
_cycle_path(NULL), _local_path(false), _reached(digraph),
_dist(digraph), _policy(digraph), _comp(digraph)
{}
/// Destructor.
~MinMeanCycle() {
if (_local_path) delete _cycle_path;
}
/// \brief Set the path structure for storing the found cycle.
///
/// This function sets an external path structure for storing the
/// found cycle.
///
/// If you don't call this function before calling \ref run() or
/// \ref init(), it will allocate a local \ref Path "path"
/// structure. The destuctor deallocates this automatically
/// allocated object, of course.
///
/// \note The algorithm calls only the \ref lemon::Path::addBack()
/// "addBack()" function of the given path structure.
///
/// \return <tt>(*this)</tt>
///
/// \sa cycle()
MinMeanCycle& cyclePath(Path &path) {
if (_local_path) {
delete _cycle_path;
_local_path = false;
}
_cycle_path = &path;
return *this;
}
/// \name Execution control
/// The simplest way to execute the algorithm is to call the \ref run()
/// function.\n
/// If you only need the minimum mean length, you may call \ref init()
/// and \ref findMinMean().
/// If you would like to run the algorithm again (e.g. the underlying
/// digraph and/or the arc lengths has been modified), you may not
/// create a new instance of the class, rather call \ref reset(),
/// \ref findMinMean() and \ref findCycle() instead.
/// @{
/// \brief Run the algorithm.
///
/// This function runs the algorithm.
///
/// \return \c true if a directed cycle exists in the digraph.
///
/// \note Apart from the return value, <tt>mmc.run()</tt> is just a
/// shortcut of the following code.
/// \code
/// mmc.init();
/// mmc.findMinMean();
/// mmc.findCycle();
/// \endcode
bool run() {
init();
return findMinMean() && findCycle();
}
/// \brief Initialize the internal data structures.
///
/// This function initializes the internal data structures.
///
/// \sa reset()
void init() {
_tol.epsilon(1e-6);
if (!_cycle_path) {
_local_path = true;
_cycle_path = new Path;
}
_cycle_found = false;
_comp_num = stronglyConnectedComponents(_gr, _comp);
}
/// \brief Reset the internal data structures.
///
/// This function resets the internal data structures so that
/// findMinMean() and findCycle() can be called again (e.g. when the
/// underlying digraph and/or the arc lengths has been modified).
///
/// \sa init()
void reset() {
if (_cycle_path) _cycle_path->clear();
_cycle_found = false;
_comp_num = stronglyConnectedComponents(_gr, _comp);
}
/// \brief Find the minimum cycle mean.
///
/// This function computes all the required data and finds the
/// minimum mean length of the directed cycles in the digraph.
///
/// \return \c true if a directed cycle exists in the digraph.
///
/// \pre \ref init() must be called before using this function.
bool findMinMean() {
// Find the minimum cycle mean in the components
for (int comp = 0; comp < _comp_num; ++comp) {
if (!initCurrentComponent(comp)) continue;
while (true) {
if (!findPolicyCycles()) break;
contractPolicyGraph(comp);
if (!computeNodeDistances()) break;
}
}
return _cycle_found;
}
/// \brief Find a minimum mean directed cycle.
///
/// This function finds a directed cycle of minimum mean length
/// in the digraph using the data computed by findMinMean().
///
/// \return \c true if a directed cycle exists in the digraph.
///
/// \pre \ref init() and \ref findMinMean() must be called before
/// using this function.
bool findCycle() {
if (!_cycle_found) return false;
_cycle_path->addBack(_policy[_cycle_node]);
for ( Node v = _cycle_node;
(v = _gr.target(_policy[v])) != _cycle_node; ) {
_cycle_path->addBack(_policy[v]);
}
return true;
}
/// @}
/// \name Query Functions
/// The result of the algorithm can be obtained using these
/// functions.\n
/// The algorithm should be executed before using them.
/// @{
/// \brief Return the total length of the found cycle.
///
/// This function returns the total length of the found cycle.
///
/// \pre \ref run() or \ref findCycle() must be called before
/// using this function.
Value cycleLength() const {
return _cycle_length;
}
/// \brief Return the number of arcs on the found cycle.
///
/// This function returns the number of arcs on the found cycle.
///
/// \pre \ref run() or \ref findCycle() must be called before
/// using this function.
int cycleArcNum() const {
return _cycle_size;
}
/// \brief Return the mean length of the found cycle.
///
/// This function returns the mean length of the found cycle.
///
/// \note <tt>mmc.cycleMean()</tt> is just a shortcut of the
/// following code.
/// \code
/// return double(mmc.cycleLength()) / mmc.cycleArcNum();
/// \endcode
///
/// \pre \ref run() or \ref findMinMean() must be called before
/// using this function.
double cycleMean() const {
return double(_cycle_length) / _cycle_size;
}
/// \brief Return the found cycle.
///
/// This function returns a const reference to the path structure
/// storing the found cycle.
///
/// \pre \ref run() or \ref findCycle() must be called before using
/// this function.
///
/// \sa cyclePath()
const Path& cycle() const {
return *_cycle_path;
}
///@}
private:
// Initialize the internal data structures for the current strongly
// connected component and create the policy graph.
// The policy graph can be represented by the _policy map because
// the out-degree of every node is 1.
bool initCurrentComponent(int comp) {
// Find the nodes of the current component
_nodes.clear();
for (NodeIt n(_gr); n != INVALID; ++n) {
if (_comp[n] == comp) _nodes.push_back(n);
}
if (_nodes.size() <= 1) return false;
// Find the arcs of the current component
_arcs.clear();
for (ArcIt e(_gr); e != INVALID; ++e) {
if ( _comp[_gr.source(e)] == comp &&
_comp[_gr.target(e)] == comp )
_arcs.push_back(e);
}
// Initialize _reached, _dist, _policy maps
for (int i = 0; i < int(_nodes.size()); ++i) {
_reached[_nodes[i]] = false;
_policy[_nodes[i]] = INVALID;
}
Node u; Arc e;
for (int j = 0; j < int(_arcs.size()); ++j) {
e = _arcs[j];
u = _gr.source(e);
if (!_reached[u] || _length[e] < _dist[u]) {
_dist[u] = _length[e];
_policy[u] = e;
_reached[u] = true;
}
}
return true;
}
// Find all cycles in the policy graph.
// Set _cycle_found to true if a cycle is found and set
// _cycle_length, _cycle_size, _cycle_node to represent the minimum
// mean cycle in the policy graph.
bool findPolicyCycles() {
typename Digraph::template NodeMap<int> level(_gr, -1);
bool curr_cycle_found = false;
Value clength;
int csize;
int path_cnt = 0;
Node u, v;
// Searching for cycles
for (int i = 0; i < int(_nodes.size()); ++i) {
if (level[_nodes[i]] < 0) {
u = _nodes[i];
level[u] = path_cnt;
while (level[u = _gr.target(_policy[u])] < 0)
level[u] = path_cnt;
if (level[u] == path_cnt) {
// A cycle is found
curr_cycle_found = true;
clength = _length[_policy[u]];
csize = 1;
for (v = u; (v = _gr.target(_policy[v])) != u; ) {
clength += _length[_policy[v]];
++csize;
}
if ( !_cycle_found ||
clength * _cycle_size < _cycle_length * csize ) {
_cycle_found = true;
_cycle_length = clength;
_cycle_size = csize;
_cycle_node = u;
}
}
++path_cnt;
}
}
return curr_cycle_found;
}
// Contract the policy graph to be connected by cutting all cycles
// except for the main cycle (i.e. the minimum mean cycle).
void contractPolicyGraph(int comp) {
// Find the component of the main cycle using reverse BFS search
typename Digraph::template NodeMap<int> found(_gr, false);
std::deque<Node> queue;
queue.push_back(_cycle_node);
found[_cycle_node] = true;
Node u, v;
while (!queue.empty()) {
v = queue.front(); queue.pop_front();
for (InArcIt e(_gr, v); e != INVALID; ++e) {
u = _gr.source(e);
if (_policy[u] == e && !found[u]) {
found[u] = true;
queue.push_back(u);
}
}
}
// Connect all other nodes to this component using reverse BFS search
queue.clear();
for (int i = 0; i < int(_nodes.size()); ++i)
if (found[_nodes[i]]) queue.push_back(_nodes[i]);
int found_cnt = queue.size();
while (found_cnt < int(_nodes.size())) {
v = queue.front(); queue.pop_front();
for (InArcIt e(_gr, v); e != INVALID; ++e) {
u = _gr.source(e);
if (_comp[u] == comp && !found[u]) {
found[u] = true;
++found_cnt;
_policy[u] = e;
queue.push_back(u);
}
}
}
}
// Compute node distances in the policy graph and update the
// policy graph if the node distances can be improved.
bool computeNodeDistances() {
// Compute node distances using reverse BFS search
double cycle_mean = double(_cycle_length) / _cycle_size;
typename Digraph::template NodeMap<int> found(_gr, false);
std::deque<Node> queue;
queue.push_back(_cycle_node);
found[_cycle_node] = true;
_dist[_cycle_node] = 0;
Node u, v;
while (!queue.empty()) {
v = queue.front(); queue.pop_front();
for (InArcIt e(_gr, v); e != INVALID; ++e) {
u = _gr.source(e);
if (_policy[u] == e && !found[u]) {
found[u] = true;
_dist[u] = _dist[v] + _length[e] - cycle_mean;
queue.push_back(u);
}
}
}
// Improving node distances
bool improved = false;
for (int j = 0; j < int(_arcs.size()); ++j) {
Arc e = _arcs[j];
u = _gr.source(e); v = _gr.target(e);
double delta = _dist[v] + _length[e] - cycle_mean;
if (_tol.less(delta, _dist[u])) {
improved = true;
_dist[u] = delta;
_policy[u] = e;
}
}
return improved;
}
}; //class MinMeanCycle
///@}
} //namespace lemon
#endif //LEMON_MIN_MEAN_CYCLE_H