↑ Collapse diff ↑
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_BIN_HEAP_H
20 20
#define LEMON_BIN_HEAP_H
21 21

	
22 22
///\ingroup auxdat
23 23
///\file
24 24
///\brief Binary Heap implementation.
25 25

	
26 26
#include <vector>
27 27
#include <utility>
28 28
#include <functional>
29 29

	
30 30
namespace lemon {
31 31

	
32 32
  ///\ingroup auxdat
33 33
  ///
34 34
  ///\brief A Binary Heap implementation.
35 35
  ///
36 36
  ///This class implements the \e binary \e heap data structure. 
37 37
  /// 
38 38
  ///A \e heap is a data structure for storing items with specified values
39 39
  ///called \e priorities in such a way that finding the item with minimum
40 40
  ///priority is efficient. \c Comp specifies the ordering of the priorities.
41 41
  ///In a heap one can change the priority of an item, add or erase an
42 42
  ///item, etc.
43 43
  ///
44 44
  ///\tparam PR Type of the priority of the items.
45 45
  ///\tparam IM A read and writable item map with int values, used internally
46 46
  ///to handle the cross references.
47 47
  ///\tparam Comp A functor class for the ordering of the priorities.
48 48
  ///The default is \c std::less<PR>.
49 49
  ///
50 50
  ///\sa FibHeap
51 51
  ///\sa Dijkstra
52 52
  template <typename PR, typename IM, typename Comp = std::less<PR> >
53 53
  class BinHeap {
54 54

	
55 55
  public:
56 56
    ///\e
57 57
    typedef IM ItemIntMap;
58 58
    ///\e
59 59
    typedef PR Prio;
60 60
    ///\e
61 61
    typedef typename ItemIntMap::Key Item;
62 62
    ///\e
63 63
    typedef std::pair<Item,Prio> Pair;
64 64
    ///\e
65 65
    typedef Comp Compare;
66 66

	
67 67
    /// \brief Type to represent the items states.
68 68
    ///
69 69
    /// Each Item element have a state associated to it. It may be "in heap",
70 70
    /// "pre heap" or "post heap". The latter two are indifferent from the
71 71
    /// heap's point of view, but may be useful to the user.
72 72
    ///
73 73
    /// The item-int map must be initialized in such way that it assigns
74 74
    /// \c PRE_HEAP (<tt>-1</tt>) to any element to be put in the heap.
75 75
    enum State {
76
      IN_HEAP = 0,    ///< \e
77
      PRE_HEAP = -1,  ///< \e
78
      POST_HEAP = -2  ///< \e
76
      IN_HEAP = 0,    ///< = 0.
77
      PRE_HEAP = -1,  ///< = -1.
78
      POST_HEAP = -2  ///< = -2.
79 79
    };
80 80

	
81 81
  private:
82 82
    std::vector<Pair> _data;
83 83
    Compare _comp;
84 84
    ItemIntMap &_iim;
85 85

	
86 86
  public:
87 87
    /// \brief The constructor.
88 88
    ///
89 89
    /// The constructor.
90 90
    /// \param map should be given to the constructor, since it is used
91 91
    /// internally to handle the cross references. The value of the map
92 92
    /// must be \c PRE_HEAP (<tt>-1</tt>) for every item.
93 93
    explicit BinHeap(ItemIntMap &map) : _iim(map) {}
94 94

	
95 95
    /// \brief The constructor.
96 96
    ///
97 97
    /// The constructor.
98 98
    /// \param map should be given to the constructor, since it is used
99 99
    /// internally to handle the cross references. The value of the map
100 100
    /// should be PRE_HEAP (-1) for each element.
101 101
    ///
102 102
    /// \param comp The comparator function object.
103 103
    BinHeap(ItemIntMap &map, const Compare &comp)
104 104
      : _iim(map), _comp(comp) {}
105 105

	
106 106

	
107 107
    /// The number of items stored in the heap.
108 108
    ///
109 109
    /// \brief Returns the number of items stored in the heap.
110 110
    int size() const { return _data.size(); }
111 111

	
112 112
    /// \brief Checks if the heap stores no items.
113 113
    ///
114 114
    /// Returns \c true if and only if the heap stores no items.
115 115
    bool empty() const { return _data.empty(); }
116 116

	
117 117
    /// \brief Make empty this heap.
118 118
    ///
119 119
    /// Make empty this heap. It does not change the cross reference map.
120 120
    /// If you want to reuse what is not surely empty you should first clear
121 121
    /// the heap and after that you should set the cross reference map for
122 122
    /// each item to \c PRE_HEAP.
123 123
    void clear() {
124 124
      _data.clear();
125 125
    }
126 126

	
127 127
  private:
128 128
    static int parent(int i) { return (i-1)/2; }
129 129

	
130 130
    static int second_child(int i) { return 2*i+2; }
131 131
    bool less(const Pair &p1, const Pair &p2) const {
132 132
      return _comp(p1.second, p2.second);
133 133
    }
134 134

	
135 135
    int bubble_up(int hole, Pair p) {
136 136
      int par = parent(hole);
137 137
      while( hole>0 && less(p,_data[par]) ) {
138 138
        move(_data[par],hole);
139 139
        hole = par;
140 140
        par = parent(hole);
141 141
      }
142 142
      move(p, hole);
143 143
      return hole;
144 144
    }
145 145

	
146 146
    int bubble_down(int hole, Pair p, int length) {
147 147
      int child = second_child(hole);
148 148
      while(child < length) {
149 149
        if( less(_data[child-1], _data[child]) ) {
150 150
          --child;
151 151
        }
152 152
        if( !less(_data[child], p) )
153 153
          goto ok;
154 154
        move(_data[child], hole);
155 155
        hole = child;
156 156
        child = second_child(hole);
157 157
      }
158 158
      child--;
159 159
      if( child<length && less(_data[child], p) ) {
160 160
        move(_data[child], hole);
161 161
        hole=child;
162 162
      }
163 163
    ok:
164 164
      move(p, hole);
165 165
      return hole;
166 166
    }
167 167

	
168 168
    void move(const Pair &p, int i) {
169 169
      _data[i] = p;
170 170
      _iim.set(p.first, i);
171 171
    }
172 172

	
173 173
  public:
174 174
    /// \brief Insert a pair of item and priority into the heap.
175 175
    ///
176 176
    /// Adds \c p.first to the heap with priority \c p.second.
177 177
    /// \param p The pair to insert.
178 178
    void push(const Pair &p) {
179 179
      int n = _data.size();
180 180
      _data.resize(n+1);
181 181
      bubble_up(n, p);
182 182
    }
183 183

	
184 184
    /// \brief Insert an item into the heap with the given heap.
185 185
    ///
186 186
    /// Adds \c i to the heap with priority \c p.
187 187
    /// \param i The item to insert.
188 188
    /// \param p The priority of the item.
189 189
    void push(const Item &i, const Prio &p) { push(Pair(i,p)); }
190 190

	
191 191
    /// \brief Returns the item with minimum priority relative to \c Compare.
192 192
    ///
193 193
    /// This method returns the item with minimum priority relative to \c
194 194
    /// Compare.
195 195
    /// \pre The heap must be nonempty.
196 196
    Item top() const {
197 197
      return _data[0].first;
198 198
    }
199 199

	
200 200
    /// \brief Returns the minimum priority relative to \c Compare.
201 201
    ///
202 202
    /// It returns the minimum priority relative to \c Compare.
203 203
    /// \pre The heap must be nonempty.
204 204
    Prio prio() const {
205 205
      return _data[0].second;
206 206
    }
207 207

	
208 208
    /// \brief Deletes the item with minimum priority relative to \c Compare.
209 209
    ///
210 210
    /// This method deletes the item with minimum priority relative to \c
211 211
    /// Compare from the heap.
212 212
    /// \pre The heap must be non-empty.
213 213
    void pop() {
214 214
      int n = _data.size()-1;
215 215
      _iim.set(_data[0].first, POST_HEAP);
216 216
      if (n > 0) {
217 217
        bubble_down(0, _data[n], n);
218 218
      }
219 219
      _data.pop_back();
220 220
    }
221 221

	
222 222
    /// \brief Deletes \c i from the heap.
223 223
    ///
224 224
    /// This method deletes item \c i from the heap.
225 225
    /// \param i The item to erase.
226 226
    /// \pre The item should be in the heap.
227 227
    void erase(const Item &i) {
228 228
      int h = _iim[i];
229 229
      int n = _data.size()-1;
230 230
      _iim.set(_data[h].first, POST_HEAP);
231 231
      if( h < n ) {
232 232
        if ( bubble_up(h, _data[n]) == h) {
233 233
          bubble_down(h, _data[n], n);
234 234
        }
235 235
      }
236 236
      _data.pop_back();
237 237
    }
238 238

	
239 239

	
240 240
    /// \brief Returns the priority of \c i.
241 241
    ///
242 242
    /// This function returns the priority of item \c i.
243 243
    /// \param i The item.
244 244
    /// \pre \c i must be in the heap.
245 245
    Prio operator[](const Item &i) const {
246 246
      int idx = _iim[i];
247 247
      return _data[idx].second;
248 248
    }
249 249

	
250 250
    /// \brief \c i gets to the heap with priority \c p independently
251 251
    /// if \c i was already there.
252 252
    ///
253 253
    /// This method calls \ref push(\c i, \c p) if \c i is not stored
254 254
    /// in the heap and sets the priority of \c i to \c p otherwise.
255 255
    /// \param i The item.
256 256
    /// \param p The priority.
257 257
    void set(const Item &i, const Prio &p) {
258 258
      int idx = _iim[i];
259 259
      if( idx < 0 ) {
260 260
        push(i,p);
261 261
      }
262 262
      else if( _comp(p, _data[idx].second) ) {
263 263
        bubble_up(idx, Pair(i,p));
264 264
      }
265 265
      else {
266 266
        bubble_down(idx, Pair(i,p), _data.size());
267 267
      }
268 268
    }
269 269

	
270 270
    /// \brief Decreases the priority of \c i to \c p.
271 271
    ///
272 272
    /// This method decreases the priority of item \c i to \c p.
273 273
    /// \param i The item.
274 274
    /// \param p The priority.
275 275
    /// \pre \c i must be stored in the heap with priority at least \c
276 276
    /// p relative to \c Compare.
277 277
    void decrease(const Item &i, const Prio &p) {
278 278
      int idx = _iim[i];
279 279
      bubble_up(idx, Pair(i,p));
280 280
    }
281 281

	
282 282
    /// \brief Increases the priority of \c i to \c p.
283 283
    ///
284 284
    /// This method sets the priority of item \c i to \c p.
285 285
    /// \param i The item.
286 286
    /// \param p The priority.
287 287
    /// \pre \c i must be stored in the heap with priority at most \c
288 288
    /// p relative to \c Compare.
289 289
    void increase(const Item &i, const Prio &p) {
290 290
      int idx = _iim[i];
291 291
      bubble_down(idx, Pair(i,p), _data.size());
292 292
    }
293 293

	
294 294
    /// \brief Returns if \c item is in, has already been in, or has
295 295
    /// never been in the heap.
296 296
    ///
297 297
    /// This method returns PRE_HEAP if \c item has never been in the
298 298
    /// heap, IN_HEAP if it is in the heap at the moment, and POST_HEAP
299 299
    /// otherwise. In the latter case it is possible that \c item will
300 300
    /// get back to the heap again.
301 301
    /// \param i The item.
302 302
    State state(const Item &i) const {
303 303
      int s = _iim[i];
304 304
      if( s>=0 )
305 305
        s=0;
306 306
      return State(s);
307 307
    }
308 308

	
309 309
    /// \brief Sets the state of the \c item in the heap.
310 310
    ///
311 311
    /// Sets the state of the \c item in the heap. It can be used to
312 312
    /// manually clear the heap when it is important to achive the
313 313
    /// better time complexity.
314 314
    /// \param i The item.
315 315
    /// \param st The state. It should not be \c IN_HEAP.
316 316
    void state(const Item& i, State st) {
317 317
      switch (st) {
318 318
      case POST_HEAP:
319 319
      case PRE_HEAP:
320 320
        if (state(i) == IN_HEAP) {
321 321
          erase(i);
322 322
        }
323 323
        _iim[i] = st;
324 324
        break;
325 325
      case IN_HEAP:
326 326
        break;
327 327
      }
328 328
    }
329 329

	
330 330
    /// \brief Replaces an item in the heap.
331 331
    ///
332 332
    /// The \c i item is replaced with \c j item. The \c i item should
333 333
    /// be in the heap, while the \c j should be out of the heap. The
334 334
    /// \c i item will out of the heap and \c j will be in the heap
Ignore white space 6 line context
... ...
@@ -349,729 +349,729 @@
349 349

	
350 350
        void constraints() {
351 351
          checkConcept<Base, _Digraph >();
352 352
          typename _Digraph::Node node;
353 353
          int nid = digraph.id(node);
354 354
          nid = digraph.id(node);
355 355
          node = digraph.nodeFromId(nid);
356 356
          typename _Digraph::Arc arc;
357 357
          int eid = digraph.id(arc);
358 358
          eid = digraph.id(arc);
359 359
          arc = digraph.arcFromId(eid);
360 360

	
361 361
          nid = digraph.maxNodeId();
362 362
          ignore_unused_variable_warning(nid);
363 363
          eid = digraph.maxArcId();
364 364
          ignore_unused_variable_warning(eid);
365 365
        }
366 366

	
367 367
        const _Digraph& digraph;
368 368
      };
369 369
    };
370 370

	
371 371
    /// \brief Skeleton class for \e idable undirected graphs.
372 372
    ///
373 373
    /// This class describes the interface of \e idable undirected
374 374
    /// graphs. It extends \ref IDableDigraphComponent with the core ID
375 375
    /// functions of undirected graphs.
376 376
    /// The ids of the items must be unique and immutable.
377 377
    /// This concept is part of the Graph concept.
378 378
    template <typename BAS = BaseGraphComponent>
379 379
    class IDableGraphComponent : public IDableDigraphComponent<BAS> {
380 380
    public:
381 381

	
382 382
      typedef BAS Base;
383 383
      typedef typename Base::Edge Edge;
384 384

	
385 385
      using IDableDigraphComponent<Base>::id;
386 386

	
387 387
      /// \brief Return a unique integer id for the given edge.
388 388
      ///
389 389
      /// This function returns a unique integer id for the given edge.
390 390
      int id(const Edge&) const { return -1; }
391 391

	
392 392
      /// \brief Return the edge by its unique id.
393 393
      ///
394 394
      /// This function returns the edge by its unique id.
395 395
      /// If the graph does not contain an edge with the given id,
396 396
      /// then the result of the function is undefined.
397 397
      Edge edgeFromId(int) const { return INVALID; }
398 398

	
399 399
      /// \brief Return an integer greater or equal to the maximum
400 400
      /// edge id.
401 401
      ///
402 402
      /// This function returns an integer greater or equal to the
403 403
      /// maximum edge id.
404 404
      int maxEdgeId() const { return -1; }
405 405

	
406 406
      template <typename _Graph>
407 407
      struct Constraints {
408 408

	
409 409
        void constraints() {
410 410
          checkConcept<IDableDigraphComponent<Base>, _Graph >();
411 411
          typename _Graph::Edge edge;
412 412
          int ueid = graph.id(edge);
413 413
          ueid = graph.id(edge);
414 414
          edge = graph.edgeFromId(ueid);
415 415
          ueid = graph.maxEdgeId();
416 416
          ignore_unused_variable_warning(ueid);
417 417
        }
418 418

	
419 419
        const _Graph& graph;
420 420
      };
421 421
    };
422 422

	
423 423
    /// \brief Concept class for \c NodeIt, \c ArcIt and \c EdgeIt types.
424 424
    ///
425 425
    /// This class describes the concept of \c NodeIt, \c ArcIt and 
426 426
    /// \c EdgeIt subtypes of digraph and graph types.
427 427
    template <typename GR, typename Item>
428 428
    class GraphItemIt : public Item {
429 429
    public:
430 430
      /// \brief Default constructor.
431 431
      ///
432 432
      /// Default constructor.
433 433
      /// \warning The default constructor is not required to set
434 434
      /// the iterator to some well-defined value. So you should consider it
435 435
      /// as uninitialized.
436 436
      GraphItemIt() {}
437 437

	
438 438
      /// \brief Copy constructor.
439 439
      ///
440 440
      /// Copy constructor.
441 441
      GraphItemIt(const GraphItemIt& it) : Item(it) {}
442 442

	
443 443
      /// \brief Constructor that sets the iterator to the first item.
444 444
      ///
445 445
      /// Constructor that sets the iterator to the first item.
446 446
      explicit GraphItemIt(const GR&) {}
447 447

	
448 448
      /// \brief Constructor for conversion from \c INVALID.
449 449
      ///
450 450
      /// Constructor for conversion from \c INVALID.
451 451
      /// It initializes the iterator to be invalid.
452 452
      /// \sa Invalid for more details.
453 453
      GraphItemIt(Invalid) {}
454 454

	
455 455
      /// \brief Assignment operator.
456 456
      ///
457 457
      /// Assignment operator for the iterator.
458 458
      GraphItemIt& operator=(const GraphItemIt&) { return *this; }
459 459

	
460 460
      /// \brief Increment the iterator.
461 461
      ///
462 462
      /// This operator increments the iterator, i.e. assigns it to the
463 463
      /// next item.
464 464
      GraphItemIt& operator++() { return *this; }
465 465
 
466 466
      /// \brief Equality operator
467 467
      ///
468 468
      /// Equality operator.
469 469
      /// Two iterators are equal if and only if they point to the
470 470
      /// same object or both are invalid.
471 471
      bool operator==(const GraphItemIt&) const { return true;}
472 472

	
473 473
      /// \brief Inequality operator
474 474
      ///
475 475
      /// Inequality operator.
476 476
      /// Two iterators are equal if and only if they point to the
477 477
      /// same object or both are invalid.
478 478
      bool operator!=(const GraphItemIt&) const { return true;}
479 479

	
480 480
      template<typename _GraphItemIt>
481 481
      struct Constraints {
482 482
        void constraints() {
483 483
          checkConcept<GraphItem<>, _GraphItemIt>();
484 484
          _GraphItemIt it1(g);
485 485
          _GraphItemIt it2;
486 486
          _GraphItemIt it3 = it1;
487 487
          _GraphItemIt it4 = INVALID;
488 488

	
489 489
          it2 = ++it1;
490 490
          ++it2 = it1;
491 491
          ++(++it1);
492 492

	
493 493
          Item bi = it1;
494 494
          bi = it2;
495 495
        }
496 496
        const GR& g;
497 497
      };
498 498
    };
499 499

	
500 500
    /// \brief Concept class for \c InArcIt, \c OutArcIt and 
501 501
    /// \c IncEdgeIt types.
502 502
    ///
503 503
    /// This class describes the concept of \c InArcIt, \c OutArcIt 
504 504
    /// and \c IncEdgeIt subtypes of digraph and graph types.
505 505
    ///
506 506
    /// \note Since these iterator classes do not inherit from the same
507 507
    /// base class, there is an additional template parameter (selector)
508 508
    /// \c sel. For \c InArcIt you should instantiate it with character 
509 509
    /// \c 'i', for \c OutArcIt with \c 'o' and for \c IncEdgeIt with \c 'e'.
510 510
    template <typename GR,
511 511
              typename Item = typename GR::Arc,
512 512
              typename Base = typename GR::Node,
513 513
              char sel = '0'>
514 514
    class GraphIncIt : public Item {
515 515
    public:
516 516
      /// \brief Default constructor.
517 517
      ///
518 518
      /// Default constructor.
519 519
      /// \warning The default constructor is not required to set
520 520
      /// the iterator to some well-defined value. So you should consider it
521 521
      /// as uninitialized.
522 522
      GraphIncIt() {}
523 523

	
524 524
      /// \brief Copy constructor.
525 525
      ///
526 526
      /// Copy constructor.
527 527
      GraphIncIt(const GraphIncIt& it) : Item(it) {}
528 528

	
529 529
      /// \brief Constructor that sets the iterator to the first 
530 530
      /// incoming or outgoing arc.
531 531
      ///
532 532
      /// Constructor that sets the iterator to the first arc 
533 533
      /// incoming to or outgoing from the given node.
534 534
      explicit GraphIncIt(const GR&, const Base&) {}
535 535

	
536 536
      /// \brief Constructor for conversion from \c INVALID.
537 537
      ///
538 538
      /// Constructor for conversion from \c INVALID.
539 539
      /// It initializes the iterator to be invalid.
540 540
      /// \sa Invalid for more details.
541 541
      GraphIncIt(Invalid) {}
542 542

	
543 543
      /// \brief Assignment operator.
544 544
      ///
545 545
      /// Assignment operator for the iterator.
546 546
      GraphIncIt& operator=(const GraphIncIt&) { return *this; }
547 547

	
548 548
      /// \brief Increment the iterator.
549 549
      ///
550 550
      /// This operator increments the iterator, i.e. assigns it to the
551 551
      /// next arc incoming to or outgoing from the given node.
552 552
      GraphIncIt& operator++() { return *this; }
553 553

	
554 554
      /// \brief Equality operator
555 555
      ///
556 556
      /// Equality operator.
557 557
      /// Two iterators are equal if and only if they point to the
558 558
      /// same object or both are invalid.
559 559
      bool operator==(const GraphIncIt&) const { return true;}
560 560

	
561 561
      /// \brief Inequality operator
562 562
      ///
563 563
      /// Inequality operator.
564 564
      /// Two iterators are equal if and only if they point to the
565 565
      /// same object or both are invalid.
566 566
      bool operator!=(const GraphIncIt&) const { return true;}
567 567

	
568 568
      template <typename _GraphIncIt>
569 569
      struct Constraints {
570 570
        void constraints() {
571 571
          checkConcept<GraphItem<sel>, _GraphIncIt>();
572 572
          _GraphIncIt it1(graph, node);
573 573
          _GraphIncIt it2;
574 574
          _GraphIncIt it3 = it1;
575 575
          _GraphIncIt it4 = INVALID;
576 576

	
577 577
          it2 = ++it1;
578 578
          ++it2 = it1;
579 579
          ++(++it1);
580 580
          Item e = it1;
581 581
          e = it2;
582 582
        }
583 583
        const Base& node;
584 584
        const GR& graph;
585 585
      };
586 586
    };
587 587

	
588 588
    /// \brief Skeleton class for iterable directed graphs.
589 589
    ///
590 590
    /// This class describes the interface of iterable directed
591 591
    /// graphs. It extends \ref BaseDigraphComponent with the core
592 592
    /// iterable interface.
593 593
    /// This concept is part of the Digraph concept.
594 594
    template <typename BAS = BaseDigraphComponent>
595 595
    class IterableDigraphComponent : public BAS {
596 596

	
597 597
    public:
598 598

	
599 599
      typedef BAS Base;
600 600
      typedef typename Base::Node Node;
601 601
      typedef typename Base::Arc Arc;
602 602

	
603 603
      typedef IterableDigraphComponent Digraph;
604 604

	
605
      /// \name Base iteration
605
      /// \name Base Iteration
606 606
      ///
607 607
      /// This interface provides functions for iteration on digraph items.
608 608
      ///
609 609
      /// @{
610 610

	
611 611
      /// \brief Return the first node.
612 612
      ///
613 613
      /// This function gives back the first node in the iteration order.
614 614
      void first(Node&) const {}
615 615

	
616 616
      /// \brief Return the next node.
617 617
      ///
618 618
      /// This function gives back the next node in the iteration order.
619 619
      void next(Node&) const {}
620 620

	
621 621
      /// \brief Return the first arc.
622 622
      ///
623 623
      /// This function gives back the first arc in the iteration order.
624 624
      void first(Arc&) const {}
625 625

	
626 626
      /// \brief Return the next arc.
627 627
      ///
628 628
      /// This function gives back the next arc in the iteration order.
629 629
      void next(Arc&) const {}
630 630

	
631 631
      /// \brief Return the first arc incomming to the given node.
632 632
      ///
633 633
      /// This function gives back the first arc incomming to the
634 634
      /// given node.
635 635
      void firstIn(Arc&, const Node&) const {}
636 636

	
637 637
      /// \brief Return the next arc incomming to the given node.
638 638
      ///
639 639
      /// This function gives back the next arc incomming to the
640 640
      /// given node.
641 641
      void nextIn(Arc&) const {}
642 642

	
643 643
      /// \brief Return the first arc outgoing form the given node.
644 644
      ///
645 645
      /// This function gives back the first arc outgoing form the
646 646
      /// given node.
647 647
      void firstOut(Arc&, const Node&) const {}
648 648

	
649 649
      /// \brief Return the next arc outgoing form the given node.
650 650
      ///
651 651
      /// This function gives back the next arc outgoing form the
652 652
      /// given node.
653 653
      void nextOut(Arc&) const {}
654 654

	
655 655
      /// @}
656 656

	
657
      /// \name Class based iteration
657
      /// \name Class Based Iteration
658 658
      ///
659 659
      /// This interface provides iterator classes for digraph items.
660 660
      ///
661 661
      /// @{
662 662

	
663 663
      /// \brief This iterator goes through each node.
664 664
      ///
665 665
      /// This iterator goes through each node.
666 666
      ///
667 667
      typedef GraphItemIt<Digraph, Node> NodeIt;
668 668

	
669 669
      /// \brief This iterator goes through each arc.
670 670
      ///
671 671
      /// This iterator goes through each arc.
672 672
      ///
673 673
      typedef GraphItemIt<Digraph, Arc> ArcIt;
674 674

	
675 675
      /// \brief This iterator goes trough the incoming arcs of a node.
676 676
      ///
677 677
      /// This iterator goes trough the \e incoming arcs of a certain node
678 678
      /// of a digraph.
679 679
      typedef GraphIncIt<Digraph, Arc, Node, 'i'> InArcIt;
680 680

	
681 681
      /// \brief This iterator goes trough the outgoing arcs of a node.
682 682
      ///
683 683
      /// This iterator goes trough the \e outgoing arcs of a certain node
684 684
      /// of a digraph.
685 685
      typedef GraphIncIt<Digraph, Arc, Node, 'o'> OutArcIt;
686 686

	
687 687
      /// \brief The base node of the iterator.
688 688
      ///
689 689
      /// This function gives back the base node of the iterator.
690 690
      /// It is always the target node of the pointed arc.
691 691
      Node baseNode(const InArcIt&) const { return INVALID; }
692 692

	
693 693
      /// \brief The running node of the iterator.
694 694
      ///
695 695
      /// This function gives back the running node of the iterator.
696 696
      /// It is always the source node of the pointed arc.
697 697
      Node runningNode(const InArcIt&) const { return INVALID; }
698 698

	
699 699
      /// \brief The base node of the iterator.
700 700
      ///
701 701
      /// This function gives back the base node of the iterator.
702 702
      /// It is always the source node of the pointed arc.
703 703
      Node baseNode(const OutArcIt&) const { return INVALID; }
704 704

	
705 705
      /// \brief The running node of the iterator.
706 706
      ///
707 707
      /// This function gives back the running node of the iterator.
708 708
      /// It is always the target node of the pointed arc.
709 709
      Node runningNode(const OutArcIt&) const { return INVALID; }
710 710

	
711 711
      /// @}
712 712

	
713 713
      template <typename _Digraph>
714 714
      struct Constraints {
715 715
        void constraints() {
716 716
          checkConcept<Base, _Digraph>();
717 717

	
718 718
          {
719 719
            typename _Digraph::Node node(INVALID);
720 720
            typename _Digraph::Arc arc(INVALID);
721 721
            {
722 722
              digraph.first(node);
723 723
              digraph.next(node);
724 724
            }
725 725
            {
726 726
              digraph.first(arc);
727 727
              digraph.next(arc);
728 728
            }
729 729
            {
730 730
              digraph.firstIn(arc, node);
731 731
              digraph.nextIn(arc);
732 732
            }
733 733
            {
734 734
              digraph.firstOut(arc, node);
735 735
              digraph.nextOut(arc);
736 736
            }
737 737
          }
738 738

	
739 739
          {
740 740
            checkConcept<GraphItemIt<_Digraph, typename _Digraph::Arc>,
741 741
              typename _Digraph::ArcIt >();
742 742
            checkConcept<GraphItemIt<_Digraph, typename _Digraph::Node>,
743 743
              typename _Digraph::NodeIt >();
744 744
            checkConcept<GraphIncIt<_Digraph, typename _Digraph::Arc,
745 745
              typename _Digraph::Node, 'i'>, typename _Digraph::InArcIt>();
746 746
            checkConcept<GraphIncIt<_Digraph, typename _Digraph::Arc,
747 747
              typename _Digraph::Node, 'o'>, typename _Digraph::OutArcIt>();
748 748

	
749 749
            typename _Digraph::Node n;
750 750
            const typename _Digraph::InArcIt iait(INVALID);
751 751
            const typename _Digraph::OutArcIt oait(INVALID);
752 752
            n = digraph.baseNode(iait);
753 753
            n = digraph.runningNode(iait);
754 754
            n = digraph.baseNode(oait);
755 755
            n = digraph.runningNode(oait);
756 756
            ignore_unused_variable_warning(n);
757 757
          }
758 758
        }
759 759

	
760 760
        const _Digraph& digraph;
761 761
      };
762 762
    };
763 763

	
764 764
    /// \brief Skeleton class for iterable undirected graphs.
765 765
    ///
766 766
    /// This class describes the interface of iterable undirected
767 767
    /// graphs. It extends \ref IterableDigraphComponent with the core
768 768
    /// iterable interface of undirected graphs.
769 769
    /// This concept is part of the Graph concept.
770 770
    template <typename BAS = BaseGraphComponent>
771 771
    class IterableGraphComponent : public IterableDigraphComponent<BAS> {
772 772
    public:
773 773

	
774 774
      typedef BAS Base;
775 775
      typedef typename Base::Node Node;
776 776
      typedef typename Base::Arc Arc;
777 777
      typedef typename Base::Edge Edge;
778 778

	
779 779

	
780 780
      typedef IterableGraphComponent Graph;
781 781

	
782
      /// \name Base iteration
782
      /// \name Base Iteration
783 783
      ///
784 784
      /// This interface provides functions for iteration on edges.
785 785
      ///
786 786
      /// @{
787 787

	
788 788
      using IterableDigraphComponent<Base>::first;
789 789
      using IterableDigraphComponent<Base>::next;
790 790

	
791 791
      /// \brief Return the first edge.
792 792
      ///
793 793
      /// This function gives back the first edge in the iteration order.
794 794
      void first(Edge&) const {}
795 795

	
796 796
      /// \brief Return the next edge.
797 797
      ///
798 798
      /// This function gives back the next edge in the iteration order.
799 799
      void next(Edge&) const {}
800 800

	
801 801
      /// \brief Return the first edge incident to the given node.
802 802
      ///
803 803
      /// This function gives back the first edge incident to the given 
804 804
      /// node. The bool parameter gives back the direction for which the
805 805
      /// source node of the directed arc representing the edge is the 
806 806
      /// given node.
807 807
      void firstInc(Edge&, bool&, const Node&) const {}
808 808

	
809 809
      /// \brief Gives back the next of the edges from the
810 810
      /// given node.
811 811
      ///
812 812
      /// This function gives back the next edge incident to the given 
813 813
      /// node. The bool parameter should be used as \c firstInc() use it.
814 814
      void nextInc(Edge&, bool&) const {}
815 815

	
816 816
      using IterableDigraphComponent<Base>::baseNode;
817 817
      using IterableDigraphComponent<Base>::runningNode;
818 818

	
819 819
      /// @}
820 820

	
821
      /// \name Class based iteration
821
      /// \name Class Based Iteration
822 822
      ///
823 823
      /// This interface provides iterator classes for edges.
824 824
      ///
825 825
      /// @{
826 826

	
827 827
      /// \brief This iterator goes through each edge.
828 828
      ///
829 829
      /// This iterator goes through each edge.
830 830
      typedef GraphItemIt<Graph, Edge> EdgeIt;
831 831

	
832 832
      /// \brief This iterator goes trough the incident edges of a
833 833
      /// node.
834 834
      ///
835 835
      /// This iterator goes trough the incident edges of a certain
836 836
      /// node of a graph.
837 837
      typedef GraphIncIt<Graph, Edge, Node, 'e'> IncEdgeIt;
838 838

	
839 839
      /// \brief The base node of the iterator.
840 840
      ///
841 841
      /// This function gives back the base node of the iterator.
842 842
      Node baseNode(const IncEdgeIt&) const { return INVALID; }
843 843

	
844 844
      /// \brief The running node of the iterator.
845 845
      ///
846 846
      /// This function gives back the running node of the iterator.
847 847
      Node runningNode(const IncEdgeIt&) const { return INVALID; }
848 848

	
849 849
      /// @}
850 850

	
851 851
      template <typename _Graph>
852 852
      struct Constraints {
853 853
        void constraints() {
854 854
          checkConcept<IterableDigraphComponent<Base>, _Graph>();
855 855

	
856 856
          {
857 857
            typename _Graph::Node node(INVALID);
858 858
            typename _Graph::Edge edge(INVALID);
859 859
            bool dir;
860 860
            {
861 861
              graph.first(edge);
862 862
              graph.next(edge);
863 863
            }
864 864
            {
865 865
              graph.firstInc(edge, dir, node);
866 866
              graph.nextInc(edge, dir);
867 867
            }
868 868

	
869 869
          }
870 870

	
871 871
          {
872 872
            checkConcept<GraphItemIt<_Graph, typename _Graph::Edge>,
873 873
              typename _Graph::EdgeIt >();
874 874
            checkConcept<GraphIncIt<_Graph, typename _Graph::Edge,
875 875
              typename _Graph::Node, 'e'>, typename _Graph::IncEdgeIt>();
876 876

	
877 877
            typename _Graph::Node n;
878 878
            const typename _Graph::IncEdgeIt ieit(INVALID);
879 879
            n = graph.baseNode(ieit);
880 880
            n = graph.runningNode(ieit);
881 881
          }
882 882
        }
883 883

	
884 884
        const _Graph& graph;
885 885
      };
886 886
    };
887 887

	
888 888
    /// \brief Skeleton class for alterable directed graphs.
889 889
    ///
890 890
    /// This class describes the interface of alterable directed
891 891
    /// graphs. It extends \ref BaseDigraphComponent with the alteration
892 892
    /// notifier interface. It implements
893 893
    /// an observer-notifier pattern for each digraph item. More
894 894
    /// obsevers can be registered into the notifier and whenever an
895 895
    /// alteration occured in the digraph all the observers will be
896 896
    /// notified about it.
897 897
    template <typename BAS = BaseDigraphComponent>
898 898
    class AlterableDigraphComponent : public BAS {
899 899
    public:
900 900

	
901 901
      typedef BAS Base;
902 902
      typedef typename Base::Node Node;
903 903
      typedef typename Base::Arc Arc;
904 904

	
905 905

	
906 906
      /// Node alteration notifier class.
907 907
      typedef AlterationNotifier<AlterableDigraphComponent, Node>
908 908
      NodeNotifier;
909 909
      /// Arc alteration notifier class.
910 910
      typedef AlterationNotifier<AlterableDigraphComponent, Arc>
911 911
      ArcNotifier;
912 912

	
913 913
      /// \brief Return the node alteration notifier.
914 914
      ///
915 915
      /// This function gives back the node alteration notifier.
916 916
      NodeNotifier& notifier(Node) const {
917 917
         return NodeNotifier();
918 918
      }
919 919

	
920 920
      /// \brief Return the arc alteration notifier.
921 921
      ///
922 922
      /// This function gives back the arc alteration notifier.
923 923
      ArcNotifier& notifier(Arc) const {
924 924
        return ArcNotifier();
925 925
      }
926 926

	
927 927
      template <typename _Digraph>
928 928
      struct Constraints {
929 929
        void constraints() {
930 930
          checkConcept<Base, _Digraph>();
931 931
          typename _Digraph::NodeNotifier& nn
932 932
            = digraph.notifier(typename _Digraph::Node());
933 933

	
934 934
          typename _Digraph::ArcNotifier& en
935 935
            = digraph.notifier(typename _Digraph::Arc());
936 936

	
937 937
          ignore_unused_variable_warning(nn);
938 938
          ignore_unused_variable_warning(en);
939 939
        }
940 940

	
941 941
        const _Digraph& digraph;
942 942
      };
943 943
    };
944 944

	
945 945
    /// \brief Skeleton class for alterable undirected graphs.
946 946
    ///
947 947
    /// This class describes the interface of alterable undirected
948 948
    /// graphs. It extends \ref AlterableDigraphComponent with the alteration
949 949
    /// notifier interface of undirected graphs. It implements
950 950
    /// an observer-notifier pattern for the edges. More
951 951
    /// obsevers can be registered into the notifier and whenever an
952 952
    /// alteration occured in the graph all the observers will be
953 953
    /// notified about it.
954 954
    template <typename BAS = BaseGraphComponent>
955 955
    class AlterableGraphComponent : public AlterableDigraphComponent<BAS> {
956 956
    public:
957 957

	
958 958
      typedef BAS Base;
959 959
      typedef typename Base::Edge Edge;
960 960

	
961 961

	
962 962
      /// Edge alteration notifier class.
963 963
      typedef AlterationNotifier<AlterableGraphComponent, Edge>
964 964
      EdgeNotifier;
965 965

	
966 966
      /// \brief Return the edge alteration notifier.
967 967
      ///
968 968
      /// This function gives back the edge alteration notifier.
969 969
      EdgeNotifier& notifier(Edge) const {
970 970
        return EdgeNotifier();
971 971
      }
972 972

	
973 973
      template <typename _Graph>
974 974
      struct Constraints {
975 975
        void constraints() {
976 976
          checkConcept<AlterableDigraphComponent<Base>, _Graph>();
977 977
          typename _Graph::EdgeNotifier& uen
978 978
            = graph.notifier(typename _Graph::Edge());
979 979
          ignore_unused_variable_warning(uen);
980 980
        }
981 981

	
982 982
        const _Graph& graph;
983 983
      };
984 984
    };
985 985

	
986 986
    /// \brief Concept class for standard graph maps.
987 987
    ///
988 988
    /// This class describes the concept of standard graph maps, i.e.
989 989
    /// the \c NodeMap, \c ArcMap and \c EdgeMap subtypes of digraph and 
990 990
    /// graph types, which can be used for associating data to graph items.
991 991
    /// The standard graph maps must conform to the ReferenceMap concept.
992 992
    template <typename GR, typename K, typename V>
993 993
    class GraphMap : public ReferenceMap<K, V, V&, const V&> {
994 994
    public:
995 995

	
996 996
      typedef ReadWriteMap<K, V> Parent;
997 997

	
998 998
      /// The graph type of the map.
999 999
      typedef GR Graph;
1000 1000
      /// The key type of the map.
1001 1001
      typedef K Key;
1002 1002
      /// The value type of the map.
1003 1003
      typedef V Value;
1004 1004
      /// The reference type of the map.
1005 1005
      typedef Value& Reference;
1006 1006
      /// The const reference type of the map.
1007 1007
      typedef const Value& ConstReference;
1008 1008

	
1009 1009
      // The reference map tag.
1010 1010
      typedef True ReferenceMapTag;
1011 1011

	
1012 1012
      /// \brief Construct a new map.
1013 1013
      ///
1014 1014
      /// Construct a new map for the graph.
1015 1015
      explicit GraphMap(const Graph&) {}
1016 1016
      /// \brief Construct a new map with default value.
1017 1017
      ///
1018 1018
      /// Construct a new map for the graph and initalize the values.
1019 1019
      GraphMap(const Graph&, const Value&) {}
1020 1020

	
1021 1021
    private:
1022 1022
      /// \brief Copy constructor.
1023 1023
      ///
1024 1024
      /// Copy Constructor.
1025 1025
      GraphMap(const GraphMap&) : Parent() {}
1026 1026

	
1027 1027
      /// \brief Assignment operator.
1028 1028
      ///
1029 1029
      /// Assignment operator. It does not mofify the underlying graph,
1030 1030
      /// it just iterates on the current item set and set the  map
1031 1031
      /// with the value returned by the assigned map.
1032 1032
      template <typename CMap>
1033 1033
      GraphMap& operator=(const CMap&) {
1034 1034
        checkConcept<ReadMap<Key, Value>, CMap>();
1035 1035
        return *this;
1036 1036
      }
1037 1037

	
1038 1038
    public:
1039 1039
      template<typename _Map>
1040 1040
      struct Constraints {
1041 1041
        void constraints() {
1042 1042
          checkConcept
1043 1043
            <ReferenceMap<Key, Value, Value&, const Value&>, _Map>();
1044 1044
          _Map m1(g);
1045 1045
          _Map m2(g,t);
1046 1046
          
1047 1047
          // Copy constructor
1048 1048
          // _Map m3(m);
1049 1049

	
1050 1050
          // Assignment operator
1051 1051
          // ReadMap<Key, Value> cmap;
1052 1052
          // m3 = cmap;
1053 1053

	
1054 1054
          ignore_unused_variable_warning(m1);
1055 1055
          ignore_unused_variable_warning(m2);
1056 1056
          // ignore_unused_variable_warning(m3);
1057 1057
        }
1058 1058

	
1059 1059
        const _Map &m;
1060 1060
        const Graph &g;
1061 1061
        const typename GraphMap::Value &t;
1062 1062
      };
1063 1063

	
1064 1064
    };
1065 1065

	
1066 1066
    /// \brief Skeleton class for mappable directed graphs.
1067 1067
    ///
1068 1068
    /// This class describes the interface of mappable directed graphs.
1069 1069
    /// It extends \ref BaseDigraphComponent with the standard digraph 
1070 1070
    /// map classes, namely \c NodeMap and \c ArcMap.
1071 1071
    /// This concept is part of the Digraph concept.
1072 1072
    template <typename BAS = BaseDigraphComponent>
1073 1073
    class MappableDigraphComponent : public BAS  {
1074 1074
    public:
1075 1075

	
1076 1076
      typedef BAS Base;
1077 1077
      typedef typename Base::Node Node;
Ignore white space 512 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
///\ingroup concept
20 20
///\file
21 21
///\brief The concept of heaps.
22 22

	
23 23
#ifndef LEMON_CONCEPTS_HEAP_H
24 24
#define LEMON_CONCEPTS_HEAP_H
25 25

	
26 26
#include <lemon/core.h>
27 27
#include <lemon/concept_check.h>
28 28

	
29 29
namespace lemon {
30 30

	
31 31
  namespace concepts {
32 32

	
33 33
    /// \addtogroup concept
34 34
    /// @{
35 35

	
36 36
    /// \brief The heap concept.
37 37
    ///
38 38
    /// Concept class describing the main interface of heaps. A \e heap
39 39
    /// is a data structure for storing items with specified values called
40 40
    /// \e priorities in such a way that finding the item with minimum
41 41
    /// priority is efficient. In a heap one can change the priority of an
42 42
    /// item, add or erase an item, etc.
43 43
    ///
44 44
    /// \tparam PR Type of the priority of the items.
45 45
    /// \tparam IM A read and writable item map with int values, used
46 46
    /// internally to handle the cross references.
47 47
    /// \tparam Comp A functor class for the ordering of the priorities.
48 48
    /// The default is \c std::less<PR>.
49 49
#ifdef DOXYGEN
50 50
    template <typename PR, typename IM, typename Comp = std::less<PR> >
51 51
#else
52 52
    template <typename PR, typename IM>
53 53
#endif
54 54
    class Heap {
55 55
    public:
56 56

	
57 57
      /// Type of the item-int map.
58 58
      typedef IM ItemIntMap;
59 59
      /// Type of the priorities.
60 60
      typedef PR Prio;
61 61
      /// Type of the items stored in the heap.
62 62
      typedef typename ItemIntMap::Key Item;
63 63

	
64 64
      /// \brief Type to represent the states of the items.
65 65
      ///
66 66
      /// Each item has a state associated to it. It can be "in heap",
67 67
      /// "pre heap" or "post heap". The later two are indifferent
68 68
      /// from the point of view of the heap, but may be useful for
69 69
      /// the user.
70 70
      ///
71 71
      /// The item-int map must be initialized in such way that it assigns
72 72
      /// \c PRE_HEAP (<tt>-1</tt>) to any element to be put in the heap.
73 73
      enum State {
74
        IN_HEAP = 0,    ///< The "in heap" state constant.
75
        PRE_HEAP = -1,  ///< The "pre heap" state constant.
76
        POST_HEAP = -2  ///< The "post heap" state constant.
74
        IN_HEAP = 0,    ///< = 0. The "in heap" state constant.
75
        PRE_HEAP = -1,  ///< = -1. The "pre heap" state constant.
76
        POST_HEAP = -2  ///< = -2. The "post heap" state constant.
77 77
      };
78 78

	
79 79
      /// \brief The constructor.
80 80
      ///
81 81
      /// The constructor.
82 82
      /// \param map A map that assigns \c int values to keys of type
83 83
      /// \c Item. It is used internally by the heap implementations to
84 84
      /// handle the cross references. The assigned value must be
85 85
      /// \c PRE_HEAP (<tt>-1</tt>) for every item.
86 86
      explicit Heap(ItemIntMap &map) {}
87 87

	
88 88
      /// \brief The number of items stored in the heap.
89 89
      ///
90 90
      /// Returns the number of items stored in the heap.
91 91
      int size() const { return 0; }
92 92

	
93 93
      /// \brief Checks if the heap is empty.
94 94
      ///
95 95
      /// Returns \c true if the heap is empty.
96 96
      bool empty() const { return false; }
97 97

	
98 98
      /// \brief Makes the heap empty.
99 99
      ///
100 100
      /// Makes the heap empty.
101 101
      void clear();
102 102

	
103 103
      /// \brief Inserts an item into the heap with the given priority.
104 104
      ///
105 105
      /// Inserts the given item into the heap with the given priority.
106 106
      /// \param i The item to insert.
107 107
      /// \param p The priority of the item.
108 108
      void push(const Item &i, const Prio &p) {}
109 109

	
110 110
      /// \brief Returns the item having minimum priority.
111 111
      ///
112 112
      /// Returns the item having minimum priority.
113 113
      /// \pre The heap must be non-empty.
114 114
      Item top() const {}
115 115

	
116 116
      /// \brief The minimum priority.
117 117
      ///
118 118
      /// Returns the minimum priority.
119 119
      /// \pre The heap must be non-empty.
120 120
      Prio prio() const {}
121 121

	
122 122
      /// \brief Removes the item having minimum priority.
123 123
      ///
124 124
      /// Removes the item having minimum priority.
125 125
      /// \pre The heap must be non-empty.
126 126
      void pop() {}
127 127

	
128 128
      /// \brief Removes an item from the heap.
129 129
      ///
130 130
      /// Removes the given item from the heap if it is already stored.
131 131
      /// \param i The item to delete.
132 132
      void erase(const Item &i) {}
133 133

	
134 134
      /// \brief The priority of an item.
135 135
      ///
136 136
      /// Returns the priority of the given item.
137 137
      /// \param i The item.
138 138
      /// \pre \c i must be in the heap.
139 139
      Prio operator[](const Item &i) const {}
140 140

	
141 141
      /// \brief Sets the priority of an item or inserts it, if it is
142 142
      /// not stored in the heap.
143 143
      ///
144 144
      /// This method sets the priority of the given item if it is
145 145
      /// already stored in the heap.
146 146
      /// Otherwise it inserts the given item with the given priority.
147 147
      ///
148 148
      /// \param i The item.
149 149
      /// \param p The priority.
150 150
      void set(const Item &i, const Prio &p) {}
151 151

	
152 152
      /// \brief Decreases the priority of an item to the given value.
153 153
      ///
154 154
      /// Decreases the priority of an item to the given value.
155 155
      /// \param i The item.
156 156
      /// \param p The priority.
157 157
      /// \pre \c i must be stored in the heap with priority at least \c p.
158 158
      void decrease(const Item &i, const Prio &p) {}
159 159

	
160 160
      /// \brief Increases the priority of an item to the given value.
161 161
      ///
162 162
      /// Increases the priority of an item to the given value.
163 163
      /// \param i The item.
164 164
      /// \param p The priority.
165 165
      /// \pre \c i must be stored in the heap with priority at most \c p.
166 166
      void increase(const Item &i, const Prio &p) {}
167 167

	
168 168
      /// \brief Returns if an item is in, has already been in, or has
169 169
      /// never been in the heap.
170 170
      ///
171 171
      /// This method returns \c PRE_HEAP if the given item has never
172 172
      /// been in the heap, \c IN_HEAP if it is in the heap at the moment,
173 173
      /// and \c POST_HEAP otherwise.
174 174
      /// In the latter case it is possible that the item will get back
175 175
      /// to the heap again.
176 176
      /// \param i The item.
177 177
      State state(const Item &i) const {}
178 178

	
179 179
      /// \brief Sets the state of an item in the heap.
180 180
      ///
181 181
      /// Sets the state of the given item in the heap. It can be used
182 182
      /// to manually clear the heap when it is important to achive the
183 183
      /// better time complexity.
184 184
      /// \param i The item.
185 185
      /// \param st The state. It should not be \c IN_HEAP.
186 186
      void state(const Item& i, State st) {}
187 187

	
188 188

	
189 189
      template <typename _Heap>
190 190
      struct Constraints {
191 191
      public:
192 192
        void constraints() {
193 193
          typedef typename _Heap::Item OwnItem;
194 194
          typedef typename _Heap::Prio OwnPrio;
195 195
          typedef typename _Heap::State OwnState;
196 196

	
197 197
          Item item;
198 198
          Prio prio;
199 199
          item=Item();
200 200
          prio=Prio();
201 201
          ignore_unused_variable_warning(item);
202 202
          ignore_unused_variable_warning(prio);
203 203

	
204 204
          OwnItem own_item;
205 205
          OwnPrio own_prio;
206 206
          OwnState own_state;
207 207
          own_item=Item();
208 208
          own_prio=Prio();
209 209
          ignore_unused_variable_warning(own_item);
210 210
          ignore_unused_variable_warning(own_prio);
211 211
          ignore_unused_variable_warning(own_state);
212 212

	
213 213
          _Heap heap1(map);
214 214
          _Heap heap2 = heap1;
215 215
          ignore_unused_variable_warning(heap1);
216 216
          ignore_unused_variable_warning(heap2);
217 217

	
218 218
          int s = heap.size();
219 219
          ignore_unused_variable_warning(s);
220 220
          bool e = heap.empty();
221 221
          ignore_unused_variable_warning(e);
222 222

	
223 223
          prio = heap.prio();
224 224
          item = heap.top();
225 225
          prio = heap[item];
226 226
          own_prio = heap.prio();
227 227
          own_item = heap.top();
228 228
          own_prio = heap[own_item];
229 229

	
230 230
          heap.push(item, prio);
231 231
          heap.push(own_item, own_prio);
232 232
          heap.pop();
233 233

	
234 234
          heap.set(item, prio);
235 235
          heap.decrease(item, prio);
236 236
          heap.increase(item, prio);
237 237
          heap.set(own_item, own_prio);
238 238
          heap.decrease(own_item, own_prio);
239 239
          heap.increase(own_item, own_prio);
240 240

	
241 241
          heap.erase(item);
242 242
          heap.erase(own_item);
243 243
          heap.clear();
244 244

	
245 245
          own_state = heap.state(own_item);
246 246
          heap.state(own_item, own_state);
247 247

	
248 248
          own_state = _Heap::PRE_HEAP;
249 249
          own_state = _Heap::IN_HEAP;
250 250
          own_state = _Heap::POST_HEAP;
251 251
        }
252 252

	
253 253
        _Heap& heap;
254 254
        ItemIntMap& map;
255 255
      };
256 256
    };
257 257

	
258 258
    /// @}
259 259
  } // namespace lemon
260 260
}
261 261
#endif
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_DFS_H
20 20
#define LEMON_DFS_H
21 21

	
22 22
///\ingroup search
23 23
///\file
24 24
///\brief DFS algorithm.
25 25

	
26 26
#include <lemon/list_graph.h>
27 27
#include <lemon/bits/path_dump.h>
28 28
#include <lemon/core.h>
29 29
#include <lemon/error.h>
30 30
#include <lemon/maps.h>
31 31
#include <lemon/path.h>
32 32

	
33 33
namespace lemon {
34 34

	
35 35
  ///Default traits class of Dfs class.
36 36

	
37 37
  ///Default traits class of Dfs class.
38 38
  ///\tparam GR Digraph type.
39 39
  template<class GR>
40 40
  struct DfsDefaultTraits
41 41
  {
42 42
    ///The type of the digraph the algorithm runs on.
43 43
    typedef GR Digraph;
44 44

	
45 45
    ///\brief The type of the map that stores the predecessor
46 46
    ///arcs of the %DFS paths.
47 47
    ///
48 48
    ///The type of the map that stores the predecessor
49 49
    ///arcs of the %DFS paths.
50 50
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
51 51
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
52 52
    ///Instantiates a \c PredMap.
53 53

	
54 54
    ///This function instantiates a \ref PredMap.
55 55
    ///\param g is the digraph, to which we would like to define the
56 56
    ///\ref PredMap.
57 57
    static PredMap *createPredMap(const Digraph &g)
58 58
    {
59 59
      return new PredMap(g);
60 60
    }
61 61

	
62 62
    ///The type of the map that indicates which nodes are processed.
63 63

	
64 64
    ///The type of the map that indicates which nodes are processed.
65 65
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
66 66
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
67 67
    ///Instantiates a \c ProcessedMap.
68 68

	
69 69
    ///This function instantiates a \ref ProcessedMap.
70 70
    ///\param g is the digraph, to which
71 71
    ///we would like to define the \ref ProcessedMap.
72 72
#ifdef DOXYGEN
73 73
    static ProcessedMap *createProcessedMap(const Digraph &g)
74 74
#else
75 75
    static ProcessedMap *createProcessedMap(const Digraph &)
76 76
#endif
77 77
    {
78 78
      return new ProcessedMap();
79 79
    }
80 80

	
81 81
    ///The type of the map that indicates which nodes are reached.
82 82

	
83 83
    ///The type of the map that indicates which nodes are reached.
84 84
    ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
85 85
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
86 86
    ///Instantiates a \c ReachedMap.
87 87

	
88 88
    ///This function instantiates a \ref ReachedMap.
89 89
    ///\param g is the digraph, to which
90 90
    ///we would like to define the \ref ReachedMap.
91 91
    static ReachedMap *createReachedMap(const Digraph &g)
92 92
    {
93 93
      return new ReachedMap(g);
94 94
    }
95 95

	
96 96
    ///The type of the map that stores the distances of the nodes.
97 97

	
98 98
    ///The type of the map that stores the distances of the nodes.
99 99
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
100 100
    typedef typename Digraph::template NodeMap<int> DistMap;
101 101
    ///Instantiates a \c DistMap.
102 102

	
103 103
    ///This function instantiates a \ref DistMap.
104 104
    ///\param g is the digraph, to which we would like to define the
105 105
    ///\ref DistMap.
106 106
    static DistMap *createDistMap(const Digraph &g)
107 107
    {
108 108
      return new DistMap(g);
109 109
    }
110 110
  };
111 111

	
112 112
  ///%DFS algorithm class.
113 113

	
114 114
  ///\ingroup search
115 115
  ///This class provides an efficient implementation of the %DFS algorithm.
116 116
  ///
117 117
  ///There is also a \ref dfs() "function-type interface" for the DFS
118 118
  ///algorithm, which is convenient in the simplier cases and it can be
119 119
  ///used easier.
120 120
  ///
121 121
  ///\tparam GR The type of the digraph the algorithm runs on.
122 122
  ///The default type is \ref ListDigraph.
123 123
#ifdef DOXYGEN
124 124
  template <typename GR,
125 125
            typename TR>
126 126
#else
127 127
  template <typename GR=ListDigraph,
128 128
            typename TR=DfsDefaultTraits<GR> >
129 129
#endif
130 130
  class Dfs {
131 131
  public:
132 132

	
133 133
    ///The type of the digraph the algorithm runs on.
134 134
    typedef typename TR::Digraph Digraph;
135 135

	
136 136
    ///\brief The type of the map that stores the predecessor arcs of the
137 137
    ///DFS paths.
138 138
    typedef typename TR::PredMap PredMap;
139 139
    ///The type of the map that stores the distances of the nodes.
140 140
    typedef typename TR::DistMap DistMap;
141 141
    ///The type of the map that indicates which nodes are reached.
142 142
    typedef typename TR::ReachedMap ReachedMap;
143 143
    ///The type of the map that indicates which nodes are processed.
144 144
    typedef typename TR::ProcessedMap ProcessedMap;
145 145
    ///The type of the paths.
146 146
    typedef PredMapPath<Digraph, PredMap> Path;
147 147

	
148 148
    ///The \ref DfsDefaultTraits "traits class" of the algorithm.
149 149
    typedef TR Traits;
150 150

	
151 151
  private:
152 152

	
153 153
    typedef typename Digraph::Node Node;
154 154
    typedef typename Digraph::NodeIt NodeIt;
155 155
    typedef typename Digraph::Arc Arc;
156 156
    typedef typename Digraph::OutArcIt OutArcIt;
157 157

	
158 158
    //Pointer to the underlying digraph.
159 159
    const Digraph *G;
160 160
    //Pointer to the map of predecessor arcs.
161 161
    PredMap *_pred;
162 162
    //Indicates if _pred is locally allocated (true) or not.
163 163
    bool local_pred;
164 164
    //Pointer to the map of distances.
165 165
    DistMap *_dist;
166 166
    //Indicates if _dist is locally allocated (true) or not.
167 167
    bool local_dist;
168 168
    //Pointer to the map of reached status of the nodes.
169 169
    ReachedMap *_reached;
170 170
    //Indicates if _reached is locally allocated (true) or not.
171 171
    bool local_reached;
172 172
    //Pointer to the map of processed status of the nodes.
173 173
    ProcessedMap *_processed;
174 174
    //Indicates if _processed is locally allocated (true) or not.
175 175
    bool local_processed;
176 176

	
177 177
    std::vector<typename Digraph::OutArcIt> _stack;
178 178
    int _stack_head;
179 179

	
180 180
    //Creates the maps if necessary.
181 181
    void create_maps()
182 182
    {
183 183
      if(!_pred) {
184 184
        local_pred = true;
185 185
        _pred = Traits::createPredMap(*G);
186 186
      }
187 187
      if(!_dist) {
188 188
        local_dist = true;
189 189
        _dist = Traits::createDistMap(*G);
190 190
      }
191 191
      if(!_reached) {
192 192
        local_reached = true;
193 193
        _reached = Traits::createReachedMap(*G);
194 194
      }
195 195
      if(!_processed) {
196 196
        local_processed = true;
197 197
        _processed = Traits::createProcessedMap(*G);
198 198
      }
199 199
    }
200 200

	
201 201
  protected:
202 202

	
203 203
    Dfs() {}
204 204

	
205 205
  public:
206 206

	
207 207
    typedef Dfs Create;
208 208

	
209
    ///\name Named template parameters
209
    ///\name Named Template Parameters
210 210

	
211 211
    ///@{
212 212

	
213 213
    template <class T>
214 214
    struct SetPredMapTraits : public Traits {
215 215
      typedef T PredMap;
216 216
      static PredMap *createPredMap(const Digraph &)
217 217
      {
218 218
        LEMON_ASSERT(false, "PredMap is not initialized");
219 219
        return 0; // ignore warnings
220 220
      }
221 221
    };
222 222
    ///\brief \ref named-templ-param "Named parameter" for setting
223 223
    ///\c PredMap type.
224 224
    ///
225 225
    ///\ref named-templ-param "Named parameter" for setting
226 226
    ///\c PredMap type.
227 227
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
228 228
    template <class T>
229 229
    struct SetPredMap : public Dfs<Digraph, SetPredMapTraits<T> > {
230 230
      typedef Dfs<Digraph, SetPredMapTraits<T> > Create;
231 231
    };
232 232

	
233 233
    template <class T>
234 234
    struct SetDistMapTraits : public Traits {
235 235
      typedef T DistMap;
236 236
      static DistMap *createDistMap(const Digraph &)
237 237
      {
238 238
        LEMON_ASSERT(false, "DistMap is not initialized");
239 239
        return 0; // ignore warnings
240 240
      }
241 241
    };
242 242
    ///\brief \ref named-templ-param "Named parameter" for setting
243 243
    ///\c DistMap type.
244 244
    ///
245 245
    ///\ref named-templ-param "Named parameter" for setting
246 246
    ///\c DistMap type.
247 247
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
248 248
    template <class T>
249 249
    struct SetDistMap : public Dfs< Digraph, SetDistMapTraits<T> > {
250 250
      typedef Dfs<Digraph, SetDistMapTraits<T> > Create;
251 251
    };
252 252

	
253 253
    template <class T>
254 254
    struct SetReachedMapTraits : public Traits {
255 255
      typedef T ReachedMap;
256 256
      static ReachedMap *createReachedMap(const Digraph &)
257 257
      {
258 258
        LEMON_ASSERT(false, "ReachedMap is not initialized");
259 259
        return 0; // ignore warnings
260 260
      }
261 261
    };
262 262
    ///\brief \ref named-templ-param "Named parameter" for setting
263 263
    ///\c ReachedMap type.
264 264
    ///
265 265
    ///\ref named-templ-param "Named parameter" for setting
266 266
    ///\c ReachedMap type.
267 267
    ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
268 268
    template <class T>
269 269
    struct SetReachedMap : public Dfs< Digraph, SetReachedMapTraits<T> > {
270 270
      typedef Dfs< Digraph, SetReachedMapTraits<T> > Create;
271 271
    };
272 272

	
273 273
    template <class T>
274 274
    struct SetProcessedMapTraits : public Traits {
275 275
      typedef T ProcessedMap;
276 276
      static ProcessedMap *createProcessedMap(const Digraph &)
277 277
      {
278 278
        LEMON_ASSERT(false, "ProcessedMap is not initialized");
279 279
        return 0; // ignore warnings
280 280
      }
281 281
    };
282 282
    ///\brief \ref named-templ-param "Named parameter" for setting
283 283
    ///\c ProcessedMap type.
284 284
    ///
285 285
    ///\ref named-templ-param "Named parameter" for setting
286 286
    ///\c ProcessedMap type.
287 287
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
288 288
    template <class T>
289 289
    struct SetProcessedMap : public Dfs< Digraph, SetProcessedMapTraits<T> > {
290 290
      typedef Dfs< Digraph, SetProcessedMapTraits<T> > Create;
291 291
    };
292 292

	
293 293
    struct SetStandardProcessedMapTraits : public Traits {
294 294
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
295 295
      static ProcessedMap *createProcessedMap(const Digraph &g)
296 296
      {
297 297
        return new ProcessedMap(g);
298 298
      }
299 299
    };
300 300
    ///\brief \ref named-templ-param "Named parameter" for setting
301 301
    ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
302 302
    ///
303 303
    ///\ref named-templ-param "Named parameter" for setting
304 304
    ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
305 305
    ///If you don't set it explicitly, it will be automatically allocated.
306 306
    struct SetStandardProcessedMap :
307 307
      public Dfs< Digraph, SetStandardProcessedMapTraits > {
308 308
      typedef Dfs< Digraph, SetStandardProcessedMapTraits > Create;
309 309
    };
310 310

	
311 311
    ///@}
312 312

	
313 313
  public:
314 314

	
315 315
    ///Constructor.
316 316

	
317 317
    ///Constructor.
318 318
    ///\param g The digraph the algorithm runs on.
319 319
    Dfs(const Digraph &g) :
320 320
      G(&g),
321 321
      _pred(NULL), local_pred(false),
322 322
      _dist(NULL), local_dist(false),
323 323
      _reached(NULL), local_reached(false),
324 324
      _processed(NULL), local_processed(false)
325 325
    { }
326 326

	
327 327
    ///Destructor.
328 328
    ~Dfs()
329 329
    {
330 330
      if(local_pred) delete _pred;
331 331
      if(local_dist) delete _dist;
332 332
      if(local_reached) delete _reached;
333 333
      if(local_processed) delete _processed;
334 334
    }
335 335

	
336 336
    ///Sets the map that stores the predecessor arcs.
337 337

	
338 338
    ///Sets the map that stores the predecessor arcs.
339 339
    ///If you don't use this function before calling \ref run(Node) "run()"
340 340
    ///or \ref init(), an instance will be allocated automatically.
341 341
    ///The destructor deallocates this automatically allocated map,
342 342
    ///of course.
343 343
    ///\return <tt> (*this) </tt>
344 344
    Dfs &predMap(PredMap &m)
345 345
    {
346 346
      if(local_pred) {
347 347
        delete _pred;
348 348
        local_pred=false;
349 349
      }
350 350
      _pred = &m;
351 351
      return *this;
352 352
    }
353 353

	
354 354
    ///Sets the map that indicates which nodes are reached.
355 355

	
356 356
    ///Sets the map that indicates which nodes are reached.
357 357
    ///If you don't use this function before calling \ref run(Node) "run()"
358 358
    ///or \ref init(), an instance will be allocated automatically.
359 359
    ///The destructor deallocates this automatically allocated map,
360 360
    ///of course.
361 361
    ///\return <tt> (*this) </tt>
362 362
    Dfs &reachedMap(ReachedMap &m)
363 363
    {
364 364
      if(local_reached) {
365 365
        delete _reached;
366 366
        local_reached=false;
367 367
      }
368 368
      _reached = &m;
369 369
      return *this;
370 370
    }
371 371

	
372 372
    ///Sets the map that indicates which nodes are processed.
373 373

	
374 374
    ///Sets the map that indicates which nodes are processed.
375 375
    ///If you don't use this function before calling \ref run(Node) "run()"
376 376
    ///or \ref init(), an instance will be allocated automatically.
377 377
    ///The destructor deallocates this automatically allocated map,
378 378
    ///of course.
379 379
    ///\return <tt> (*this) </tt>
380 380
    Dfs &processedMap(ProcessedMap &m)
381 381
    {
382 382
      if(local_processed) {
383 383
        delete _processed;
384 384
        local_processed=false;
385 385
      }
386 386
      _processed = &m;
387 387
      return *this;
388 388
    }
389 389

	
390 390
    ///Sets the map that stores the distances of the nodes.
391 391

	
392 392
    ///Sets the map that stores the distances of the nodes calculated by
393 393
    ///the algorithm.
394 394
    ///If you don't use this function before calling \ref run(Node) "run()"
395 395
    ///or \ref init(), an instance will be allocated automatically.
396 396
    ///The destructor deallocates this automatically allocated map,
397 397
    ///of course.
398 398
    ///\return <tt> (*this) </tt>
399 399
    Dfs &distMap(DistMap &m)
400 400
    {
401 401
      if(local_dist) {
402 402
        delete _dist;
403 403
        local_dist=false;
404 404
      }
405 405
      _dist = &m;
406 406
      return *this;
407 407
    }
408 408

	
409 409
  public:
410 410

	
411 411
    ///\name Execution Control
412 412
    ///The simplest way to execute the DFS algorithm is to use one of the
413 413
    ///member functions called \ref run(Node) "run()".\n
414 414
    ///If you need more control on the execution, first you have to call
415 415
    ///\ref init(), then you can add a source node with \ref addSource()
416 416
    ///and perform the actual computation with \ref start().
417 417
    ///This procedure can be repeated if there are nodes that have not
418 418
    ///been reached.
419 419

	
420 420
    ///@{
421 421

	
422 422
    ///\brief Initializes the internal data structures.
423 423
    ///
424 424
    ///Initializes the internal data structures.
425 425
    void init()
426 426
    {
427 427
      create_maps();
428 428
      _stack.resize(countNodes(*G));
429 429
      _stack_head=-1;
430 430
      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
431 431
        _pred->set(u,INVALID);
432 432
        _reached->set(u,false);
433 433
        _processed->set(u,false);
434 434
      }
435 435
    }
436 436

	
437 437
    ///Adds a new source node.
438 438

	
439 439
    ///Adds a new source node to the set of nodes to be processed.
440 440
    ///
441 441
    ///\pre The stack must be empty. Otherwise the algorithm gives
442 442
    ///wrong results. (One of the outgoing arcs of all the source nodes
443 443
    ///except for the last one will not be visited and distances will
444 444
    ///also be wrong.)
445 445
    void addSource(Node s)
446 446
    {
447 447
      LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
448 448
      if(!(*_reached)[s])
449 449
        {
450 450
          _reached->set(s,true);
451 451
          _pred->set(s,INVALID);
452 452
          OutArcIt e(*G,s);
453 453
          if(e!=INVALID) {
454 454
            _stack[++_stack_head]=e;
455 455
            _dist->set(s,_stack_head);
456 456
          }
457 457
          else {
458 458
            _processed->set(s,true);
459 459
            _dist->set(s,0);
460 460
          }
461 461
        }
462 462
    }
463 463

	
464 464
    ///Processes the next arc.
465 465

	
Ignore white space 6 line context
... ...
@@ -33,513 +33,513 @@
33 33
#include <lemon/path.h>
34 34

	
35 35
namespace lemon {
36 36

	
37 37
  /// \brief Default operation traits for the Dijkstra algorithm class.
38 38
  ///
39 39
  /// This operation traits class defines all computational operations and
40 40
  /// constants which are used in the Dijkstra algorithm.
41 41
  template <typename V>
42 42
  struct DijkstraDefaultOperationTraits {
43 43
    /// \e
44 44
    typedef V Value;
45 45
    /// \brief Gives back the zero value of the type.
46 46
    static Value zero() {
47 47
      return static_cast<Value>(0);
48 48
    }
49 49
    /// \brief Gives back the sum of the given two elements.
50 50
    static Value plus(const Value& left, const Value& right) {
51 51
      return left + right;
52 52
    }
53 53
    /// \brief Gives back true only if the first value is less than the second.
54 54
    static bool less(const Value& left, const Value& right) {
55 55
      return left < right;
56 56
    }
57 57
  };
58 58

	
59 59
  ///Default traits class of Dijkstra class.
60 60

	
61 61
  ///Default traits class of Dijkstra class.
62 62
  ///\tparam GR The type of the digraph.
63 63
  ///\tparam LEN The type of the length map.
64 64
  template<typename GR, typename LEN>
65 65
  struct DijkstraDefaultTraits
66 66
  {
67 67
    ///The type of the digraph the algorithm runs on.
68 68
    typedef GR Digraph;
69 69

	
70 70
    ///The type of the map that stores the arc lengths.
71 71

	
72 72
    ///The type of the map that stores the arc lengths.
73 73
    ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
74 74
    typedef LEN LengthMap;
75 75
    ///The type of the length of the arcs.
76 76
    typedef typename LEN::Value Value;
77 77

	
78 78
    /// Operation traits for %Dijkstra algorithm.
79 79

	
80 80
    /// This class defines the operations that are used in the algorithm.
81 81
    /// \see DijkstraDefaultOperationTraits
82 82
    typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
83 83

	
84 84
    /// The cross reference type used by the heap.
85 85

	
86 86
    /// The cross reference type used by the heap.
87 87
    /// Usually it is \c Digraph::NodeMap<int>.
88 88
    typedef typename Digraph::template NodeMap<int> HeapCrossRef;
89 89
    ///Instantiates a \c HeapCrossRef.
90 90

	
91 91
    ///This function instantiates a \ref HeapCrossRef.
92 92
    /// \param g is the digraph, to which we would like to define the
93 93
    /// \ref HeapCrossRef.
94 94
    static HeapCrossRef *createHeapCrossRef(const Digraph &g)
95 95
    {
96 96
      return new HeapCrossRef(g);
97 97
    }
98 98

	
99 99
    ///The heap type used by the %Dijkstra algorithm.
100 100

	
101 101
    ///The heap type used by the Dijkstra algorithm.
102 102
    ///
103 103
    ///\sa BinHeap
104 104
    ///\sa Dijkstra
105 105
    typedef BinHeap<typename LEN::Value, HeapCrossRef, std::less<Value> > Heap;
106 106
    ///Instantiates a \c Heap.
107 107

	
108 108
    ///This function instantiates a \ref Heap.
109 109
    static Heap *createHeap(HeapCrossRef& r)
110 110
    {
111 111
      return new Heap(r);
112 112
    }
113 113

	
114 114
    ///\brief The type of the map that stores the predecessor
115 115
    ///arcs of the shortest paths.
116 116
    ///
117 117
    ///The type of the map that stores the predecessor
118 118
    ///arcs of the shortest paths.
119 119
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
120 120
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
121 121
    ///Instantiates a \c PredMap.
122 122

	
123 123
    ///This function instantiates a \ref PredMap.
124 124
    ///\param g is the digraph, to which we would like to define the
125 125
    ///\ref PredMap.
126 126
    static PredMap *createPredMap(const Digraph &g)
127 127
    {
128 128
      return new PredMap(g);
129 129
    }
130 130

	
131 131
    ///The type of the map that indicates which nodes are processed.
132 132

	
133 133
    ///The type of the map that indicates which nodes are processed.
134 134
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
135 135
    ///By default it is a NullMap.
136 136
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
137 137
    ///Instantiates a \c ProcessedMap.
138 138

	
139 139
    ///This function instantiates a \ref ProcessedMap.
140 140
    ///\param g is the digraph, to which
141 141
    ///we would like to define the \ref ProcessedMap.
142 142
#ifdef DOXYGEN
143 143
    static ProcessedMap *createProcessedMap(const Digraph &g)
144 144
#else
145 145
    static ProcessedMap *createProcessedMap(const Digraph &)
146 146
#endif
147 147
    {
148 148
      return new ProcessedMap();
149 149
    }
150 150

	
151 151
    ///The type of the map that stores the distances of the nodes.
152 152

	
153 153
    ///The type of the map that stores the distances of the nodes.
154 154
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
155 155
    typedef typename Digraph::template NodeMap<typename LEN::Value> DistMap;
156 156
    ///Instantiates a \c DistMap.
157 157

	
158 158
    ///This function instantiates a \ref DistMap.
159 159
    ///\param g is the digraph, to which we would like to define
160 160
    ///the \ref DistMap.
161 161
    static DistMap *createDistMap(const Digraph &g)
162 162
    {
163 163
      return new DistMap(g);
164 164
    }
165 165
  };
166 166

	
167 167
  ///%Dijkstra algorithm class.
168 168

	
169 169
  /// \ingroup shortest_path
170 170
  ///This class provides an efficient implementation of the %Dijkstra algorithm.
171 171
  ///
172 172
  ///The arc lengths are passed to the algorithm using a
173 173
  ///\ref concepts::ReadMap "ReadMap",
174 174
  ///so it is easy to change it to any kind of length.
175 175
  ///The type of the length is determined by the
176 176
  ///\ref concepts::ReadMap::Value "Value" of the length map.
177 177
  ///It is also possible to change the underlying priority heap.
178 178
  ///
179 179
  ///There is also a \ref dijkstra() "function-type interface" for the
180 180
  ///%Dijkstra algorithm, which is convenient in the simplier cases and
181 181
  ///it can be used easier.
182 182
  ///
183 183
  ///\tparam GR The type of the digraph the algorithm runs on.
184 184
  ///The default type is \ref ListDigraph.
185 185
  ///\tparam LEN A \ref concepts::ReadMap "readable" arc map that specifies
186 186
  ///the lengths of the arcs.
187 187
  ///It is read once for each arc, so the map may involve in
188 188
  ///relatively time consuming process to compute the arc lengths if
189 189
  ///it is necessary. The default map type is \ref
190 190
  ///concepts::Digraph::ArcMap "GR::ArcMap<int>".
191 191
#ifdef DOXYGEN
192 192
  template <typename GR, typename LEN, typename TR>
193 193
#else
194 194
  template <typename GR=ListDigraph,
195 195
            typename LEN=typename GR::template ArcMap<int>,
196 196
            typename TR=DijkstraDefaultTraits<GR,LEN> >
197 197
#endif
198 198
  class Dijkstra {
199 199
  public:
200 200

	
201 201
    ///The type of the digraph the algorithm runs on.
202 202
    typedef typename TR::Digraph Digraph;
203 203

	
204 204
    ///The type of the length of the arcs.
205 205
    typedef typename TR::LengthMap::Value Value;
206 206
    ///The type of the map that stores the arc lengths.
207 207
    typedef typename TR::LengthMap LengthMap;
208 208
    ///\brief The type of the map that stores the predecessor arcs of the
209 209
    ///shortest paths.
210 210
    typedef typename TR::PredMap PredMap;
211 211
    ///The type of the map that stores the distances of the nodes.
212 212
    typedef typename TR::DistMap DistMap;
213 213
    ///The type of the map that indicates which nodes are processed.
214 214
    typedef typename TR::ProcessedMap ProcessedMap;
215 215
    ///The type of the paths.
216 216
    typedef PredMapPath<Digraph, PredMap> Path;
217 217
    ///The cross reference type used for the current heap.
218 218
    typedef typename TR::HeapCrossRef HeapCrossRef;
219 219
    ///The heap type used by the algorithm.
220 220
    typedef typename TR::Heap Heap;
221 221
    ///\brief The \ref DijkstraDefaultOperationTraits "operation traits class"
222 222
    ///of the algorithm.
223 223
    typedef typename TR::OperationTraits OperationTraits;
224 224

	
225 225
    ///The \ref DijkstraDefaultTraits "traits class" of the algorithm.
226 226
    typedef TR Traits;
227 227

	
228 228
  private:
229 229

	
230 230
    typedef typename Digraph::Node Node;
231 231
    typedef typename Digraph::NodeIt NodeIt;
232 232
    typedef typename Digraph::Arc Arc;
233 233
    typedef typename Digraph::OutArcIt OutArcIt;
234 234

	
235 235
    //Pointer to the underlying digraph.
236 236
    const Digraph *G;
237 237
    //Pointer to the length map.
238 238
    const LengthMap *_length;
239 239
    //Pointer to the map of predecessors arcs.
240 240
    PredMap *_pred;
241 241
    //Indicates if _pred is locally allocated (true) or not.
242 242
    bool local_pred;
243 243
    //Pointer to the map of distances.
244 244
    DistMap *_dist;
245 245
    //Indicates if _dist is locally allocated (true) or not.
246 246
    bool local_dist;
247 247
    //Pointer to the map of processed status of the nodes.
248 248
    ProcessedMap *_processed;
249 249
    //Indicates if _processed is locally allocated (true) or not.
250 250
    bool local_processed;
251 251
    //Pointer to the heap cross references.
252 252
    HeapCrossRef *_heap_cross_ref;
253 253
    //Indicates if _heap_cross_ref is locally allocated (true) or not.
254 254
    bool local_heap_cross_ref;
255 255
    //Pointer to the heap.
256 256
    Heap *_heap;
257 257
    //Indicates if _heap is locally allocated (true) or not.
258 258
    bool local_heap;
259 259

	
260 260
    //Creates the maps if necessary.
261 261
    void create_maps()
262 262
    {
263 263
      if(!_pred) {
264 264
        local_pred = true;
265 265
        _pred = Traits::createPredMap(*G);
266 266
      }
267 267
      if(!_dist) {
268 268
        local_dist = true;
269 269
        _dist = Traits::createDistMap(*G);
270 270
      }
271 271
      if(!_processed) {
272 272
        local_processed = true;
273 273
        _processed = Traits::createProcessedMap(*G);
274 274
      }
275 275
      if (!_heap_cross_ref) {
276 276
        local_heap_cross_ref = true;
277 277
        _heap_cross_ref = Traits::createHeapCrossRef(*G);
278 278
      }
279 279
      if (!_heap) {
280 280
        local_heap = true;
281 281
        _heap = Traits::createHeap(*_heap_cross_ref);
282 282
      }
283 283
    }
284 284

	
285 285
  public:
286 286

	
287 287
    typedef Dijkstra Create;
288 288

	
289
    ///\name Named template parameters
289
    ///\name Named Template Parameters
290 290

	
291 291
    ///@{
292 292

	
293 293
    template <class T>
294 294
    struct SetPredMapTraits : public Traits {
295 295
      typedef T PredMap;
296 296
      static PredMap *createPredMap(const Digraph &)
297 297
      {
298 298
        LEMON_ASSERT(false, "PredMap is not initialized");
299 299
        return 0; // ignore warnings
300 300
      }
301 301
    };
302 302
    ///\brief \ref named-templ-param "Named parameter" for setting
303 303
    ///\c PredMap type.
304 304
    ///
305 305
    ///\ref named-templ-param "Named parameter" for setting
306 306
    ///\c PredMap type.
307 307
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
308 308
    template <class T>
309 309
    struct SetPredMap
310 310
      : public Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > {
311 311
      typedef Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > Create;
312 312
    };
313 313

	
314 314
    template <class T>
315 315
    struct SetDistMapTraits : public Traits {
316 316
      typedef T DistMap;
317 317
      static DistMap *createDistMap(const Digraph &)
318 318
      {
319 319
        LEMON_ASSERT(false, "DistMap is not initialized");
320 320
        return 0; // ignore warnings
321 321
      }
322 322
    };
323 323
    ///\brief \ref named-templ-param "Named parameter" for setting
324 324
    ///\c DistMap type.
325 325
    ///
326 326
    ///\ref named-templ-param "Named parameter" for setting
327 327
    ///\c DistMap type.
328 328
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
329 329
    template <class T>
330 330
    struct SetDistMap
331 331
      : public Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > {
332 332
      typedef Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > Create;
333 333
    };
334 334

	
335 335
    template <class T>
336 336
    struct SetProcessedMapTraits : public Traits {
337 337
      typedef T ProcessedMap;
338 338
      static ProcessedMap *createProcessedMap(const Digraph &)
339 339
      {
340 340
        LEMON_ASSERT(false, "ProcessedMap is not initialized");
341 341
        return 0; // ignore warnings
342 342
      }
343 343
    };
344 344
    ///\brief \ref named-templ-param "Named parameter" for setting
345 345
    ///\c ProcessedMap type.
346 346
    ///
347 347
    ///\ref named-templ-param "Named parameter" for setting
348 348
    ///\c ProcessedMap type.
349 349
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
350 350
    template <class T>
351 351
    struct SetProcessedMap
352 352
      : public Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > {
353 353
      typedef Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > Create;
354 354
    };
355 355

	
356 356
    struct SetStandardProcessedMapTraits : public Traits {
357 357
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
358 358
      static ProcessedMap *createProcessedMap(const Digraph &g)
359 359
      {
360 360
        return new ProcessedMap(g);
361 361
      }
362 362
    };
363 363
    ///\brief \ref named-templ-param "Named parameter" for setting
364 364
    ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
365 365
    ///
366 366
    ///\ref named-templ-param "Named parameter" for setting
367 367
    ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
368 368
    ///If you don't set it explicitly, it will be automatically allocated.
369 369
    struct SetStandardProcessedMap
370 370
      : public Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits > {
371 371
      typedef Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits >
372 372
      Create;
373 373
    };
374 374

	
375 375
    template <class H, class CR>
376 376
    struct SetHeapTraits : public Traits {
377 377
      typedef CR HeapCrossRef;
378 378
      typedef H Heap;
379 379
      static HeapCrossRef *createHeapCrossRef(const Digraph &) {
380 380
        LEMON_ASSERT(false, "HeapCrossRef is not initialized");
381 381
        return 0; // ignore warnings
382 382
      }
383 383
      static Heap *createHeap(HeapCrossRef &)
384 384
      {
385 385
        LEMON_ASSERT(false, "Heap is not initialized");
386 386
        return 0; // ignore warnings
387 387
      }
388 388
    };
389 389
    ///\brief \ref named-templ-param "Named parameter" for setting
390 390
    ///heap and cross reference types
391 391
    ///
392 392
    ///\ref named-templ-param "Named parameter" for setting heap and cross
393 393
    ///reference types. If this named parameter is used, then external
394 394
    ///heap and cross reference objects must be passed to the algorithm
395 395
    ///using the \ref heap() function before calling \ref run(Node) "run()"
396 396
    ///or \ref init().
397 397
    ///\sa SetStandardHeap
398 398
    template <class H, class CR = typename Digraph::template NodeMap<int> >
399 399
    struct SetHeap
400 400
      : public Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > {
401 401
      typedef Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > Create;
402 402
    };
403 403

	
404 404
    template <class H, class CR>
405 405
    struct SetStandardHeapTraits : public Traits {
406 406
      typedef CR HeapCrossRef;
407 407
      typedef H Heap;
408 408
      static HeapCrossRef *createHeapCrossRef(const Digraph &G) {
409 409
        return new HeapCrossRef(G);
410 410
      }
411 411
      static Heap *createHeap(HeapCrossRef &R)
412 412
      {
413 413
        return new Heap(R);
414 414
      }
415 415
    };
416 416
    ///\brief \ref named-templ-param "Named parameter" for setting
417 417
    ///heap and cross reference types with automatic allocation
418 418
    ///
419 419
    ///\ref named-templ-param "Named parameter" for setting heap and cross
420 420
    ///reference types with automatic allocation.
421 421
    ///They should have standard constructor interfaces to be able to
422 422
    ///automatically created by the algorithm (i.e. the digraph should be
423 423
    ///passed to the constructor of the cross reference and the cross
424 424
    ///reference should be passed to the constructor of the heap).
425 425
    ///However external heap and cross reference objects could also be
426 426
    ///passed to the algorithm using the \ref heap() function before
427 427
    ///calling \ref run(Node) "run()" or \ref init().
428 428
    ///\sa SetHeap
429 429
    template <class H, class CR = typename Digraph::template NodeMap<int> >
430 430
    struct SetStandardHeap
431 431
      : public Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> > {
432 432
      typedef Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> >
433 433
      Create;
434 434
    };
435 435

	
436 436
    template <class T>
437 437
    struct SetOperationTraitsTraits : public Traits {
438 438
      typedef T OperationTraits;
439 439
    };
440 440

	
441 441
    /// \brief \ref named-templ-param "Named parameter" for setting
442 442
    ///\c OperationTraits type
443 443
    ///
444 444
    ///\ref named-templ-param "Named parameter" for setting
445 445
    ///\c OperationTraits type.
446 446
    template <class T>
447 447
    struct SetOperationTraits
448 448
      : public Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> > {
449 449
      typedef Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> >
450 450
      Create;
451 451
    };
452 452

	
453 453
    ///@}
454 454

	
455 455
  protected:
456 456

	
457 457
    Dijkstra() {}
458 458

	
459 459
  public:
460 460

	
461 461
    ///Constructor.
462 462

	
463 463
    ///Constructor.
464 464
    ///\param g The digraph the algorithm runs on.
465 465
    ///\param length The length map used by the algorithm.
466 466
    Dijkstra(const Digraph& g, const LengthMap& length) :
467 467
      G(&g), _length(&length),
468 468
      _pred(NULL), local_pred(false),
469 469
      _dist(NULL), local_dist(false),
470 470
      _processed(NULL), local_processed(false),
471 471
      _heap_cross_ref(NULL), local_heap_cross_ref(false),
472 472
      _heap(NULL), local_heap(false)
473 473
    { }
474 474

	
475 475
    ///Destructor.
476 476
    ~Dijkstra()
477 477
    {
478 478
      if(local_pred) delete _pred;
479 479
      if(local_dist) delete _dist;
480 480
      if(local_processed) delete _processed;
481 481
      if(local_heap_cross_ref) delete _heap_cross_ref;
482 482
      if(local_heap) delete _heap;
483 483
    }
484 484

	
485 485
    ///Sets the length map.
486 486

	
487 487
    ///Sets the length map.
488 488
    ///\return <tt> (*this) </tt>
489 489
    Dijkstra &lengthMap(const LengthMap &m)
490 490
    {
491 491
      _length = &m;
492 492
      return *this;
493 493
    }
494 494

	
495 495
    ///Sets the map that stores the predecessor arcs.
496 496

	
497 497
    ///Sets the map that stores the predecessor arcs.
498 498
    ///If you don't use this function before calling \ref run(Node) "run()"
499 499
    ///or \ref init(), an instance will be allocated automatically.
500 500
    ///The destructor deallocates this automatically allocated map,
501 501
    ///of course.
502 502
    ///\return <tt> (*this) </tt>
503 503
    Dijkstra &predMap(PredMap &m)
504 504
    {
505 505
      if(local_pred) {
506 506
        delete _pred;
507 507
        local_pred=false;
508 508
      }
509 509
      _pred = &m;
510 510
      return *this;
511 511
    }
512 512

	
513 513
    ///Sets the map that indicates which nodes are processed.
514 514

	
515 515
    ///Sets the map that indicates which nodes are processed.
516 516
    ///If you don't use this function before calling \ref run(Node) "run()"
517 517
    ///or \ref init(), an instance will be allocated automatically.
518 518
    ///The destructor deallocates this automatically allocated map,
519 519
    ///of course.
520 520
    ///\return <tt> (*this) </tt>
521 521
    Dijkstra &processedMap(ProcessedMap &m)
522 522
    {
523 523
      if(local_processed) {
524 524
        delete _processed;
525 525
        local_processed=false;
526 526
      }
527 527
      _processed = &m;
528 528
      return *this;
529 529
    }
530 530

	
531 531
    ///Sets the map that stores the distances of the nodes.
532 532

	
533 533
    ///Sets the map that stores the distances of the nodes calculated by the
534 534
    ///algorithm.
535 535
    ///If you don't use this function before calling \ref run(Node) "run()"
536 536
    ///or \ref init(), an instance will be allocated automatically.
537 537
    ///The destructor deallocates this automatically allocated map,
538 538
    ///of course.
539 539
    ///\return <tt> (*this) </tt>
540 540
    Dijkstra &distMap(DistMap &m)
541 541
    {
542 542
      if(local_dist) {
543 543
        delete _dist;
544 544
        local_dist=false;
545 545
      }
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_DIMACS_H
20 20
#define LEMON_DIMACS_H
21 21

	
22 22
#include <iostream>
23 23
#include <string>
24 24
#include <vector>
25 25
#include <limits>
26 26
#include <lemon/maps.h>
27 27
#include <lemon/error.h>
28 28
/// \ingroup dimacs_group
29 29
/// \file
30 30
/// \brief DIMACS file format reader.
31 31

	
32 32
namespace lemon {
33 33

	
34 34
  /// \addtogroup dimacs_group
35 35
  /// @{
36 36

	
37 37
  /// DIMACS file type descriptor.
38 38
  struct DimacsDescriptor
39 39
  {
40
    ///File type enum
41
    enum Type
42
      {
43
        NONE, MIN, MAX, SP, MAT
44
      };
40
    ///\brief DIMACS file type enum
41
    ///
42
    ///DIMACS file type enum.
43
    enum Type {
44
      NONE,  ///< Undefined type.
45
      MIN,   ///< DIMACS file type for minimum cost flow problems.
46
      MAX,   ///< DIMACS file type for maximum flow problems.
47
      SP,    ///< DIMACS file type for shostest path problems.
48
      MAT    ///< DIMACS file type for plain graphs and matching problems.
49
    };
45 50
    ///The file type
46 51
    Type type;
47 52
    ///The number of nodes in the graph
48 53
    int nodeNum;
49 54
    ///The number of edges in the graph
50 55
    int edgeNum;
51 56
    int lineShift;
52
    /// Constructor. Sets the type to NONE.
57
    ///Constructor. It sets the type to \c NONE.
53 58
    DimacsDescriptor() : type(NONE) {}
54 59
  };
55 60

	
56 61
  ///Discover the type of a DIMACS file
57 62

	
58
  ///It starts seeking the beginning of the file for the problem type
59
  ///and size info. The found data is returned in a special struct
60
  ///that can be evaluated and passed to the appropriate reader
61
  ///function.
63
  ///This function starts seeking the beginning of the given file for the
64
  ///problem type and size info. 
65
  ///The found data is returned in a special struct that can be evaluated
66
  ///and passed to the appropriate reader function.
62 67
  DimacsDescriptor dimacsType(std::istream& is)
63 68
  {
64 69
    DimacsDescriptor r;
65 70
    std::string problem,str;
66 71
    char c;
67 72
    r.lineShift=0;
68 73
    while (is >> c)
69 74
      switch(c)
70 75
        {
71 76
        case 'p':
72 77
          if(is >> problem >> r.nodeNum >> r.edgeNum)
73 78
            {
74 79
              getline(is, str);
75 80
              r.lineShift++;
76 81
              if(problem=="min") r.type=DimacsDescriptor::MIN;
77 82
              else if(problem=="max") r.type=DimacsDescriptor::MAX;
78 83
              else if(problem=="sp") r.type=DimacsDescriptor::SP;
79 84
              else if(problem=="mat") r.type=DimacsDescriptor::MAT;
80 85
              else throw FormatError("Unknown problem type");
81 86
              return r;
82 87
            }
83 88
          else
84 89
            {
85 90
              throw FormatError("Missing or wrong problem type declaration.");
86 91
            }
87 92
          break;
88 93
        case 'c':
89 94
          getline(is, str);
90 95
          r.lineShift++;
91 96
          break;
92 97
        default:
93 98
          throw FormatError("Unknown DIMACS declaration.");
94 99
        }
95 100
    throw FormatError("Missing problem type declaration.");
96 101
  }
97 102

	
98 103

	
99

	
100
  /// DIMACS minimum cost flow reader function.
104
  /// \brief DIMACS minimum cost flow reader function.
101 105
  ///
102 106
  /// This function reads a minimum cost flow instance from DIMACS format,
103 107
  /// i.e. from a DIMACS file having a line starting with
104 108
  /// \code
105 109
  ///   p min
106 110
  /// \endcode
107 111
  /// At the beginning, \c g is cleared by \c g.clear(). The supply
108 112
  /// amount of the nodes are written to the \c supply node map
109 113
  /// (they are signed values). The lower bounds, capacities and costs
110 114
  /// of the arcs are written to the \c lower, \c capacity and \c cost
111 115
  /// arc maps.
112 116
  ///
113 117
  /// If the capacity of an arc is less than the lower bound, it will
114 118
  /// be set to "infinite" instead. The actual value of "infinite" is
115 119
  /// contolled by the \c infty parameter. If it is 0 (the default value),
116 120
  /// \c std::numeric_limits<Capacity>::infinity() will be used if available,
117 121
  /// \c std::numeric_limits<Capacity>::max() otherwise. If \c infty is set to
118 122
  /// a non-zero value, that value will be used as "infinite".
119 123
  ///
120 124
  /// If the file type was previously evaluated by dimacsType(), then
121 125
  /// the descriptor struct should be given by the \c dest parameter.
122 126
  template <typename Digraph, typename LowerMap,
123 127
            typename CapacityMap, typename CostMap,
124 128
            typename SupplyMap>
125 129
  void readDimacsMin(std::istream& is,
126 130
                     Digraph &g,
127 131
                     LowerMap& lower,
128 132
                     CapacityMap& capacity,
129 133
                     CostMap& cost,
130 134
                     SupplyMap& supply,
131 135
                     typename CapacityMap::Value infty = 0,
132 136
                     DimacsDescriptor desc=DimacsDescriptor())
133 137
  {
134 138
    g.clear();
135 139
    std::vector<typename Digraph::Node> nodes;
136 140
    typename Digraph::Arc e;
137 141
    std::string problem, str;
138 142
    char c;
139 143
    int i, j;
140 144
    if(desc.type==DimacsDescriptor::NONE) desc=dimacsType(is);
141 145
    if(desc.type!=DimacsDescriptor::MIN)
142 146
      throw FormatError("Problem type mismatch");
143 147

	
144 148
    nodes.resize(desc.nodeNum + 1);
145 149
    for (int k = 1; k <= desc.nodeNum; ++k) {
146 150
      nodes[k] = g.addNode();
147 151
      supply.set(nodes[k], 0);
148 152
    }
149 153

	
150 154
    typename SupplyMap::Value sup;
151 155
    typename CapacityMap::Value low;
152 156
    typename CapacityMap::Value cap;
153 157
    typename CostMap::Value co;
154 158
    typedef typename CapacityMap::Value Capacity;
155 159
    if(infty==0)
156 160
      infty = std::numeric_limits<Capacity>::has_infinity ?
157 161
        std::numeric_limits<Capacity>::infinity() :
158 162
        std::numeric_limits<Capacity>::max();
159 163

	
160 164
    while (is >> c) {
161 165
      switch (c) {
162 166
      case 'c': // comment line
163 167
        getline(is, str);
164 168
        break;
165 169
      case 'n': // node definition line
166 170
        is >> i >> sup;
167 171
        getline(is, str);
168 172
        supply.set(nodes[i], sup);
169 173
        break;
170 174
      case 'a': // arc definition line
171 175
        is >> i >> j >> low >> cap >> co;
172 176
        getline(is, str);
173 177
        e = g.addArc(nodes[i], nodes[j]);
174 178
        lower.set(e, low);
175 179
        if (cap >= low)
176 180
          capacity.set(e, cap);
177 181
        else
178 182
          capacity.set(e, infty);
179 183
        cost.set(e, co);
180 184
        break;
181 185
      }
182 186
    }
183 187
  }
184 188

	
185 189
  template<typename Digraph, typename CapacityMap>
186 190
  void _readDimacs(std::istream& is,
187 191
                   Digraph &g,
188 192
                   CapacityMap& capacity,
189 193
                   typename Digraph::Node &s,
190 194
                   typename Digraph::Node &t,
191 195
                   typename CapacityMap::Value infty = 0,
192 196
                   DimacsDescriptor desc=DimacsDescriptor()) {
193 197
    g.clear();
194 198
    s=t=INVALID;
195 199
    std::vector<typename Digraph::Node> nodes;
196 200
    typename Digraph::Arc e;
197 201
    char c, d;
198 202
    int i, j;
199 203
    typename CapacityMap::Value _cap;
200 204
    std::string str;
201 205
    nodes.resize(desc.nodeNum + 1);
202 206
    for (int k = 1; k <= desc.nodeNum; ++k) {
203 207
      nodes[k] = g.addNode();
204 208
    }
205 209
    typedef typename CapacityMap::Value Capacity;
206 210

	
207 211
    if(infty==0)
208 212
      infty = std::numeric_limits<Capacity>::has_infinity ?
209 213
        std::numeric_limits<Capacity>::infinity() :
210 214
        std::numeric_limits<Capacity>::max();
211 215
 
212 216
    while (is >> c) {
213 217
      switch (c) {
214 218
      case 'c': // comment line
215 219
        getline(is, str);
216 220
        break;
217 221
      case 'n': // node definition line
218 222
        if (desc.type==DimacsDescriptor::SP) { // shortest path problem
219 223
          is >> i;
220 224
          getline(is, str);
221 225
          s = nodes[i];
222 226
        }
223 227
        if (desc.type==DimacsDescriptor::MAX) { // max flow problem
224 228
          is >> i >> d;
225 229
          getline(is, str);
226 230
          if (d == 's') s = nodes[i];
227 231
          if (d == 't') t = nodes[i];
228 232
        }
229 233
        break;
230 234
      case 'a': // arc definition line
231 235
        if (desc.type==DimacsDescriptor::SP) {
232 236
          is >> i >> j >> _cap;
233 237
          getline(is, str);
234 238
          e = g.addArc(nodes[i], nodes[j]);
235 239
          capacity.set(e, _cap);
236 240
        } 
237 241
        else if (desc.type==DimacsDescriptor::MAX) {
238 242
          is >> i >> j >> _cap;
239 243
          getline(is, str);
240 244
          e = g.addArc(nodes[i], nodes[j]);
241 245
          if (_cap >= 0)
242 246
            capacity.set(e, _cap);
243 247
          else
244 248
            capacity.set(e, infty);
245 249
        }
246 250
        else {
247 251
          is >> i >> j;
248 252
          getline(is, str);
249 253
          g.addArc(nodes[i], nodes[j]);
250 254
        }
251 255
        break;
252 256
      }
253 257
    }
254 258
  }
255 259

	
256
  /// DIMACS maximum flow reader function.
260
  /// \brief DIMACS maximum flow reader function.
257 261
  ///
258 262
  /// This function reads a maximum flow instance from DIMACS format,
259 263
  /// i.e. from a DIMACS file having a line starting with
260 264
  /// \code
261 265
  ///   p max
262 266
  /// \endcode
263 267
  /// At the beginning, \c g is cleared by \c g.clear(). The arc
264 268
  /// capacities are written to the \c capacity arc map and \c s and
265 269
  /// \c t are set to the source and the target nodes.
266 270
  ///
267 271
  /// If the capacity of an arc is negative, it will
268 272
  /// be set to "infinite" instead. The actual value of "infinite" is
269 273
  /// contolled by the \c infty parameter. If it is 0 (the default value),
270 274
  /// \c std::numeric_limits<Capacity>::infinity() will be used if available,
271 275
  /// \c std::numeric_limits<Capacity>::max() otherwise. If \c infty is set to
272 276
  /// a non-zero value, that value will be used as "infinite".
273 277
  ///
274 278
  /// If the file type was previously evaluated by dimacsType(), then
275 279
  /// the descriptor struct should be given by the \c dest parameter.
276 280
  template<typename Digraph, typename CapacityMap>
277 281
  void readDimacsMax(std::istream& is,
278 282
                     Digraph &g,
279 283
                     CapacityMap& capacity,
280 284
                     typename Digraph::Node &s,
281 285
                     typename Digraph::Node &t,
282 286
                     typename CapacityMap::Value infty = 0,
283 287
                     DimacsDescriptor desc=DimacsDescriptor()) {
284 288
    if(desc.type==DimacsDescriptor::NONE) desc=dimacsType(is);
285 289
    if(desc.type!=DimacsDescriptor::MAX)
286 290
      throw FormatError("Problem type mismatch");
287 291
    _readDimacs(is,g,capacity,s,t,infty,desc);
288 292
  }
289 293

	
290
  /// DIMACS shortest path reader function.
294
  /// \brief DIMACS shortest path reader function.
291 295
  ///
292 296
  /// This function reads a shortest path instance from DIMACS format,
293 297
  /// i.e. from a DIMACS file having a line starting with
294 298
  /// \code
295 299
  ///   p sp
296 300
  /// \endcode
297 301
  /// At the beginning, \c g is cleared by \c g.clear(). The arc
298 302
  /// lengths are written to the \c length arc map and \c s is set to the
299 303
  /// source node.
300 304
  ///
301 305
  /// If the file type was previously evaluated by dimacsType(), then
302 306
  /// the descriptor struct should be given by the \c dest parameter.
303 307
  template<typename Digraph, typename LengthMap>
304 308
  void readDimacsSp(std::istream& is,
305 309
                    Digraph &g,
306 310
                    LengthMap& length,
307 311
                    typename Digraph::Node &s,
308 312
                    DimacsDescriptor desc=DimacsDescriptor()) {
309 313
    typename Digraph::Node t;
310 314
    if(desc.type==DimacsDescriptor::NONE) desc=dimacsType(is);
311 315
    if(desc.type!=DimacsDescriptor::SP)
312 316
      throw FormatError("Problem type mismatch");
313 317
    _readDimacs(is, g, length, s, t, 0, desc);
314 318
  }
315 319

	
316
  /// DIMACS capacitated digraph reader function.
320
  /// \brief DIMACS capacitated digraph reader function.
317 321
  ///
318 322
  /// This function reads an arc capacitated digraph instance from
319 323
  /// DIMACS 'max' or 'sp' format.
320 324
  /// At the beginning, \c g is cleared by \c g.clear()
321 325
  /// and the arc capacities/lengths are written to the \c capacity
322 326
  /// arc map.
323 327
  ///
324 328
  /// In case of the 'max' format, if the capacity of an arc is negative,
325 329
  /// it will
326 330
  /// be set to "infinite" instead. The actual value of "infinite" is
327 331
  /// contolled by the \c infty parameter. If it is 0 (the default value),
328 332
  /// \c std::numeric_limits<Capacity>::infinity() will be used if available,
329 333
  /// \c std::numeric_limits<Capacity>::max() otherwise. If \c infty is set to
330 334
  /// a non-zero value, that value will be used as "infinite".
331 335
  ///
332 336
  /// If the file type was previously evaluated by dimacsType(), then
333 337
  /// the descriptor struct should be given by the \c dest parameter.
334 338
  template<typename Digraph, typename CapacityMap>
335 339
  void readDimacsCap(std::istream& is,
336 340
                     Digraph &g,
337 341
                     CapacityMap& capacity,
338 342
                     typename CapacityMap::Value infty = 0,
339 343
                     DimacsDescriptor desc=DimacsDescriptor()) {
340 344
    typename Digraph::Node u,v;
341 345
    if(desc.type==DimacsDescriptor::NONE) desc=dimacsType(is);
342 346
    if(desc.type!=DimacsDescriptor::MAX || desc.type!=DimacsDescriptor::SP)
343 347
      throw FormatError("Problem type mismatch");
344 348
    _readDimacs(is, g, capacity, u, v, infty, desc);
345 349
  }
346 350

	
347 351
  template<typename Graph>
348 352
  typename enable_if<lemon::UndirectedTagIndicator<Graph>,void>::type
349 353
  _addArcEdge(Graph &g, typename Graph::Node s, typename Graph::Node t,
350 354
              dummy<0> = 0)
351 355
  {
352 356
    g.addEdge(s,t);
353 357
  }
354 358
  template<typename Graph>
355 359
  typename disable_if<lemon::UndirectedTagIndicator<Graph>,void>::type
356 360
  _addArcEdge(Graph &g, typename Graph::Node s, typename Graph::Node t,
357 361
              dummy<1> = 1)
358 362
  {
359 363
    g.addArc(s,t);
360 364
  }
361 365
  
362
  /// DIMACS plain (di)graph reader function.
366
  /// \brief DIMACS plain (di)graph reader function.
363 367
  ///
364
  /// This function reads a (di)graph without any designated nodes and
365
  /// maps from DIMACS format, i.e. from DIMACS files having a line
366
  /// starting with
368
  /// This function reads a plain (di)graph without any designated nodes
369
  /// and maps (e.g. a matching instance) from DIMACS format, i.e. from 
370
  /// DIMACS files having a line starting with
367 371
  /// \code
368 372
  ///   p mat
369 373
  /// \endcode
370 374
  /// At the beginning, \c g is cleared by \c g.clear().
371 375
  ///
372 376
  /// If the file type was previously evaluated by dimacsType(), then
373 377
  /// the descriptor struct should be given by the \c dest parameter.
374 378
  template<typename Graph>
375 379
  void readDimacsMat(std::istream& is, Graph &g,
376 380
                     DimacsDescriptor desc=DimacsDescriptor())
377 381
  {
378 382
    if(desc.type==DimacsDescriptor::NONE) desc=dimacsType(is);
379 383
    if(desc.type!=DimacsDescriptor::MAT)
380 384
      throw FormatError("Problem type mismatch");
381 385

	
382 386
    g.clear();
383 387
    std::vector<typename Graph::Node> nodes;
384 388
    char c;
385 389
    int i, j;
386 390
    std::string str;
387 391
    nodes.resize(desc.nodeNum + 1);
388 392
    for (int k = 1; k <= desc.nodeNum; ++k) {
389 393
      nodes[k] = g.addNode();
390 394
    }
391 395
    
392 396
    while (is >> c) {
393 397
      switch (c) {
394 398
      case 'c': // comment line
395 399
        getline(is, str);
396 400
        break;
397 401
      case 'n': // node definition line
398 402
        break;
399 403
      case 'a': // arc definition line
400 404
        is >> i >> j;
401 405
        getline(is, str);
402 406
        _addArcEdge(g,nodes[i], nodes[j]);
403 407
        break;
404 408
      }
405 409
    }
406 410
  }
407 411

	
408 412
  /// DIMACS plain digraph writer function.
409 413
  ///
410 414
  /// This function writes a digraph without any designated nodes and
411 415
  /// maps into DIMACS format, i.e. into DIMACS file having a line
412 416
  /// starting with
413 417
  /// \code
414 418
  ///   p mat
415 419
  /// \endcode
416 420
  /// If \c comment is not empty, then it will be printed in the first line
417 421
  /// prefixed by 'c'.
418 422
  template<typename Digraph>
419 423
  void writeDimacsMat(std::ostream& os, const Digraph &g,
420 424
                      std::string comment="") {
421 425
    typedef typename Digraph::NodeIt NodeIt;
422 426
    typedef typename Digraph::ArcIt ArcIt;
423 427

	
424 428
    if(!comment.empty())
425 429
      os << "c " << comment << std::endl;
426 430
    os << "p mat " << g.nodeNum() << " " << g.arcNum() << std::endl;
427 431

	
428 432
    typename Digraph::template NodeMap<int> nodes(g);
429 433
    int i = 1;
430 434
    for(NodeIt v(g); v != INVALID; ++v) {
431 435
      nodes.set(v, i);
432 436
      ++i;
433 437
    }
434 438
    for(ArcIt e(g); e != INVALID; ++e) {
435 439
      os << "a " << nodes[g.source(e)] << " " << nodes[g.target(e)]
436 440
         << std::endl;
437 441
    }
438 442
  }
439 443

	
440 444
  /// @}
441 445

	
442 446
} //namespace lemon
443 447

	
444 448
#endif //LEMON_DIMACS_H
Ignore white space 6 line context
... ...
@@ -15,528 +15,524 @@
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_GRAPH_TO_EPS_H
20 20
#define LEMON_GRAPH_TO_EPS_H
21 21

	
22 22
#include<iostream>
23 23
#include<fstream>
24 24
#include<sstream>
25 25
#include<algorithm>
26 26
#include<vector>
27 27

	
28 28
#ifndef WIN32
29 29
#include<sys/time.h>
30 30
#include<ctime>
31 31
#else
32 32
#include<lemon/bits/windows.h>
33 33
#endif
34 34

	
35 35
#include<lemon/math.h>
36 36
#include<lemon/core.h>
37 37
#include<lemon/dim2.h>
38 38
#include<lemon/maps.h>
39 39
#include<lemon/color.h>
40 40
#include<lemon/bits/bezier.h>
41 41
#include<lemon/error.h>
42 42

	
43 43

	
44 44
///\ingroup eps_io
45 45
///\file
46 46
///\brief A well configurable tool for visualizing graphs
47 47

	
48 48
namespace lemon {
49 49

	
50 50
  namespace _graph_to_eps_bits {
51 51
    template<class MT>
52 52
    class _NegY {
53 53
    public:
54 54
      typedef typename MT::Key Key;
55 55
      typedef typename MT::Value Value;
56 56
      const MT &map;
57 57
      int yscale;
58 58
      _NegY(const MT &m,bool b) : map(m), yscale(1-b*2) {}
59 59
      Value operator[](Key n) { return Value(map[n].x,map[n].y*yscale);}
60 60
    };
61 61
  }
62 62

	
63 63
///Default traits class of GraphToEps
64 64

	
65 65
///Default traits class of \ref GraphToEps.
66 66
///
67 67
///\param GR is the type of the underlying graph.
68 68
template<class GR>
69 69
struct DefaultGraphToEpsTraits
70 70
{
71 71
  typedef GR Graph;
72 72
  typedef typename Graph::Node Node;
73 73
  typedef typename Graph::NodeIt NodeIt;
74 74
  typedef typename Graph::Arc Arc;
75 75
  typedef typename Graph::ArcIt ArcIt;
76 76
  typedef typename Graph::InArcIt InArcIt;
77 77
  typedef typename Graph::OutArcIt OutArcIt;
78 78

	
79 79

	
80 80
  const Graph &g;
81 81

	
82 82
  std::ostream& os;
83 83

	
84 84
  typedef ConstMap<typename Graph::Node,dim2::Point<double> > CoordsMapType;
85 85
  CoordsMapType _coords;
86 86
  ConstMap<typename Graph::Node,double > _nodeSizes;
87 87
  ConstMap<typename Graph::Node,int > _nodeShapes;
88 88

	
89 89
  ConstMap<typename Graph::Node,Color > _nodeColors;
90 90
  ConstMap<typename Graph::Arc,Color > _arcColors;
91 91

	
92 92
  ConstMap<typename Graph::Arc,double > _arcWidths;
93 93

	
94 94
  double _arcWidthScale;
95 95

	
96 96
  double _nodeScale;
97 97
  double _xBorder, _yBorder;
98 98
  double _scale;
99 99
  double _nodeBorderQuotient;
100 100

	
101 101
  bool _drawArrows;
102 102
  double _arrowLength, _arrowWidth;
103 103

	
104 104
  bool _showNodes, _showArcs;
105 105

	
106 106
  bool _enableParallel;
107 107
  double _parArcDist;
108 108

	
109 109
  bool _showNodeText;
110 110
  ConstMap<typename Graph::Node,bool > _nodeTexts;
111 111
  double _nodeTextSize;
112 112

	
113 113
  bool _showNodePsText;
114 114
  ConstMap<typename Graph::Node,bool > _nodePsTexts;
115 115
  char *_nodePsTextsPreamble;
116 116

	
117 117
  bool _undirected;
118 118

	
119 119
  bool _pleaseRemoveOsStream;
120 120

	
121 121
  bool _scaleToA4;
122 122

	
123 123
  std::string _title;
124 124
  std::string _copyright;
125 125

	
126 126
  enum NodeTextColorType
127 127
    { DIST_COL=0, DIST_BW=1, CUST_COL=2, SAME_COL=3 } _nodeTextColorType;
128 128
  ConstMap<typename Graph::Node,Color > _nodeTextColors;
129 129

	
130 130
  bool _autoNodeScale;
131 131
  bool _autoArcWidthScale;
132 132

	
133 133
  bool _absoluteNodeSizes;
134 134
  bool _absoluteArcWidths;
135 135

	
136 136
  bool _negY;
137 137

	
138 138
  bool _preScale;
139 139
  ///Constructor
140 140

	
141 141
  ///Constructor
142 142
  ///\param gr  Reference to the graph to be printed.
143 143
  ///\param ost Reference to the output stream.
144 144
  ///By default it is <tt>std::cout</tt>.
145 145
  ///\param pros If it is \c true, then the \c ostream referenced by \c os
146 146
  ///will be explicitly deallocated by the destructor.
147 147
  DefaultGraphToEpsTraits(const GR &gr, std::ostream& ost = std::cout,
148 148
                          bool pros = false) :
149 149
    g(gr), os(ost),
150 150
    _coords(dim2::Point<double>(1,1)), _nodeSizes(1), _nodeShapes(0),
151 151
    _nodeColors(WHITE), _arcColors(BLACK),
152 152
    _arcWidths(1.0), _arcWidthScale(0.003),
153 153
    _nodeScale(.01), _xBorder(10), _yBorder(10), _scale(1.0),
154 154
    _nodeBorderQuotient(.1),
155 155
    _drawArrows(false), _arrowLength(1), _arrowWidth(0.3),
156 156
    _showNodes(true), _showArcs(true),
157 157
    _enableParallel(false), _parArcDist(1),
158 158
    _showNodeText(false), _nodeTexts(false), _nodeTextSize(1),
159 159
    _showNodePsText(false), _nodePsTexts(false), _nodePsTextsPreamble(0),
160 160
    _undirected(lemon::UndirectedTagIndicator<GR>::value),
161 161
    _pleaseRemoveOsStream(pros), _scaleToA4(false),
162 162
    _nodeTextColorType(SAME_COL), _nodeTextColors(BLACK),
163 163
    _autoNodeScale(false),
164 164
    _autoArcWidthScale(false),
165 165
    _absoluteNodeSizes(false),
166 166
    _absoluteArcWidths(false),
167 167
    _negY(false),
168 168
    _preScale(true)
169 169
  {}
170 170
};
171 171

	
172 172
///Auxiliary class to implement the named parameters of \ref graphToEps()
173 173

	
174 174
///Auxiliary class to implement the named parameters of \ref graphToEps().
175 175
///
176 176
///For detailed examples see the \ref graph_to_eps_demo.cc demo file.
177 177
template<class T> class GraphToEps : public T
178 178
{
179 179
  // Can't believe it is required by the C++ standard
180 180
  using T::g;
181 181
  using T::os;
182 182

	
183 183
  using T::_coords;
184 184
  using T::_nodeSizes;
185 185
  using T::_nodeShapes;
186 186
  using T::_nodeColors;
187 187
  using T::_arcColors;
188 188
  using T::_arcWidths;
189 189

	
190 190
  using T::_arcWidthScale;
191 191
  using T::_nodeScale;
192 192
  using T::_xBorder;
193 193
  using T::_yBorder;
194 194
  using T::_scale;
195 195
  using T::_nodeBorderQuotient;
196 196

	
197 197
  using T::_drawArrows;
198 198
  using T::_arrowLength;
199 199
  using T::_arrowWidth;
200 200

	
201 201
  using T::_showNodes;
202 202
  using T::_showArcs;
203 203

	
204 204
  using T::_enableParallel;
205 205
  using T::_parArcDist;
206 206

	
207 207
  using T::_showNodeText;
208 208
  using T::_nodeTexts;
209 209
  using T::_nodeTextSize;
210 210

	
211 211
  using T::_showNodePsText;
212 212
  using T::_nodePsTexts;
213 213
  using T::_nodePsTextsPreamble;
214 214

	
215 215
  using T::_undirected;
216 216

	
217 217
  using T::_pleaseRemoveOsStream;
218 218

	
219 219
  using T::_scaleToA4;
220 220

	
221 221
  using T::_title;
222 222
  using T::_copyright;
223 223

	
224 224
  using T::NodeTextColorType;
225 225
  using T::CUST_COL;
226 226
  using T::DIST_COL;
227 227
  using T::DIST_BW;
228 228
  using T::_nodeTextColorType;
229 229
  using T::_nodeTextColors;
230 230

	
231 231
  using T::_autoNodeScale;
232 232
  using T::_autoArcWidthScale;
233 233

	
234 234
  using T::_absoluteNodeSizes;
235 235
  using T::_absoluteArcWidths;
236 236

	
237 237

	
238 238
  using T::_negY;
239 239
  using T::_preScale;
240 240

	
241 241
  // dradnats ++C eht yb deriuqer si ti eveileb t'naC
242 242

	
243 243
  typedef typename T::Graph Graph;
244 244
  typedef typename Graph::Node Node;
245 245
  typedef typename Graph::NodeIt NodeIt;
246 246
  typedef typename Graph::Arc Arc;
247 247
  typedef typename Graph::ArcIt ArcIt;
248 248
  typedef typename Graph::InArcIt InArcIt;
249 249
  typedef typename Graph::OutArcIt OutArcIt;
250 250

	
251 251
  static const int INTERPOL_PREC;
252 252
  static const double A4HEIGHT;
253 253
  static const double A4WIDTH;
254 254
  static const double A4BORDER;
255 255

	
256 256
  bool dontPrint;
257 257

	
258 258
public:
259 259
  ///Node shapes
260 260

	
261 261
  ///Node shapes.
262 262
  ///
263 263
  enum NodeShapes {
264 264
    /// = 0
265 265
    ///\image html nodeshape_0.png
266 266
    ///\image latex nodeshape_0.eps "CIRCLE shape (0)" width=2cm
267 267
    CIRCLE=0,
268 268
    /// = 1
269 269
    ///\image html nodeshape_1.png
270 270
    ///\image latex nodeshape_1.eps "SQUARE shape (1)" width=2cm
271
    ///
272 271
    SQUARE=1,
273 272
    /// = 2
274 273
    ///\image html nodeshape_2.png
275 274
    ///\image latex nodeshape_2.eps "DIAMOND shape (2)" width=2cm
276
    ///
277 275
    DIAMOND=2,
278 276
    /// = 3
279 277
    ///\image html nodeshape_3.png
280
    ///\image latex nodeshape_2.eps "MALE shape (4)" width=2cm
281
    ///
278
    ///\image latex nodeshape_3.eps "MALE shape (3)" width=2cm
282 279
    MALE=3,
283 280
    /// = 4
284 281
    ///\image html nodeshape_4.png
285
    ///\image latex nodeshape_2.eps "FEMALE shape (4)" width=2cm
286
    ///
282
    ///\image latex nodeshape_4.eps "FEMALE shape (4)" width=2cm
287 283
    FEMALE=4
288 284
  };
289 285

	
290 286
private:
291 287
  class arcLess {
292 288
    const Graph &g;
293 289
  public:
294 290
    arcLess(const Graph &_g) : g(_g) {}
295 291
    bool operator()(Arc a,Arc b) const
296 292
    {
297 293
      Node ai=std::min(g.source(a),g.target(a));
298 294
      Node aa=std::max(g.source(a),g.target(a));
299 295
      Node bi=std::min(g.source(b),g.target(b));
300 296
      Node ba=std::max(g.source(b),g.target(b));
301 297
      return ai<bi ||
302 298
        (ai==bi && (aa < ba ||
303 299
                    (aa==ba && ai==g.source(a) && bi==g.target(b))));
304 300
    }
305 301
  };
306 302
  bool isParallel(Arc e,Arc f) const
307 303
  {
308 304
    return (g.source(e)==g.source(f)&&
309 305
            g.target(e)==g.target(f)) ||
310 306
      (g.source(e)==g.target(f)&&
311 307
       g.target(e)==g.source(f));
312 308
  }
313 309
  template<class TT>
314 310
  static std::string psOut(const dim2::Point<TT> &p)
315 311
    {
316 312
      std::ostringstream os;
317 313
      os << p.x << ' ' << p.y;
318 314
      return os.str();
319 315
    }
320 316
  static std::string psOut(const Color &c)
321 317
    {
322 318
      std::ostringstream os;
323 319
      os << c.red() << ' ' << c.green() << ' ' << c.blue();
324 320
      return os.str();
325 321
    }
326 322

	
327 323
public:
328 324
  GraphToEps(const T &t) : T(t), dontPrint(false) {};
329 325

	
330 326
  template<class X> struct CoordsTraits : public T {
331 327
  typedef X CoordsMapType;
332 328
    const X &_coords;
333 329
    CoordsTraits(const T &t,const X &x) : T(t), _coords(x) {}
334 330
  };
335 331
  ///Sets the map of the node coordinates
336 332

	
337 333
  ///Sets the map of the node coordinates.
338 334
  ///\param x must be a node map with \ref dim2::Point "dim2::Point<double>" or
339 335
  ///\ref dim2::Point "dim2::Point<int>" values.
340 336
  template<class X> GraphToEps<CoordsTraits<X> > coords(const X &x) {
341 337
    dontPrint=true;
342 338
    return GraphToEps<CoordsTraits<X> >(CoordsTraits<X>(*this,x));
343 339
  }
344 340
  template<class X> struct NodeSizesTraits : public T {
345 341
    const X &_nodeSizes;
346 342
    NodeSizesTraits(const T &t,const X &x) : T(t), _nodeSizes(x) {}
347 343
  };
348 344
  ///Sets the map of the node sizes
349 345

	
350 346
  ///Sets the map of the node sizes.
351 347
  ///\param x must be a node map with \c double (or convertible) values.
352 348
  template<class X> GraphToEps<NodeSizesTraits<X> > nodeSizes(const X &x)
353 349
  {
354 350
    dontPrint=true;
355 351
    return GraphToEps<NodeSizesTraits<X> >(NodeSizesTraits<X>(*this,x));
356 352
  }
357 353
  template<class X> struct NodeShapesTraits : public T {
358 354
    const X &_nodeShapes;
359 355
    NodeShapesTraits(const T &t,const X &x) : T(t), _nodeShapes(x) {}
360 356
  };
361 357
  ///Sets the map of the node shapes
362 358

	
363 359
  ///Sets the map of the node shapes.
364 360
  ///The available shape values
365 361
  ///can be found in \ref NodeShapes "enum NodeShapes".
366 362
  ///\param x must be a node map with \c int (or convertible) values.
367 363
  ///\sa NodeShapes
368 364
  template<class X> GraphToEps<NodeShapesTraits<X> > nodeShapes(const X &x)
369 365
  {
370 366
    dontPrint=true;
371 367
    return GraphToEps<NodeShapesTraits<X> >(NodeShapesTraits<X>(*this,x));
372 368
  }
373 369
  template<class X> struct NodeTextsTraits : public T {
374 370
    const X &_nodeTexts;
375 371
    NodeTextsTraits(const T &t,const X &x) : T(t), _nodeTexts(x) {}
376 372
  };
377 373
  ///Sets the text printed on the nodes
378 374

	
379 375
  ///Sets the text printed on the nodes.
380 376
  ///\param x must be a node map with type that can be pushed to a standard
381 377
  ///\c ostream.
382 378
  template<class X> GraphToEps<NodeTextsTraits<X> > nodeTexts(const X &x)
383 379
  {
384 380
    dontPrint=true;
385 381
    _showNodeText=true;
386 382
    return GraphToEps<NodeTextsTraits<X> >(NodeTextsTraits<X>(*this,x));
387 383
  }
388 384
  template<class X> struct NodePsTextsTraits : public T {
389 385
    const X &_nodePsTexts;
390 386
    NodePsTextsTraits(const T &t,const X &x) : T(t), _nodePsTexts(x) {}
391 387
  };
392 388
  ///Inserts a PostScript block to the nodes
393 389

	
394 390
  ///With this command it is possible to insert a verbatim PostScript
395 391
  ///block to the nodes.
396 392
  ///The PS current point will be moved to the center of the node before
397 393
  ///the PostScript block inserted.
398 394
  ///
399 395
  ///Before and after the block a newline character is inserted so you
400 396
  ///don't have to bother with the separators.
401 397
  ///
402 398
  ///\param x must be a node map with type that can be pushed to a standard
403 399
  ///\c ostream.
404 400
  ///
405 401
  ///\sa nodePsTextsPreamble()
406 402
  template<class X> GraphToEps<NodePsTextsTraits<X> > nodePsTexts(const X &x)
407 403
  {
408 404
    dontPrint=true;
409 405
    _showNodePsText=true;
410 406
    return GraphToEps<NodePsTextsTraits<X> >(NodePsTextsTraits<X>(*this,x));
411 407
  }
412 408
  template<class X> struct ArcWidthsTraits : public T {
413 409
    const X &_arcWidths;
414 410
    ArcWidthsTraits(const T &t,const X &x) : T(t), _arcWidths(x) {}
415 411
  };
416 412
  ///Sets the map of the arc widths
417 413

	
418 414
  ///Sets the map of the arc widths.
419 415
  ///\param x must be an arc map with \c double (or convertible) values.
420 416
  template<class X> GraphToEps<ArcWidthsTraits<X> > arcWidths(const X &x)
421 417
  {
422 418
    dontPrint=true;
423 419
    return GraphToEps<ArcWidthsTraits<X> >(ArcWidthsTraits<X>(*this,x));
424 420
  }
425 421

	
426 422
  template<class X> struct NodeColorsTraits : public T {
427 423
    const X &_nodeColors;
428 424
    NodeColorsTraits(const T &t,const X &x) : T(t), _nodeColors(x) {}
429 425
  };
430 426
  ///Sets the map of the node colors
431 427

	
432 428
  ///Sets the map of the node colors.
433 429
  ///\param x must be a node map with \ref Color values.
434 430
  ///
435 431
  ///\sa Palette
436 432
  template<class X> GraphToEps<NodeColorsTraits<X> >
437 433
  nodeColors(const X &x)
438 434
  {
439 435
    dontPrint=true;
440 436
    return GraphToEps<NodeColorsTraits<X> >(NodeColorsTraits<X>(*this,x));
441 437
  }
442 438
  template<class X> struct NodeTextColorsTraits : public T {
443 439
    const X &_nodeTextColors;
444 440
    NodeTextColorsTraits(const T &t,const X &x) : T(t), _nodeTextColors(x) {}
445 441
  };
446 442
  ///Sets the map of the node text colors
447 443

	
448 444
  ///Sets the map of the node text colors.
449 445
  ///\param x must be a node map with \ref Color values.
450 446
  ///
451 447
  ///\sa Palette
452 448
  template<class X> GraphToEps<NodeTextColorsTraits<X> >
453 449
  nodeTextColors(const X &x)
454 450
  {
455 451
    dontPrint=true;
456 452
    _nodeTextColorType=CUST_COL;
457 453
    return GraphToEps<NodeTextColorsTraits<X> >
458 454
      (NodeTextColorsTraits<X>(*this,x));
459 455
  }
460 456
  template<class X> struct ArcColorsTraits : public T {
461 457
    const X &_arcColors;
462 458
    ArcColorsTraits(const T &t,const X &x) : T(t), _arcColors(x) {}
463 459
  };
464 460
  ///Sets the map of the arc colors
465 461

	
466 462
  ///Sets the map of the arc colors.
467 463
  ///\param x must be an arc map with \ref Color values.
468 464
  ///
469 465
  ///\sa Palette
470 466
  template<class X> GraphToEps<ArcColorsTraits<X> >
471 467
  arcColors(const X &x)
472 468
  {
473 469
    dontPrint=true;
474 470
    return GraphToEps<ArcColorsTraits<X> >(ArcColorsTraits<X>(*this,x));
475 471
  }
476 472
  ///Sets a global scale factor for node sizes
477 473

	
478 474
  ///Sets a global scale factor for node sizes.
479 475
  ///
480 476
  /// If nodeSizes() is not given, this function simply sets the node
481 477
  /// sizes to \c d.  If nodeSizes() is given, but
482 478
  /// autoNodeScale() is not, then the node size given by
483 479
  /// nodeSizes() will be multiplied by the value \c d.
484 480
  /// If both nodeSizes() and autoNodeScale() are used, then the
485 481
  /// node sizes will be scaled in such a way that the greatest size will be
486 482
  /// equal to \c d.
487 483
  /// \sa nodeSizes()
488 484
  /// \sa autoNodeScale()
489 485
  GraphToEps<T> &nodeScale(double d=.01) {_nodeScale=d;return *this;}
490 486
  ///Turns on/off the automatic node size scaling.
491 487

	
492 488
  ///Turns on/off the automatic node size scaling.
493 489
  ///
494 490
  ///\sa nodeScale()
495 491
  ///
496 492
  GraphToEps<T> &autoNodeScale(bool b=true) {
497 493
    _autoNodeScale=b;return *this;
498 494
  }
499 495

	
500 496
  ///Turns on/off the absolutematic node size scaling.
501 497

	
502 498
  ///Turns on/off the absolutematic node size scaling.
503 499
  ///
504 500
  ///\sa nodeScale()
505 501
  ///
506 502
  GraphToEps<T> &absoluteNodeSizes(bool b=true) {
507 503
    _absoluteNodeSizes=b;return *this;
508 504
  }
509 505

	
510 506
  ///Negates the Y coordinates.
511 507
  GraphToEps<T> &negateY(bool b=true) {
512 508
    _negY=b;return *this;
513 509
  }
514 510

	
515 511
  ///Turn on/off pre-scaling
516 512

	
517 513
  ///By default graphToEps() rescales the whole image in order to avoid
518 514
  ///very big or very small bounding boxes.
519 515
  ///
520 516
  ///This (p)rescaling can be turned off with this function.
521 517
  ///
522 518
  GraphToEps<T> &preScale(bool b=true) {
523 519
    _preScale=b;return *this;
524 520
  }
525 521

	
526 522
  ///Sets a global scale factor for arc widths
527 523

	
528 524
  /// Sets a global scale factor for arc widths.
529 525
  ///
530 526
  /// If arcWidths() is not given, this function simply sets the arc
531 527
  /// widths to \c d.  If arcWidths() is given, but
532 528
  /// autoArcWidthScale() is not, then the arc withs given by
533 529
  /// arcWidths() will be multiplied by the value \c d.
534 530
  /// If both arcWidths() and autoArcWidthScale() are used, then the
535 531
  /// arc withs will be scaled in such a way that the greatest width will be
536 532
  /// equal to \c d.
537 533
  GraphToEps<T> &arcWidthScale(double d=.003) {_arcWidthScale=d;return *this;}
538 534
  ///Turns on/off the automatic arc width scaling.
539 535

	
540 536
  ///Turns on/off the automatic arc width scaling.
541 537
  ///
542 538
  ///\sa arcWidthScale()
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_KRUSKAL_H
20 20
#define LEMON_KRUSKAL_H
21 21

	
22 22
#include <algorithm>
23 23
#include <vector>
24 24
#include <lemon/unionfind.h>
25 25
#include <lemon/maps.h>
26 26

	
27 27
#include <lemon/core.h>
28 28
#include <lemon/bits/traits.h>
29 29

	
30 30
///\ingroup spantree
31 31
///\file
32 32
///\brief Kruskal's algorithm to compute a minimum cost spanning tree
33 33
///
34 34
///Kruskal's algorithm to compute a minimum cost spanning tree.
35 35
///
36 36

	
37 37
namespace lemon {
38 38

	
39 39
  namespace _kruskal_bits {
40 40

	
41 41
    // Kruskal for directed graphs.
42 42

	
43 43
    template <typename Digraph, typename In, typename Out>
44 44
    typename disable_if<lemon::UndirectedTagIndicator<Digraph>,
45 45
                       typename In::value_type::second_type >::type
46 46
    kruskal(const Digraph& digraph, const In& in, Out& out,dummy<0> = 0) {
47 47
      typedef typename In::value_type::second_type Value;
48 48
      typedef typename Digraph::template NodeMap<int> IndexMap;
49 49
      typedef typename Digraph::Node Node;
50 50

	
51 51
      IndexMap index(digraph);
52 52
      UnionFind<IndexMap> uf(index);
53 53
      for (typename Digraph::NodeIt it(digraph); it != INVALID; ++it) {
54 54
        uf.insert(it);
55 55
      }
56 56

	
57 57
      Value tree_value = 0;
58 58
      for (typename In::const_iterator it = in.begin(); it != in.end(); ++it) {
59 59
        if (uf.join(digraph.target(it->first),digraph.source(it->first))) {
60 60
          out.set(it->first, true);
61 61
          tree_value += it->second;
62 62
        }
63 63
        else {
64 64
          out.set(it->first, false);
65 65
        }
66 66
      }
67 67
      return tree_value;
68 68
    }
69 69

	
70 70
    // Kruskal for undirected graphs.
71 71

	
72 72
    template <typename Graph, typename In, typename Out>
73 73
    typename enable_if<lemon::UndirectedTagIndicator<Graph>,
74 74
                       typename In::value_type::second_type >::type
75 75
    kruskal(const Graph& graph, const In& in, Out& out,dummy<1> = 1) {
76 76
      typedef typename In::value_type::second_type Value;
77 77
      typedef typename Graph::template NodeMap<int> IndexMap;
78 78
      typedef typename Graph::Node Node;
79 79

	
80 80
      IndexMap index(graph);
81 81
      UnionFind<IndexMap> uf(index);
82 82
      for (typename Graph::NodeIt it(graph); it != INVALID; ++it) {
83 83
        uf.insert(it);
84 84
      }
85 85

	
86 86
      Value tree_value = 0;
87 87
      for (typename In::const_iterator it = in.begin(); it != in.end(); ++it) {
88 88
        if (uf.join(graph.u(it->first),graph.v(it->first))) {
89 89
          out.set(it->first, true);
90 90
          tree_value += it->second;
91 91
        }
92 92
        else {
93 93
          out.set(it->first, false);
94 94
        }
95 95
      }
96 96
      return tree_value;
97 97
    }
98 98

	
99 99

	
100 100
    template <typename Sequence>
101 101
    struct PairComp {
102 102
      typedef typename Sequence::value_type Value;
103 103
      bool operator()(const Value& left, const Value& right) {
104 104
        return left.second < right.second;
105 105
      }
106 106
    };
107 107

	
108 108
    template <typename In, typename Enable = void>
109 109
    struct SequenceInputIndicator {
110 110
      static const bool value = false;
111 111
    };
112 112

	
113 113
    template <typename In>
114 114
    struct SequenceInputIndicator<In,
115 115
      typename exists<typename In::value_type::first_type>::type> {
116 116
      static const bool value = true;
117 117
    };
118 118

	
119 119
    template <typename In, typename Enable = void>
120 120
    struct MapInputIndicator {
121 121
      static const bool value = false;
122 122
    };
123 123

	
124 124
    template <typename In>
125 125
    struct MapInputIndicator<In,
126 126
      typename exists<typename In::Value>::type> {
127 127
      static const bool value = true;
128 128
    };
129 129

	
130 130
    template <typename In, typename Enable = void>
131 131
    struct SequenceOutputIndicator {
132 132
      static const bool value = false;
133 133
    };
134 134

	
135 135
    template <typename Out>
136 136
    struct SequenceOutputIndicator<Out,
137 137
      typename exists<typename Out::value_type>::type> {
138 138
      static const bool value = true;
139 139
    };
140 140

	
141 141
    template <typename Out, typename Enable = void>
142 142
    struct MapOutputIndicator {
143 143
      static const bool value = false;
144 144
    };
145 145

	
146 146
    template <typename Out>
147 147
    struct MapOutputIndicator<Out,
148 148
      typename exists<typename Out::Value>::type> {
149 149
      static const bool value = true;
150 150
    };
151 151

	
152 152
    template <typename In, typename InEnable = void>
153 153
    struct KruskalValueSelector {};
154 154

	
155 155
    template <typename In>
156 156
    struct KruskalValueSelector<In,
157 157
      typename enable_if<SequenceInputIndicator<In>, void>::type>
158 158
    {
159 159
      typedef typename In::value_type::second_type Value;
160 160
    };
161 161

	
162 162
    template <typename In>
163 163
    struct KruskalValueSelector<In,
164 164
      typename enable_if<MapInputIndicator<In>, void>::type>
165 165
    {
166 166
      typedef typename In::Value Value;
167 167
    };
168 168

	
169 169
    template <typename Graph, typename In, typename Out,
170 170
              typename InEnable = void>
171 171
    struct KruskalInputSelector {};
172 172

	
173 173
    template <typename Graph, typename In, typename Out,
174 174
              typename InEnable = void>
175 175
    struct KruskalOutputSelector {};
176 176

	
177 177
    template <typename Graph, typename In, typename Out>
178 178
    struct KruskalInputSelector<Graph, In, Out,
179 179
      typename enable_if<SequenceInputIndicator<In>, void>::type >
180 180
    {
181 181
      typedef typename In::value_type::second_type Value;
182 182

	
183 183
      static Value kruskal(const Graph& graph, const In& in, Out& out) {
184 184
        return KruskalOutputSelector<Graph, In, Out>::
185 185
          kruskal(graph, in, out);
186 186
      }
187 187

	
188 188
    };
189 189

	
190 190
    template <typename Graph, typename In, typename Out>
191 191
    struct KruskalInputSelector<Graph, In, Out,
192 192
      typename enable_if<MapInputIndicator<In>, void>::type >
193 193
    {
194 194
      typedef typename In::Value Value;
195 195
      static Value kruskal(const Graph& graph, const In& in, Out& out) {
196 196
        typedef typename In::Key MapArc;
197 197
        typedef typename In::Value Value;
198 198
        typedef typename ItemSetTraits<Graph, MapArc>::ItemIt MapArcIt;
199 199
        typedef std::vector<std::pair<MapArc, Value> > Sequence;
200 200
        Sequence seq;
201 201

	
202 202
        for (MapArcIt it(graph); it != INVALID; ++it) {
203 203
          seq.push_back(std::make_pair(it, in[it]));
204 204
        }
205 205

	
206 206
        std::sort(seq.begin(), seq.end(), PairComp<Sequence>());
207 207
        return KruskalOutputSelector<Graph, Sequence, Out>::
208 208
          kruskal(graph, seq, out);
209 209
      }
210 210
    };
211 211

	
212 212
    template <typename T>
213 213
    struct RemoveConst {
214 214
      typedef T type;
215 215
    };
216 216

	
217 217
    template <typename T>
218 218
    struct RemoveConst<const T> {
219 219
      typedef T type;
220 220
    };
221 221

	
222 222
    template <typename Graph, typename In, typename Out>
223 223
    struct KruskalOutputSelector<Graph, In, Out,
224 224
      typename enable_if<SequenceOutputIndicator<Out>, void>::type >
225 225
    {
226 226
      typedef typename In::value_type::second_type Value;
227 227

	
228 228
      static Value kruskal(const Graph& graph, const In& in, Out& out) {
229 229
        typedef LoggerBoolMap<typename RemoveConst<Out>::type> Map;
230 230
        Map map(out);
231 231
        return _kruskal_bits::kruskal(graph, in, map);
232 232
      }
233 233

	
234 234
    };
235 235

	
236 236
    template <typename Graph, typename In, typename Out>
237 237
    struct KruskalOutputSelector<Graph, In, Out,
238 238
      typename enable_if<MapOutputIndicator<Out>, void>::type >
239 239
    {
240 240
      typedef typename In::value_type::second_type Value;
241 241

	
242 242
      static Value kruskal(const Graph& graph, const In& in, Out& out) {
243 243
        return _kruskal_bits::kruskal(graph, in, out);
244 244
      }
245 245
    };
246 246

	
247 247
  }
248 248

	
249 249
  /// \ingroup spantree
250 250
  ///
251
  /// \brief Kruskal algorithm to find a minimum cost spanning tree of
251
  /// \brief Kruskal's algorithm for finding a minimum cost spanning tree of
252 252
  /// a graph.
253 253
  ///
254 254
  /// This function runs Kruskal's algorithm to find a minimum cost
255
  /// spanning tree.
255
  /// spanning tree of a graph.
256 256
  /// Due to some C++ hacking, it accepts various input and output types.
257 257
  ///
258 258
  /// \param g The graph the algorithm runs on.
259 259
  /// It can be either \ref concepts::Digraph "directed" or
260 260
  /// \ref concepts::Graph "undirected".
261 261
  /// If the graph is directed, the algorithm consider it to be
262 262
  /// undirected by disregarding the direction of the arcs.
263 263
  ///
264 264
  /// \param in This object is used to describe the arc/edge costs.
265 265
  /// It can be one of the following choices.
266 266
  /// - An STL compatible 'Forward Container' with
267
  /// <tt>std::pair<GR::Arc,X></tt> or
268
  /// <tt>std::pair<GR::Edge,X></tt> as its <tt>value_type</tt>, where
269
  /// \c X is the type of the costs. The pairs indicates the arcs/edges
267
  /// <tt>std::pair<GR::Arc,C></tt> or
268
  /// <tt>std::pair<GR::Edge,C></tt> as its <tt>value_type</tt>, where
269
  /// \c C is the type of the costs. The pairs indicates the arcs/edges
270 270
  /// along with the assigned cost. <em>They must be in a
271 271
  /// cost-ascending order.</em>
272 272
  /// - Any readable arc/edge map. The values of the map indicate the
273 273
  /// arc/edge costs.
274 274
  ///
275 275
  /// \retval out Here we also have a choice.
276
  /// - It can be a writable \c bool arc/edge map. After running the
277
  /// algorithm it will contain the found minimum cost spanning
276
  /// - It can be a writable arc/edge map with \c bool value type. After
277
  /// running the algorithm it will contain the found minimum cost spanning
278 278
  /// tree: the value of an arc/edge will be set to \c true if it belongs
279 279
  /// to the tree, otherwise it will be set to \c false. The value of
280 280
  /// each arc/edge will be set exactly once.
281 281
  /// - It can also be an iteraror of an STL Container with
282 282
  /// <tt>GR::Arc</tt> or <tt>GR::Edge</tt> as its
283 283
  /// <tt>value_type</tt>.  The algorithm copies the elements of the
284 284
  /// found tree into this sequence.  For example, if we know that the
285 285
  /// spanning tree of the graph \c g has say 53 arcs, then we can
286 286
  /// put its arcs into an STL vector \c tree with a code like this.
287 287
  ///\code
288 288
  /// std::vector<Arc> tree(53);
289 289
  /// kruskal(g,cost,tree.begin());
290 290
  ///\endcode
291 291
  /// Or if we don't know in advance the size of the tree, we can
292 292
  /// write this.
293 293
  ///\code
294 294
  /// std::vector<Arc> tree;
295 295
  /// kruskal(g,cost,std::back_inserter(tree));
296 296
  ///\endcode
297 297
  ///
298 298
  /// \return The total cost of the found spanning tree.
299 299
  ///
300 300
  /// \note If the input graph is not (weakly) connected, a spanning
301 301
  /// forest is calculated instead of a spanning tree.
302 302

	
303 303
#ifdef DOXYGEN
304
  template <class Graph, class In, class Out>
305
  Value kruskal(GR const& g, const In& in, Out& out)
304
  template <typename Graph, typename In, typename Out>
305
  Value kruskal(const Graph& g, const In& in, Out& out)
306 306
#else
307 307
  template <class Graph, class In, class Out>
308 308
  inline typename _kruskal_bits::KruskalValueSelector<In>::Value
309 309
  kruskal(const Graph& graph, const In& in, Out& out)
310 310
#endif
311 311
  {
312 312
    return _kruskal_bits::KruskalInputSelector<Graph, In, Out>::
313 313
      kruskal(graph, in, out);
314 314
  }
315 315

	
316 316

	
317

	
318

	
319 317
  template <class Graph, class In, class Out>
320 318
  inline typename _kruskal_bits::KruskalValueSelector<In>::Value
321 319
  kruskal(const Graph& graph, const In& in, const Out& out)
322 320
  {
323 321
    return _kruskal_bits::KruskalInputSelector<Graph, In, const Out>::
324 322
      kruskal(graph, in, out);
325 323
  }
326 324

	
327 325
} //namespace lemon
328 326

	
329 327
#endif //LEMON_KRUSKAL_H
Ignore white space 6 line context
... ...
@@ -340,2336 +340,2336 @@
340 340
        char c;
341 341
        std::string line;
342 342
        while (is.get(c) && c != '@') {
343 343
          if (c == '\n') {
344 344
            ++line_num;
345 345
          } else if (c == '#') {
346 346
            getline(is, line);
347 347
            ++line_num;
348 348
          } else if (!isWhiteSpace(c)) {
349 349
            is.putback(c);
350 350
            getline(is, line);
351 351
            _functor(line);
352 352
            ++line_num;
353 353
          }
354 354
        }
355 355
        if (is) is.putback(c);
356 356
        else if (is.eof()) is.clear();
357 357
      }
358 358
    };
359 359

	
360 360
    template <typename Functor>
361 361
    class StreamSection : public Section {
362 362
    private:
363 363

	
364 364
      Functor _functor;
365 365

	
366 366
    public:
367 367

	
368 368
      StreamSection(const Functor& functor) : _functor(functor) {}
369 369
      virtual ~StreamSection() {}
370 370

	
371 371
      virtual void process(std::istream& is, int& line_num) {
372 372
        _functor(is, line_num);
373 373
        char c;
374 374
        std::string line;
375 375
        while (is.get(c) && c != '@') {
376 376
          if (c == '\n') {
377 377
            ++line_num;
378 378
          } else if (!isWhiteSpace(c)) {
379 379
            getline(is, line);
380 380
            ++line_num;
381 381
          }
382 382
        }
383 383
        if (is) is.putback(c);
384 384
        else if (is.eof()) is.clear();
385 385
      }
386 386
    };
387 387

	
388 388
  }
389 389

	
390 390
  template <typename Digraph>
391 391
  class DigraphReader;
392 392

	
393 393
  template <typename Digraph>
394 394
  DigraphReader<Digraph> digraphReader(Digraph& digraph, 
395 395
                                       std::istream& is = std::cin);
396 396
  template <typename Digraph>
397 397
  DigraphReader<Digraph> digraphReader(Digraph& digraph, const std::string& fn);
398 398
  template <typename Digraph>
399 399
  DigraphReader<Digraph> digraphReader(Digraph& digraph, const char *fn);
400 400

	
401 401
  /// \ingroup lemon_io
402 402
  ///
403 403
  /// \brief \ref lgf-format "LGF" reader for directed graphs
404 404
  ///
405 405
  /// This utility reads an \ref lgf-format "LGF" file.
406 406
  ///
407 407
  /// The reading method does a batch processing. The user creates a
408 408
  /// reader object, then various reading rules can be added to the
409 409
  /// reader, and eventually the reading is executed with the \c run()
410 410
  /// member function. A map reading rule can be added to the reader
411 411
  /// with the \c nodeMap() or \c arcMap() members. An optional
412 412
  /// converter parameter can also be added as a standard functor
413 413
  /// converting from \c std::string to the value type of the map. If it
414 414
  /// is set, it will determine how the tokens in the file should be
415 415
  /// converted to the value type of the map. If the functor is not set,
416 416
  /// then a default conversion will be used. One map can be read into
417 417
  /// multiple map objects at the same time. The \c attribute(), \c
418 418
  /// node() and \c arc() functions are used to add attribute reading
419 419
  /// rules.
420 420
  ///
421 421
  ///\code
422 422
  /// DigraphReader<Digraph>(digraph, std::cin).
423 423
  ///   nodeMap("coordinates", coord_map).
424 424
  ///   arcMap("capacity", cap_map).
425 425
  ///   node("source", src).
426 426
  ///   node("target", trg).
427 427
  ///   attribute("caption", caption).
428 428
  ///   run();
429 429
  ///\endcode
430 430
  ///
431 431
  /// By default the reader uses the first section in the file of the
432 432
  /// proper type. If a section has an optional name, then it can be
433 433
  /// selected for reading by giving an optional name parameter to the
434 434
  /// \c nodes(), \c arcs() or \c attributes() functions.
435 435
  ///
436 436
  /// The \c useNodes() and \c useArcs() functions are used to tell the reader
437 437
  /// that the nodes or arcs should not be constructed (added to the
438 438
  /// graph) during the reading, but instead the label map of the items
439 439
  /// are given as a parameter of these functions. An
440 440
  /// application of these functions is multipass reading, which is
441 441
  /// important if two \c \@arcs sections must be read from the
442 442
  /// file. In this case the first phase would read the node set and one
443 443
  /// of the arc sets, while the second phase would read the second arc
444 444
  /// set into an \e ArcSet class (\c SmartArcSet or \c ListArcSet).
445 445
  /// The previously read label node map should be passed to the \c
446 446
  /// useNodes() functions. Another application of multipass reading when
447 447
  /// paths are given as a node map or an arc map.
448 448
  /// It is impossible to read this in
449 449
  /// a single pass, because the arcs are not constructed when the node
450 450
  /// maps are read.
451 451
  template <typename GR>
452 452
  class DigraphReader {
453 453
  public:
454 454

	
455 455
    typedef GR Digraph;
456 456

	
457 457
  private:
458 458

	
459 459
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
460 460

	
461 461
    std::istream* _is;
462 462
    bool local_is;
463 463
    std::string _filename;
464 464

	
465 465
    Digraph& _digraph;
466 466

	
467 467
    std::string _nodes_caption;
468 468
    std::string _arcs_caption;
469 469
    std::string _attributes_caption;
470 470

	
471 471
    typedef std::map<std::string, Node> NodeIndex;
472 472
    NodeIndex _node_index;
473 473
    typedef std::map<std::string, Arc> ArcIndex;
474 474
    ArcIndex _arc_index;
475 475

	
476 476
    typedef std::vector<std::pair<std::string,
477 477
      _reader_bits::MapStorageBase<Node>*> > NodeMaps;
478 478
    NodeMaps _node_maps;
479 479

	
480 480
    typedef std::vector<std::pair<std::string,
481 481
      _reader_bits::MapStorageBase<Arc>*> >ArcMaps;
482 482
    ArcMaps _arc_maps;
483 483

	
484 484
    typedef std::multimap<std::string, _reader_bits::ValueStorageBase*>
485 485
      Attributes;
486 486
    Attributes _attributes;
487 487

	
488 488
    bool _use_nodes;
489 489
    bool _use_arcs;
490 490

	
491 491
    bool _skip_nodes;
492 492
    bool _skip_arcs;
493 493

	
494 494
    int line_num;
495 495
    std::istringstream line;
496 496

	
497 497
  public:
498 498

	
499 499
    /// \brief Constructor
500 500
    ///
501 501
    /// Construct a directed graph reader, which reads from the given
502 502
    /// input stream.
503 503
    DigraphReader(Digraph& digraph, std::istream& is = std::cin)
504 504
      : _is(&is), local_is(false), _digraph(digraph),
505 505
        _use_nodes(false), _use_arcs(false),
506 506
        _skip_nodes(false), _skip_arcs(false) {}
507 507

	
508 508
    /// \brief Constructor
509 509
    ///
510 510
    /// Construct a directed graph reader, which reads from the given
511 511
    /// file.
512 512
    DigraphReader(Digraph& digraph, const std::string& fn)
513 513
      : _is(new std::ifstream(fn.c_str())), local_is(true),
514 514
        _filename(fn), _digraph(digraph),
515 515
        _use_nodes(false), _use_arcs(false),
516 516
        _skip_nodes(false), _skip_arcs(false) {
517 517
      if (!(*_is)) {
518 518
        delete _is;
519 519
        throw IoError("Cannot open file", fn);
520 520
      }
521 521
    }
522 522

	
523 523
    /// \brief Constructor
524 524
    ///
525 525
    /// Construct a directed graph reader, which reads from the given
526 526
    /// file.
527 527
    DigraphReader(Digraph& digraph, const char* fn)
528 528
      : _is(new std::ifstream(fn)), local_is(true),
529 529
        _filename(fn), _digraph(digraph),
530 530
        _use_nodes(false), _use_arcs(false),
531 531
        _skip_nodes(false), _skip_arcs(false) {
532 532
      if (!(*_is)) {
533 533
        delete _is;
534 534
        throw IoError("Cannot open file", fn);
535 535
      }
536 536
    }
537 537

	
538 538
    /// \brief Destructor
539 539
    ~DigraphReader() {
540 540
      for (typename NodeMaps::iterator it = _node_maps.begin();
541 541
           it != _node_maps.end(); ++it) {
542 542
        delete it->second;
543 543
      }
544 544

	
545 545
      for (typename ArcMaps::iterator it = _arc_maps.begin();
546 546
           it != _arc_maps.end(); ++it) {
547 547
        delete it->second;
548 548
      }
549 549

	
550 550
      for (typename Attributes::iterator it = _attributes.begin();
551 551
           it != _attributes.end(); ++it) {
552 552
        delete it->second;
553 553
      }
554 554

	
555 555
      if (local_is) {
556 556
        delete _is;
557 557
      }
558 558

	
559 559
    }
560 560

	
561 561
  private:
562 562

	
563 563
    template <typename DGR>
564 564
    friend DigraphReader<DGR> digraphReader(DGR& digraph, std::istream& is);
565 565
    template <typename DGR>
566 566
    friend DigraphReader<DGR> digraphReader(DGR& digraph, 
567 567
                                            const std::string& fn);
568 568
    template <typename DGR>
569 569
    friend DigraphReader<DGR> digraphReader(DGR& digraph, const char *fn);
570 570

	
571 571
    DigraphReader(DigraphReader& other)
572 572
      : _is(other._is), local_is(other.local_is), _digraph(other._digraph),
573 573
        _use_nodes(other._use_nodes), _use_arcs(other._use_arcs),
574 574
        _skip_nodes(other._skip_nodes), _skip_arcs(other._skip_arcs) {
575 575

	
576 576
      other._is = 0;
577 577
      other.local_is = false;
578 578

	
579 579
      _node_index.swap(other._node_index);
580 580
      _arc_index.swap(other._arc_index);
581 581

	
582 582
      _node_maps.swap(other._node_maps);
583 583
      _arc_maps.swap(other._arc_maps);
584 584
      _attributes.swap(other._attributes);
585 585

	
586 586
      _nodes_caption = other._nodes_caption;
587 587
      _arcs_caption = other._arcs_caption;
588 588
      _attributes_caption = other._attributes_caption;
589 589

	
590 590
    }
591 591

	
592 592
    DigraphReader& operator=(const DigraphReader&);
593 593

	
594 594
  public:
595 595

	
596
    /// \name Reading rules
596
    /// \name Reading Rules
597 597
    /// @{
598 598

	
599 599
    /// \brief Node map reading rule
600 600
    ///
601 601
    /// Add a node map reading rule to the reader.
602 602
    template <typename Map>
603 603
    DigraphReader& nodeMap(const std::string& caption, Map& map) {
604 604
      checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
605 605
      _reader_bits::MapStorageBase<Node>* storage =
606 606
        new _reader_bits::MapStorage<Node, Map>(map);
607 607
      _node_maps.push_back(std::make_pair(caption, storage));
608 608
      return *this;
609 609
    }
610 610

	
611 611
    /// \brief Node map reading rule
612 612
    ///
613 613
    /// Add a node map reading rule with specialized converter to the
614 614
    /// reader.
615 615
    template <typename Map, typename Converter>
616 616
    DigraphReader& nodeMap(const std::string& caption, Map& map,
617 617
                           const Converter& converter = Converter()) {
618 618
      checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
619 619
      _reader_bits::MapStorageBase<Node>* storage =
620 620
        new _reader_bits::MapStorage<Node, Map, Converter>(map, converter);
621 621
      _node_maps.push_back(std::make_pair(caption, storage));
622 622
      return *this;
623 623
    }
624 624

	
625 625
    /// \brief Arc map reading rule
626 626
    ///
627 627
    /// Add an arc map reading rule to the reader.
628 628
    template <typename Map>
629 629
    DigraphReader& arcMap(const std::string& caption, Map& map) {
630 630
      checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
631 631
      _reader_bits::MapStorageBase<Arc>* storage =
632 632
        new _reader_bits::MapStorage<Arc, Map>(map);
633 633
      _arc_maps.push_back(std::make_pair(caption, storage));
634 634
      return *this;
635 635
    }
636 636

	
637 637
    /// \brief Arc map reading rule
638 638
    ///
639 639
    /// Add an arc map reading rule with specialized converter to the
640 640
    /// reader.
641 641
    template <typename Map, typename Converter>
642 642
    DigraphReader& arcMap(const std::string& caption, Map& map,
643 643
                          const Converter& converter = Converter()) {
644 644
      checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
645 645
      _reader_bits::MapStorageBase<Arc>* storage =
646 646
        new _reader_bits::MapStorage<Arc, Map, Converter>(map, converter);
647 647
      _arc_maps.push_back(std::make_pair(caption, storage));
648 648
      return *this;
649 649
    }
650 650

	
651 651
    /// \brief Attribute reading rule
652 652
    ///
653 653
    /// Add an attribute reading rule to the reader.
654 654
    template <typename Value>
655 655
    DigraphReader& attribute(const std::string& caption, Value& value) {
656 656
      _reader_bits::ValueStorageBase* storage =
657 657
        new _reader_bits::ValueStorage<Value>(value);
658 658
      _attributes.insert(std::make_pair(caption, storage));
659 659
      return *this;
660 660
    }
661 661

	
662 662
    /// \brief Attribute reading rule
663 663
    ///
664 664
    /// Add an attribute reading rule with specialized converter to the
665 665
    /// reader.
666 666
    template <typename Value, typename Converter>
667 667
    DigraphReader& attribute(const std::string& caption, Value& value,
668 668
                             const Converter& converter = Converter()) {
669 669
      _reader_bits::ValueStorageBase* storage =
670 670
        new _reader_bits::ValueStorage<Value, Converter>(value, converter);
671 671
      _attributes.insert(std::make_pair(caption, storage));
672 672
      return *this;
673 673
    }
674 674

	
675 675
    /// \brief Node reading rule
676 676
    ///
677 677
    /// Add a node reading rule to reader.
678 678
    DigraphReader& node(const std::string& caption, Node& node) {
679 679
      typedef _reader_bits::MapLookUpConverter<Node> Converter;
680 680
      Converter converter(_node_index);
681 681
      _reader_bits::ValueStorageBase* storage =
682 682
        new _reader_bits::ValueStorage<Node, Converter>(node, converter);
683 683
      _attributes.insert(std::make_pair(caption, storage));
684 684
      return *this;
685 685
    }
686 686

	
687 687
    /// \brief Arc reading rule
688 688
    ///
689 689
    /// Add an arc reading rule to reader.
690 690
    DigraphReader& arc(const std::string& caption, Arc& arc) {
691 691
      typedef _reader_bits::MapLookUpConverter<Arc> Converter;
692 692
      Converter converter(_arc_index);
693 693
      _reader_bits::ValueStorageBase* storage =
694 694
        new _reader_bits::ValueStorage<Arc, Converter>(arc, converter);
695 695
      _attributes.insert(std::make_pair(caption, storage));
696 696
      return *this;
697 697
    }
698 698

	
699 699
    /// @}
700 700

	
701
    /// \name Select section by name
701
    /// \name Select Section by Name
702 702
    /// @{
703 703

	
704 704
    /// \brief Set \c \@nodes section to be read
705 705
    ///
706 706
    /// Set \c \@nodes section to be read
707 707
    DigraphReader& nodes(const std::string& caption) {
708 708
      _nodes_caption = caption;
709 709
      return *this;
710 710
    }
711 711

	
712 712
    /// \brief Set \c \@arcs section to be read
713 713
    ///
714 714
    /// Set \c \@arcs section to be read
715 715
    DigraphReader& arcs(const std::string& caption) {
716 716
      _arcs_caption = caption;
717 717
      return *this;
718 718
    }
719 719

	
720 720
    /// \brief Set \c \@attributes section to be read
721 721
    ///
722 722
    /// Set \c \@attributes section to be read
723 723
    DigraphReader& attributes(const std::string& caption) {
724 724
      _attributes_caption = caption;
725 725
      return *this;
726 726
    }
727 727

	
728 728
    /// @}
729 729

	
730
    /// \name Using previously constructed node or arc set
730
    /// \name Using Previously Constructed Node or Arc Set
731 731
    /// @{
732 732

	
733 733
    /// \brief Use previously constructed node set
734 734
    ///
735 735
    /// Use previously constructed node set, and specify the node
736 736
    /// label map.
737 737
    template <typename Map>
738 738
    DigraphReader& useNodes(const Map& map) {
739 739
      checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
740 740
      LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
741 741
      _use_nodes = true;
742 742
      _writer_bits::DefaultConverter<typename Map::Value> converter;
743 743
      for (NodeIt n(_digraph); n != INVALID; ++n) {
744 744
        _node_index.insert(std::make_pair(converter(map[n]), n));
745 745
      }
746 746
      return *this;
747 747
    }
748 748

	
749 749
    /// \brief Use previously constructed node set
750 750
    ///
751 751
    /// Use previously constructed node set, and specify the node
752 752
    /// label map and a functor which converts the label map values to
753 753
    /// \c std::string.
754 754
    template <typename Map, typename Converter>
755 755
    DigraphReader& useNodes(const Map& map,
756 756
                            const Converter& converter = Converter()) {
757 757
      checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
758 758
      LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
759 759
      _use_nodes = true;
760 760
      for (NodeIt n(_digraph); n != INVALID; ++n) {
761 761
        _node_index.insert(std::make_pair(converter(map[n]), n));
762 762
      }
763 763
      return *this;
764 764
    }
765 765

	
766 766
    /// \brief Use previously constructed arc set
767 767
    ///
768 768
    /// Use previously constructed arc set, and specify the arc
769 769
    /// label map.
770 770
    template <typename Map>
771 771
    DigraphReader& useArcs(const Map& map) {
772 772
      checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
773 773
      LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member");
774 774
      _use_arcs = true;
775 775
      _writer_bits::DefaultConverter<typename Map::Value> converter;
776 776
      for (ArcIt a(_digraph); a != INVALID; ++a) {
777 777
        _arc_index.insert(std::make_pair(converter(map[a]), a));
778 778
      }
779 779
      return *this;
780 780
    }
781 781

	
782 782
    /// \brief Use previously constructed arc set
783 783
    ///
784 784
    /// Use previously constructed arc set, and specify the arc
785 785
    /// label map and a functor which converts the label map values to
786 786
    /// \c std::string.
787 787
    template <typename Map, typename Converter>
788 788
    DigraphReader& useArcs(const Map& map,
789 789
                           const Converter& converter = Converter()) {
790 790
      checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
791 791
      LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member");
792 792
      _use_arcs = true;
793 793
      for (ArcIt a(_digraph); a != INVALID; ++a) {
794 794
        _arc_index.insert(std::make_pair(converter(map[a]), a));
795 795
      }
796 796
      return *this;
797 797
    }
798 798

	
799 799
    /// \brief Skips the reading of node section
800 800
    ///
801 801
    /// Omit the reading of the node section. This implies that each node
802 802
    /// map reading rule will be abandoned, and the nodes of the graph
803 803
    /// will not be constructed, which usually cause that the arc set
804 804
    /// could not be read due to lack of node name resolving.
805 805
    /// Therefore \c skipArcs() function should also be used, or
806 806
    /// \c useNodes() should be used to specify the label of the nodes.
807 807
    DigraphReader& skipNodes() {
808 808
      LEMON_ASSERT(!_skip_nodes, "Skip nodes already set");
809 809
      _skip_nodes = true;
810 810
      return *this;
811 811
    }
812 812

	
813 813
    /// \brief Skips the reading of arc section
814 814
    ///
815 815
    /// Omit the reading of the arc section. This implies that each arc
816 816
    /// map reading rule will be abandoned, and the arcs of the graph
817 817
    /// will not be constructed.
818 818
    DigraphReader& skipArcs() {
819 819
      LEMON_ASSERT(!_skip_arcs, "Skip arcs already set");
820 820
      _skip_arcs = true;
821 821
      return *this;
822 822
    }
823 823

	
824 824
    /// @}
825 825

	
826 826
  private:
827 827

	
828 828
    bool readLine() {
829 829
      std::string str;
830 830
      while(++line_num, std::getline(*_is, str)) {
831 831
        line.clear(); line.str(str);
832 832
        char c;
833 833
        if (line >> std::ws >> c && c != '#') {
834 834
          line.putback(c);
835 835
          return true;
836 836
        }
837 837
      }
838 838
      return false;
839 839
    }
840 840

	
841 841
    bool readSuccess() {
842 842
      return static_cast<bool>(*_is);
843 843
    }
844 844

	
845 845
    void skipSection() {
846 846
      char c;
847 847
      while (readSuccess() && line >> c && c != '@') {
848 848
        readLine();
849 849
      }
850 850
      if (readSuccess()) {
851 851
        line.putback(c);
852 852
      }
853 853
    }
854 854

	
855 855
    void readNodes() {
856 856

	
857 857
      std::vector<int> map_index(_node_maps.size());
858 858
      int map_num, label_index;
859 859

	
860 860
      char c;
861 861
      if (!readLine() || !(line >> c) || c == '@') {
862 862
        if (readSuccess() && line) line.putback(c);
863 863
        if (!_node_maps.empty())
864 864
          throw FormatError("Cannot find map names");
865 865
        return;
866 866
      }
867 867
      line.putback(c);
868 868

	
869 869
      {
870 870
        std::map<std::string, int> maps;
871 871

	
872 872
        std::string map;
873 873
        int index = 0;
874 874
        while (_reader_bits::readToken(line, map)) {
875 875
          if (maps.find(map) != maps.end()) {
876 876
            std::ostringstream msg;
877 877
            msg << "Multiple occurence of node map: " << map;
878 878
            throw FormatError(msg.str());
879 879
          }
880 880
          maps.insert(std::make_pair(map, index));
881 881
          ++index;
882 882
        }
883 883

	
884 884
        for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
885 885
          std::map<std::string, int>::iterator jt =
886 886
            maps.find(_node_maps[i].first);
887 887
          if (jt == maps.end()) {
888 888
            std::ostringstream msg;
889 889
            msg << "Map not found: " << _node_maps[i].first;
890 890
            throw FormatError(msg.str());
891 891
          }
892 892
          map_index[i] = jt->second;
893 893
        }
894 894

	
895 895
        {
896 896
          std::map<std::string, int>::iterator jt = maps.find("label");
897 897
          if (jt != maps.end()) {
898 898
            label_index = jt->second;
899 899
          } else {
900 900
            label_index = -1;
901 901
          }
902 902
        }
903 903
        map_num = maps.size();
904 904
      }
905 905

	
906 906
      while (readLine() && line >> c && c != '@') {
907 907
        line.putback(c);
908 908

	
909 909
        std::vector<std::string> tokens(map_num);
910 910
        for (int i = 0; i < map_num; ++i) {
911 911
          if (!_reader_bits::readToken(line, tokens[i])) {
912 912
            std::ostringstream msg;
913 913
            msg << "Column not found (" << i + 1 << ")";
914 914
            throw FormatError(msg.str());
915 915
          }
916 916
        }
917 917
        if (line >> std::ws >> c)
918 918
          throw FormatError("Extra character at the end of line");
919 919

	
920 920
        Node n;
921 921
        if (!_use_nodes) {
922 922
          n = _digraph.addNode();
923 923
          if (label_index != -1)
924 924
            _node_index.insert(std::make_pair(tokens[label_index], n));
925 925
        } else {
926 926
          if (label_index == -1)
927 927
            throw FormatError("Label map not found");
928 928
          typename std::map<std::string, Node>::iterator it =
929 929
            _node_index.find(tokens[label_index]);
930 930
          if (it == _node_index.end()) {
931 931
            std::ostringstream msg;
932 932
            msg << "Node with label not found: " << tokens[label_index];
933 933
            throw FormatError(msg.str());
934 934
          }
935 935
          n = it->second;
936 936
        }
937 937

	
938 938
        for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
939 939
          _node_maps[i].second->set(n, tokens[map_index[i]]);
940 940
        }
941 941

	
942 942
      }
943 943
      if (readSuccess()) {
944 944
        line.putback(c);
945 945
      }
946 946
    }
947 947

	
948 948
    void readArcs() {
949 949

	
950 950
      std::vector<int> map_index(_arc_maps.size());
951 951
      int map_num, label_index;
952 952

	
953 953
      char c;
954 954
      if (!readLine() || !(line >> c) || c == '@') {
955 955
        if (readSuccess() && line) line.putback(c);
956 956
        if (!_arc_maps.empty())
957 957
          throw FormatError("Cannot find map names");
958 958
        return;
959 959
      }
960 960
      line.putback(c);
961 961

	
962 962
      {
963 963
        std::map<std::string, int> maps;
964 964

	
965 965
        std::string map;
966 966
        int index = 0;
967 967
        while (_reader_bits::readToken(line, map)) {
968 968
          if (maps.find(map) != maps.end()) {
969 969
            std::ostringstream msg;
970 970
            msg << "Multiple occurence of arc map: " << map;
971 971
            throw FormatError(msg.str());
972 972
          }
973 973
          maps.insert(std::make_pair(map, index));
974 974
          ++index;
975 975
        }
976 976

	
977 977
        for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) {
978 978
          std::map<std::string, int>::iterator jt =
979 979
            maps.find(_arc_maps[i].first);
980 980
          if (jt == maps.end()) {
981 981
            std::ostringstream msg;
982 982
            msg << "Map not found: " << _arc_maps[i].first;
983 983
            throw FormatError(msg.str());
984 984
          }
985 985
          map_index[i] = jt->second;
986 986
        }
987 987

	
988 988
        {
989 989
          std::map<std::string, int>::iterator jt = maps.find("label");
990 990
          if (jt != maps.end()) {
991 991
            label_index = jt->second;
992 992
          } else {
993 993
            label_index = -1;
994 994
          }
995 995
        }
996 996
        map_num = maps.size();
997 997
      }
998 998

	
999 999
      while (readLine() && line >> c && c != '@') {
1000 1000
        line.putback(c);
1001 1001

	
1002 1002
        std::string source_token;
1003 1003
        std::string target_token;
1004 1004

	
1005 1005
        if (!_reader_bits::readToken(line, source_token))
1006 1006
          throw FormatError("Source not found");
1007 1007

	
1008 1008
        if (!_reader_bits::readToken(line, target_token))
1009 1009
          throw FormatError("Target not found");
1010 1010

	
1011 1011
        std::vector<std::string> tokens(map_num);
1012 1012
        for (int i = 0; i < map_num; ++i) {
1013 1013
          if (!_reader_bits::readToken(line, tokens[i])) {
1014 1014
            std::ostringstream msg;
1015 1015
            msg << "Column not found (" << i + 1 << ")";
1016 1016
            throw FormatError(msg.str());
1017 1017
          }
1018 1018
        }
1019 1019
        if (line >> std::ws >> c)
1020 1020
          throw FormatError("Extra character at the end of line");
1021 1021

	
1022 1022
        Arc a;
1023 1023
        if (!_use_arcs) {
1024 1024

	
1025 1025
          typename NodeIndex::iterator it;
1026 1026

	
1027 1027
          it = _node_index.find(source_token);
1028 1028
          if (it == _node_index.end()) {
1029 1029
            std::ostringstream msg;
1030 1030
            msg << "Item not found: " << source_token;
1031 1031
            throw FormatError(msg.str());
1032 1032
          }
1033 1033
          Node source = it->second;
1034 1034

	
1035 1035
          it = _node_index.find(target_token);
1036 1036
          if (it == _node_index.end()) {
1037 1037
            std::ostringstream msg;
1038 1038
            msg << "Item not found: " << target_token;
1039 1039
            throw FormatError(msg.str());
1040 1040
          }
1041 1041
          Node target = it->second;
1042 1042

	
1043 1043
          a = _digraph.addArc(source, target);
1044 1044
          if (label_index != -1)
1045 1045
            _arc_index.insert(std::make_pair(tokens[label_index], a));
1046 1046
        } else {
1047 1047
          if (label_index == -1)
1048 1048
            throw FormatError("Label map not found");
1049 1049
          typename std::map<std::string, Arc>::iterator it =
1050 1050
            _arc_index.find(tokens[label_index]);
1051 1051
          if (it == _arc_index.end()) {
1052 1052
            std::ostringstream msg;
1053 1053
            msg << "Arc with label not found: " << tokens[label_index];
1054 1054
            throw FormatError(msg.str());
1055 1055
          }
1056 1056
          a = it->second;
1057 1057
        }
1058 1058

	
1059 1059
        for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) {
1060 1060
          _arc_maps[i].second->set(a, tokens[map_index[i]]);
1061 1061
        }
1062 1062

	
1063 1063
      }
1064 1064
      if (readSuccess()) {
1065 1065
        line.putback(c);
1066 1066
      }
1067 1067
    }
1068 1068

	
1069 1069
    void readAttributes() {
1070 1070

	
1071 1071
      std::set<std::string> read_attr;
1072 1072

	
1073 1073
      char c;
1074 1074
      while (readLine() && line >> c && c != '@') {
1075 1075
        line.putback(c);
1076 1076

	
1077 1077
        std::string attr, token;
1078 1078
        if (!_reader_bits::readToken(line, attr))
1079 1079
          throw FormatError("Attribute name not found");
1080 1080
        if (!_reader_bits::readToken(line, token))
1081 1081
          throw FormatError("Attribute value not found");
1082 1082
        if (line >> c)
1083 1083
          throw FormatError("Extra character at the end of line");
1084 1084

	
1085 1085
        {
1086 1086
          std::set<std::string>::iterator it = read_attr.find(attr);
1087 1087
          if (it != read_attr.end()) {
1088 1088
            std::ostringstream msg;
1089 1089
            msg << "Multiple occurence of attribute: " << attr;
1090 1090
            throw FormatError(msg.str());
1091 1091
          }
1092 1092
          read_attr.insert(attr);
1093 1093
        }
1094 1094

	
1095 1095
        {
1096 1096
          typename Attributes::iterator it = _attributes.lower_bound(attr);
1097 1097
          while (it != _attributes.end() && it->first == attr) {
1098 1098
            it->second->set(token);
1099 1099
            ++it;
1100 1100
          }
1101 1101
        }
1102 1102

	
1103 1103
      }
1104 1104
      if (readSuccess()) {
1105 1105
        line.putback(c);
1106 1106
      }
1107 1107
      for (typename Attributes::iterator it = _attributes.begin();
1108 1108
           it != _attributes.end(); ++it) {
1109 1109
        if (read_attr.find(it->first) == read_attr.end()) {
1110 1110
          std::ostringstream msg;
1111 1111
          msg << "Attribute not found: " << it->first;
1112 1112
          throw FormatError(msg.str());
1113 1113
        }
1114 1114
      }
1115 1115
    }
1116 1116

	
1117 1117
  public:
1118 1118

	
1119
    /// \name Execution of the reader
1119
    /// \name Execution of the Reader
1120 1120
    /// @{
1121 1121

	
1122 1122
    /// \brief Start the batch processing
1123 1123
    ///
1124 1124
    /// This function starts the batch processing
1125 1125
    void run() {
1126 1126
      LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
1127 1127

	
1128 1128
      bool nodes_done = _skip_nodes;
1129 1129
      bool arcs_done = _skip_arcs;
1130 1130
      bool attributes_done = false;
1131 1131

	
1132 1132
      line_num = 0;
1133 1133
      readLine();
1134 1134
      skipSection();
1135 1135

	
1136 1136
      while (readSuccess()) {
1137 1137
        try {
1138 1138
          char c;
1139 1139
          std::string section, caption;
1140 1140
          line >> c;
1141 1141
          _reader_bits::readToken(line, section);
1142 1142
          _reader_bits::readToken(line, caption);
1143 1143

	
1144 1144
          if (line >> c)
1145 1145
            throw FormatError("Extra character at the end of line");
1146 1146

	
1147 1147
          if (section == "nodes" && !nodes_done) {
1148 1148
            if (_nodes_caption.empty() || _nodes_caption == caption) {
1149 1149
              readNodes();
1150 1150
              nodes_done = true;
1151 1151
            }
1152 1152
          } else if ((section == "arcs" || section == "edges") &&
1153 1153
                     !arcs_done) {
1154 1154
            if (_arcs_caption.empty() || _arcs_caption == caption) {
1155 1155
              readArcs();
1156 1156
              arcs_done = true;
1157 1157
            }
1158 1158
          } else if (section == "attributes" && !attributes_done) {
1159 1159
            if (_attributes_caption.empty() || _attributes_caption == caption) {
1160 1160
              readAttributes();
1161 1161
              attributes_done = true;
1162 1162
            }
1163 1163
          } else {
1164 1164
            readLine();
1165 1165
            skipSection();
1166 1166
          }
1167 1167
        } catch (FormatError& error) {
1168 1168
          error.line(line_num);
1169 1169
          error.file(_filename);
1170 1170
          throw;
1171 1171
        }
1172 1172
      }
1173 1173

	
1174 1174
      if (!nodes_done) {
1175 1175
        throw FormatError("Section @nodes not found");
1176 1176
      }
1177 1177

	
1178 1178
      if (!arcs_done) {
1179 1179
        throw FormatError("Section @arcs not found");
1180 1180
      }
1181 1181

	
1182 1182
      if (!attributes_done && !_attributes.empty()) {
1183 1183
        throw FormatError("Section @attributes not found");
1184 1184
      }
1185 1185

	
1186 1186
    }
1187 1187

	
1188 1188
    /// @}
1189 1189

	
1190 1190
  };
1191 1191

	
1192 1192
  /// \brief Return a \ref DigraphReader class
1193 1193
  ///
1194 1194
  /// This function just returns a \ref DigraphReader class.
1195 1195
  /// \relates DigraphReader
1196 1196
  template <typename Digraph>
1197 1197
  DigraphReader<Digraph> digraphReader(Digraph& digraph, std::istream& is) {
1198 1198
    DigraphReader<Digraph> tmp(digraph, is);
1199 1199
    return tmp;
1200 1200
  }
1201 1201

	
1202 1202
  /// \brief Return a \ref DigraphReader class
1203 1203
  ///
1204 1204
  /// This function just returns a \ref DigraphReader class.
1205 1205
  /// \relates DigraphReader
1206 1206
  template <typename Digraph>
1207 1207
  DigraphReader<Digraph> digraphReader(Digraph& digraph,
1208 1208
                                       const std::string& fn) {
1209 1209
    DigraphReader<Digraph> tmp(digraph, fn);
1210 1210
    return tmp;
1211 1211
  }
1212 1212

	
1213 1213
  /// \brief Return a \ref DigraphReader class
1214 1214
  ///
1215 1215
  /// This function just returns a \ref DigraphReader class.
1216 1216
  /// \relates DigraphReader
1217 1217
  template <typename Digraph>
1218 1218
  DigraphReader<Digraph> digraphReader(Digraph& digraph, const char* fn) {
1219 1219
    DigraphReader<Digraph> tmp(digraph, fn);
1220 1220
    return tmp;
1221 1221
  }
1222 1222

	
1223 1223
  template <typename Graph>
1224 1224
  class GraphReader;
1225 1225
 
1226 1226
  template <typename Graph>
1227 1227
  GraphReader<Graph> graphReader(Graph& graph, 
1228 1228
                                 std::istream& is = std::cin);
1229 1229
  template <typename Graph>
1230 1230
  GraphReader<Graph> graphReader(Graph& graph, const std::string& fn);
1231 1231
  template <typename Graph>
1232 1232
  GraphReader<Graph> graphReader(Graph& graph, const char *fn);
1233 1233

	
1234 1234
  /// \ingroup lemon_io
1235 1235
  ///
1236 1236
  /// \brief \ref lgf-format "LGF" reader for undirected graphs
1237 1237
  ///
1238 1238
  /// This utility reads an \ref lgf-format "LGF" file.
1239 1239
  ///
1240 1240
  /// It can be used almost the same way as \c DigraphReader.
1241 1241
  /// The only difference is that this class can handle edges and
1242 1242
  /// edge maps as well as arcs and arc maps.
1243 1243
  ///
1244 1244
  /// The columns in the \c \@edges (or \c \@arcs) section are the
1245 1245
  /// edge maps. However, if there are two maps with the same name
1246 1246
  /// prefixed with \c '+' and \c '-', then these can be read into an
1247 1247
  /// arc map.  Similarly, an attribute can be read into an arc, if
1248 1248
  /// it's value is an edge label prefixed with \c '+' or \c '-'.
1249 1249
  template <typename GR>
1250 1250
  class GraphReader {
1251 1251
  public:
1252 1252

	
1253 1253
    typedef GR Graph;
1254 1254

	
1255 1255
  private:
1256 1256

	
1257 1257
    TEMPLATE_GRAPH_TYPEDEFS(Graph);
1258 1258

	
1259 1259
    std::istream* _is;
1260 1260
    bool local_is;
1261 1261
    std::string _filename;
1262 1262

	
1263 1263
    Graph& _graph;
1264 1264

	
1265 1265
    std::string _nodes_caption;
1266 1266
    std::string _edges_caption;
1267 1267
    std::string _attributes_caption;
1268 1268

	
1269 1269
    typedef std::map<std::string, Node> NodeIndex;
1270 1270
    NodeIndex _node_index;
1271 1271
    typedef std::map<std::string, Edge> EdgeIndex;
1272 1272
    EdgeIndex _edge_index;
1273 1273

	
1274 1274
    typedef std::vector<std::pair<std::string,
1275 1275
      _reader_bits::MapStorageBase<Node>*> > NodeMaps;
1276 1276
    NodeMaps _node_maps;
1277 1277

	
1278 1278
    typedef std::vector<std::pair<std::string,
1279 1279
      _reader_bits::MapStorageBase<Edge>*> > EdgeMaps;
1280 1280
    EdgeMaps _edge_maps;
1281 1281

	
1282 1282
    typedef std::multimap<std::string, _reader_bits::ValueStorageBase*>
1283 1283
      Attributes;
1284 1284
    Attributes _attributes;
1285 1285

	
1286 1286
    bool _use_nodes;
1287 1287
    bool _use_edges;
1288 1288

	
1289 1289
    bool _skip_nodes;
1290 1290
    bool _skip_edges;
1291 1291

	
1292 1292
    int line_num;
1293 1293
    std::istringstream line;
1294 1294

	
1295 1295
  public:
1296 1296

	
1297 1297
    /// \brief Constructor
1298 1298
    ///
1299 1299
    /// Construct an undirected graph reader, which reads from the given
1300 1300
    /// input stream.
1301 1301
    GraphReader(Graph& graph, std::istream& is = std::cin)
1302 1302
      : _is(&is), local_is(false), _graph(graph),
1303 1303
        _use_nodes(false), _use_edges(false),
1304 1304
        _skip_nodes(false), _skip_edges(false) {}
1305 1305

	
1306 1306
    /// \brief Constructor
1307 1307
    ///
1308 1308
    /// Construct an undirected graph reader, which reads from the given
1309 1309
    /// file.
1310 1310
    GraphReader(Graph& graph, const std::string& fn)
1311 1311
      : _is(new std::ifstream(fn.c_str())), local_is(true),
1312 1312
        _filename(fn), _graph(graph),
1313 1313
        _use_nodes(false), _use_edges(false),
1314 1314
        _skip_nodes(false), _skip_edges(false) {
1315 1315
      if (!(*_is)) {
1316 1316
        delete _is;
1317 1317
        throw IoError("Cannot open file", fn);
1318 1318
      }
1319 1319
    }
1320 1320

	
1321 1321
    /// \brief Constructor
1322 1322
    ///
1323 1323
    /// Construct an undirected graph reader, which reads from the given
1324 1324
    /// file.
1325 1325
    GraphReader(Graph& graph, const char* fn)
1326 1326
      : _is(new std::ifstream(fn)), local_is(true),
1327 1327
        _filename(fn), _graph(graph),
1328 1328
        _use_nodes(false), _use_edges(false),
1329 1329
        _skip_nodes(false), _skip_edges(false) {
1330 1330
      if (!(*_is)) {
1331 1331
        delete _is;
1332 1332
        throw IoError("Cannot open file", fn);
1333 1333
      }
1334 1334
    }
1335 1335

	
1336 1336
    /// \brief Destructor
1337 1337
    ~GraphReader() {
1338 1338
      for (typename NodeMaps::iterator it = _node_maps.begin();
1339 1339
           it != _node_maps.end(); ++it) {
1340 1340
        delete it->second;
1341 1341
      }
1342 1342

	
1343 1343
      for (typename EdgeMaps::iterator it = _edge_maps.begin();
1344 1344
           it != _edge_maps.end(); ++it) {
1345 1345
        delete it->second;
1346 1346
      }
1347 1347

	
1348 1348
      for (typename Attributes::iterator it = _attributes.begin();
1349 1349
           it != _attributes.end(); ++it) {
1350 1350
        delete it->second;
1351 1351
      }
1352 1352

	
1353 1353
      if (local_is) {
1354 1354
        delete _is;
1355 1355
      }
1356 1356

	
1357 1357
    }
1358 1358

	
1359 1359
  private:
1360 1360
    template <typename Graph>
1361 1361
    friend GraphReader<Graph> graphReader(Graph& graph, std::istream& is);
1362 1362
    template <typename Graph>
1363 1363
    friend GraphReader<Graph> graphReader(Graph& graph, const std::string& fn); 
1364 1364
    template <typename Graph>
1365 1365
    friend GraphReader<Graph> graphReader(Graph& graph, const char *fn);
1366 1366

	
1367 1367
    GraphReader(GraphReader& other)
1368 1368
      : _is(other._is), local_is(other.local_is), _graph(other._graph),
1369 1369
        _use_nodes(other._use_nodes), _use_edges(other._use_edges),
1370 1370
        _skip_nodes(other._skip_nodes), _skip_edges(other._skip_edges) {
1371 1371

	
1372 1372
      other._is = 0;
1373 1373
      other.local_is = false;
1374 1374

	
1375 1375
      _node_index.swap(other._node_index);
1376 1376
      _edge_index.swap(other._edge_index);
1377 1377

	
1378 1378
      _node_maps.swap(other._node_maps);
1379 1379
      _edge_maps.swap(other._edge_maps);
1380 1380
      _attributes.swap(other._attributes);
1381 1381

	
1382 1382
      _nodes_caption = other._nodes_caption;
1383 1383
      _edges_caption = other._edges_caption;
1384 1384
      _attributes_caption = other._attributes_caption;
1385 1385

	
1386 1386
    }
1387 1387

	
1388 1388
    GraphReader& operator=(const GraphReader&);
1389 1389

	
1390 1390
  public:
1391 1391

	
1392
    /// \name Reading rules
1392
    /// \name Reading Rules
1393 1393
    /// @{
1394 1394

	
1395 1395
    /// \brief Node map reading rule
1396 1396
    ///
1397 1397
    /// Add a node map reading rule to the reader.
1398 1398
    template <typename Map>
1399 1399
    GraphReader& nodeMap(const std::string& caption, Map& map) {
1400 1400
      checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
1401 1401
      _reader_bits::MapStorageBase<Node>* storage =
1402 1402
        new _reader_bits::MapStorage<Node, Map>(map);
1403 1403
      _node_maps.push_back(std::make_pair(caption, storage));
1404 1404
      return *this;
1405 1405
    }
1406 1406

	
1407 1407
    /// \brief Node map reading rule
1408 1408
    ///
1409 1409
    /// Add a node map reading rule with specialized converter to the
1410 1410
    /// reader.
1411 1411
    template <typename Map, typename Converter>
1412 1412
    GraphReader& nodeMap(const std::string& caption, Map& map,
1413 1413
                           const Converter& converter = Converter()) {
1414 1414
      checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
1415 1415
      _reader_bits::MapStorageBase<Node>* storage =
1416 1416
        new _reader_bits::MapStorage<Node, Map, Converter>(map, converter);
1417 1417
      _node_maps.push_back(std::make_pair(caption, storage));
1418 1418
      return *this;
1419 1419
    }
1420 1420

	
1421 1421
    /// \brief Edge map reading rule
1422 1422
    ///
1423 1423
    /// Add an edge map reading rule to the reader.
1424 1424
    template <typename Map>
1425 1425
    GraphReader& edgeMap(const std::string& caption, Map& map) {
1426 1426
      checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>();
1427 1427
      _reader_bits::MapStorageBase<Edge>* storage =
1428 1428
        new _reader_bits::MapStorage<Edge, Map>(map);
1429 1429
      _edge_maps.push_back(std::make_pair(caption, storage));
1430 1430
      return *this;
1431 1431
    }
1432 1432

	
1433 1433
    /// \brief Edge map reading rule
1434 1434
    ///
1435 1435
    /// Add an edge map reading rule with specialized converter to the
1436 1436
    /// reader.
1437 1437
    template <typename Map, typename Converter>
1438 1438
    GraphReader& edgeMap(const std::string& caption, Map& map,
1439 1439
                          const Converter& converter = Converter()) {
1440 1440
      checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>();
1441 1441
      _reader_bits::MapStorageBase<Edge>* storage =
1442 1442
        new _reader_bits::MapStorage<Edge, Map, Converter>(map, converter);
1443 1443
      _edge_maps.push_back(std::make_pair(caption, storage));
1444 1444
      return *this;
1445 1445
    }
1446 1446

	
1447 1447
    /// \brief Arc map reading rule
1448 1448
    ///
1449 1449
    /// Add an arc map reading rule to the reader.
1450 1450
    template <typename Map>
1451 1451
    GraphReader& arcMap(const std::string& caption, Map& map) {
1452 1452
      checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
1453 1453
      _reader_bits::MapStorageBase<Edge>* forward_storage =
1454 1454
        new _reader_bits::GraphArcMapStorage<Graph, true, Map>(_graph, map);
1455 1455
      _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
1456 1456
      _reader_bits::MapStorageBase<Edge>* backward_storage =
1457 1457
        new _reader_bits::GraphArcMapStorage<Graph, false, Map>(_graph, map);
1458 1458
      _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
1459 1459
      return *this;
1460 1460
    }
1461 1461

	
1462 1462
    /// \brief Arc map reading rule
1463 1463
    ///
1464 1464
    /// Add an arc map reading rule with specialized converter to the
1465 1465
    /// reader.
1466 1466
    template <typename Map, typename Converter>
1467 1467
    GraphReader& arcMap(const std::string& caption, Map& map,
1468 1468
                          const Converter& converter = Converter()) {
1469 1469
      checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
1470 1470
      _reader_bits::MapStorageBase<Edge>* forward_storage =
1471 1471
        new _reader_bits::GraphArcMapStorage<Graph, true, Map, Converter>
1472 1472
        (_graph, map, converter);
1473 1473
      _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
1474 1474
      _reader_bits::MapStorageBase<Edge>* backward_storage =
1475 1475
        new _reader_bits::GraphArcMapStorage<Graph, false, Map, Converter>
1476 1476
        (_graph, map, converter);
1477 1477
      _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
1478 1478
      return *this;
1479 1479
    }
1480 1480

	
1481 1481
    /// \brief Attribute reading rule
1482 1482
    ///
1483 1483
    /// Add an attribute reading rule to the reader.
1484 1484
    template <typename Value>
1485 1485
    GraphReader& attribute(const std::string& caption, Value& value) {
1486 1486
      _reader_bits::ValueStorageBase* storage =
1487 1487
        new _reader_bits::ValueStorage<Value>(value);
1488 1488
      _attributes.insert(std::make_pair(caption, storage));
1489 1489
      return *this;
1490 1490
    }
1491 1491

	
1492 1492
    /// \brief Attribute reading rule
1493 1493
    ///
1494 1494
    /// Add an attribute reading rule with specialized converter to the
1495 1495
    /// reader.
1496 1496
    template <typename Value, typename Converter>
1497 1497
    GraphReader& attribute(const std::string& caption, Value& value,
1498 1498
                             const Converter& converter = Converter()) {
1499 1499
      _reader_bits::ValueStorageBase* storage =
1500 1500
        new _reader_bits::ValueStorage<Value, Converter>(value, converter);
1501 1501
      _attributes.insert(std::make_pair(caption, storage));
1502 1502
      return *this;
1503 1503
    }
1504 1504

	
1505 1505
    /// \brief Node reading rule
1506 1506
    ///
1507 1507
    /// Add a node reading rule to reader.
1508 1508
    GraphReader& node(const std::string& caption, Node& node) {
1509 1509
      typedef _reader_bits::MapLookUpConverter<Node> Converter;
1510 1510
      Converter converter(_node_index);
1511 1511
      _reader_bits::ValueStorageBase* storage =
1512 1512
        new _reader_bits::ValueStorage<Node, Converter>(node, converter);
1513 1513
      _attributes.insert(std::make_pair(caption, storage));
1514 1514
      return *this;
1515 1515
    }
1516 1516

	
1517 1517
    /// \brief Edge reading rule
1518 1518
    ///
1519 1519
    /// Add an edge reading rule to reader.
1520 1520
    GraphReader& edge(const std::string& caption, Edge& edge) {
1521 1521
      typedef _reader_bits::MapLookUpConverter<Edge> Converter;
1522 1522
      Converter converter(_edge_index);
1523 1523
      _reader_bits::ValueStorageBase* storage =
1524 1524
        new _reader_bits::ValueStorage<Edge, Converter>(edge, converter);
1525 1525
      _attributes.insert(std::make_pair(caption, storage));
1526 1526
      return *this;
1527 1527
    }
1528 1528

	
1529 1529
    /// \brief Arc reading rule
1530 1530
    ///
1531 1531
    /// Add an arc reading rule to reader.
1532 1532
    GraphReader& arc(const std::string& caption, Arc& arc) {
1533 1533
      typedef _reader_bits::GraphArcLookUpConverter<Graph> Converter;
1534 1534
      Converter converter(_graph, _edge_index);
1535 1535
      _reader_bits::ValueStorageBase* storage =
1536 1536
        new _reader_bits::ValueStorage<Arc, Converter>(arc, converter);
1537 1537
      _attributes.insert(std::make_pair(caption, storage));
1538 1538
      return *this;
1539 1539
    }
1540 1540

	
1541 1541
    /// @}
1542 1542

	
1543
    /// \name Select section by name
1543
    /// \name Select Section by Name
1544 1544
    /// @{
1545 1545

	
1546 1546
    /// \brief Set \c \@nodes section to be read
1547 1547
    ///
1548 1548
    /// Set \c \@nodes section to be read.
1549 1549
    GraphReader& nodes(const std::string& caption) {
1550 1550
      _nodes_caption = caption;
1551 1551
      return *this;
1552 1552
    }
1553 1553

	
1554 1554
    /// \brief Set \c \@edges section to be read
1555 1555
    ///
1556 1556
    /// Set \c \@edges section to be read.
1557 1557
    GraphReader& edges(const std::string& caption) {
1558 1558
      _edges_caption = caption;
1559 1559
      return *this;
1560 1560
    }
1561 1561

	
1562 1562
    /// \brief Set \c \@attributes section to be read
1563 1563
    ///
1564 1564
    /// Set \c \@attributes section to be read.
1565 1565
    GraphReader& attributes(const std::string& caption) {
1566 1566
      _attributes_caption = caption;
1567 1567
      return *this;
1568 1568
    }
1569 1569

	
1570 1570
    /// @}
1571 1571

	
1572
    /// \name Using previously constructed node or edge set
1572
    /// \name Using Previously Constructed Node or Edge Set
1573 1573
    /// @{
1574 1574

	
1575 1575
    /// \brief Use previously constructed node set
1576 1576
    ///
1577 1577
    /// Use previously constructed node set, and specify the node
1578 1578
    /// label map.
1579 1579
    template <typename Map>
1580 1580
    GraphReader& useNodes(const Map& map) {
1581 1581
      checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
1582 1582
      LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
1583 1583
      _use_nodes = true;
1584 1584
      _writer_bits::DefaultConverter<typename Map::Value> converter;
1585 1585
      for (NodeIt n(_graph); n != INVALID; ++n) {
1586 1586
        _node_index.insert(std::make_pair(converter(map[n]), n));
1587 1587
      }
1588 1588
      return *this;
1589 1589
    }
1590 1590

	
1591 1591
    /// \brief Use previously constructed node set
1592 1592
    ///
1593 1593
    /// Use previously constructed node set, and specify the node
1594 1594
    /// label map and a functor which converts the label map values to
1595 1595
    /// \c std::string.
1596 1596
    template <typename Map, typename Converter>
1597 1597
    GraphReader& useNodes(const Map& map,
1598 1598
                            const Converter& converter = Converter()) {
1599 1599
      checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
1600 1600
      LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
1601 1601
      _use_nodes = true;
1602 1602
      for (NodeIt n(_graph); n != INVALID; ++n) {
1603 1603
        _node_index.insert(std::make_pair(converter(map[n]), n));
1604 1604
      }
1605 1605
      return *this;
1606 1606
    }
1607 1607

	
1608 1608
    /// \brief Use previously constructed edge set
1609 1609
    ///
1610 1610
    /// Use previously constructed edge set, and specify the edge
1611 1611
    /// label map.
1612 1612
    template <typename Map>
1613 1613
    GraphReader& useEdges(const Map& map) {
1614 1614
      checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
1615 1615
      LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member");
1616 1616
      _use_edges = true;
1617 1617
      _writer_bits::DefaultConverter<typename Map::Value> converter;
1618 1618
      for (EdgeIt a(_graph); a != INVALID; ++a) {
1619 1619
        _edge_index.insert(std::make_pair(converter(map[a]), a));
1620 1620
      }
1621 1621
      return *this;
1622 1622
    }
1623 1623

	
1624 1624
    /// \brief Use previously constructed edge set
1625 1625
    ///
1626 1626
    /// Use previously constructed edge set, and specify the edge
1627 1627
    /// label map and a functor which converts the label map values to
1628 1628
    /// \c std::string.
1629 1629
    template <typename Map, typename Converter>
1630 1630
    GraphReader& useEdges(const Map& map,
1631 1631
                            const Converter& converter = Converter()) {
1632 1632
      checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
1633 1633
      LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member");
1634 1634
      _use_edges = true;
1635 1635
      for (EdgeIt a(_graph); a != INVALID; ++a) {
1636 1636
        _edge_index.insert(std::make_pair(converter(map[a]), a));
1637 1637
      }
1638 1638
      return *this;
1639 1639
    }
1640 1640

	
1641 1641
    /// \brief Skip the reading of node section
1642 1642
    ///
1643 1643
    /// Omit the reading of the node section. This implies that each node
1644 1644
    /// map reading rule will be abandoned, and the nodes of the graph
1645 1645
    /// will not be constructed, which usually cause that the edge set
1646 1646
    /// could not be read due to lack of node name
1647 1647
    /// could not be read due to lack of node name resolving.
1648 1648
    /// Therefore \c skipEdges() function should also be used, or
1649 1649
    /// \c useNodes() should be used to specify the label of the nodes.
1650 1650
    GraphReader& skipNodes() {
1651 1651
      LEMON_ASSERT(!_skip_nodes, "Skip nodes already set");
1652 1652
      _skip_nodes = true;
1653 1653
      return *this;
1654 1654
    }
1655 1655

	
1656 1656
    /// \brief Skip the reading of edge section
1657 1657
    ///
1658 1658
    /// Omit the reading of the edge section. This implies that each edge
1659 1659
    /// map reading rule will be abandoned, and the edges of the graph
1660 1660
    /// will not be constructed.
1661 1661
    GraphReader& skipEdges() {
1662 1662
      LEMON_ASSERT(!_skip_edges, "Skip edges already set");
1663 1663
      _skip_edges = true;
1664 1664
      return *this;
1665 1665
    }
1666 1666

	
1667 1667
    /// @}
1668 1668

	
1669 1669
  private:
1670 1670

	
1671 1671
    bool readLine() {
1672 1672
      std::string str;
1673 1673
      while(++line_num, std::getline(*_is, str)) {
1674 1674
        line.clear(); line.str(str);
1675 1675
        char c;
1676 1676
        if (line >> std::ws >> c && c != '#') {
1677 1677
          line.putback(c);
1678 1678
          return true;
1679 1679
        }
1680 1680
      }
1681 1681
      return false;
1682 1682
    }
1683 1683

	
1684 1684
    bool readSuccess() {
1685 1685
      return static_cast<bool>(*_is);
1686 1686
    }
1687 1687

	
1688 1688
    void skipSection() {
1689 1689
      char c;
1690 1690
      while (readSuccess() && line >> c && c != '@') {
1691 1691
        readLine();
1692 1692
      }
1693 1693
      if (readSuccess()) {
1694 1694
        line.putback(c);
1695 1695
      }
1696 1696
    }
1697 1697

	
1698 1698
    void readNodes() {
1699 1699

	
1700 1700
      std::vector<int> map_index(_node_maps.size());
1701 1701
      int map_num, label_index;
1702 1702

	
1703 1703
      char c;
1704 1704
      if (!readLine() || !(line >> c) || c == '@') {
1705 1705
        if (readSuccess() && line) line.putback(c);
1706 1706
        if (!_node_maps.empty())
1707 1707
          throw FormatError("Cannot find map names");
1708 1708
        return;
1709 1709
      }
1710 1710
      line.putback(c);
1711 1711

	
1712 1712
      {
1713 1713
        std::map<std::string, int> maps;
1714 1714

	
1715 1715
        std::string map;
1716 1716
        int index = 0;
1717 1717
        while (_reader_bits::readToken(line, map)) {
1718 1718
          if (maps.find(map) != maps.end()) {
1719 1719
            std::ostringstream msg;
1720 1720
            msg << "Multiple occurence of node map: " << map;
1721 1721
            throw FormatError(msg.str());
1722 1722
          }
1723 1723
          maps.insert(std::make_pair(map, index));
1724 1724
          ++index;
1725 1725
        }
1726 1726

	
1727 1727
        for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
1728 1728
          std::map<std::string, int>::iterator jt =
1729 1729
            maps.find(_node_maps[i].first);
1730 1730
          if (jt == maps.end()) {
1731 1731
            std::ostringstream msg;
1732 1732
            msg << "Map not found: " << _node_maps[i].first;
1733 1733
            throw FormatError(msg.str());
1734 1734
          }
1735 1735
          map_index[i] = jt->second;
1736 1736
        }
1737 1737

	
1738 1738
        {
1739 1739
          std::map<std::string, int>::iterator jt = maps.find("label");
1740 1740
          if (jt != maps.end()) {
1741 1741
            label_index = jt->second;
1742 1742
          } else {
1743 1743
            label_index = -1;
1744 1744
          }
1745 1745
        }
1746 1746
        map_num = maps.size();
1747 1747
      }
1748 1748

	
1749 1749
      while (readLine() && line >> c && c != '@') {
1750 1750
        line.putback(c);
1751 1751

	
1752 1752
        std::vector<std::string> tokens(map_num);
1753 1753
        for (int i = 0; i < map_num; ++i) {
1754 1754
          if (!_reader_bits::readToken(line, tokens[i])) {
1755 1755
            std::ostringstream msg;
1756 1756
            msg << "Column not found (" << i + 1 << ")";
1757 1757
            throw FormatError(msg.str());
1758 1758
          }
1759 1759
        }
1760 1760
        if (line >> std::ws >> c)
1761 1761
          throw FormatError("Extra character at the end of line");
1762 1762

	
1763 1763
        Node n;
1764 1764
        if (!_use_nodes) {
1765 1765
          n = _graph.addNode();
1766 1766
          if (label_index != -1)
1767 1767
            _node_index.insert(std::make_pair(tokens[label_index], n));
1768 1768
        } else {
1769 1769
          if (label_index == -1)
1770 1770
            throw FormatError("Label map not found");
1771 1771
          typename std::map<std::string, Node>::iterator it =
1772 1772
            _node_index.find(tokens[label_index]);
1773 1773
          if (it == _node_index.end()) {
1774 1774
            std::ostringstream msg;
1775 1775
            msg << "Node with label not found: " << tokens[label_index];
1776 1776
            throw FormatError(msg.str());
1777 1777
          }
1778 1778
          n = it->second;
1779 1779
        }
1780 1780

	
1781 1781
        for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
1782 1782
          _node_maps[i].second->set(n, tokens[map_index[i]]);
1783 1783
        }
1784 1784

	
1785 1785
      }
1786 1786
      if (readSuccess()) {
1787 1787
        line.putback(c);
1788 1788
      }
1789 1789
    }
1790 1790

	
1791 1791
    void readEdges() {
1792 1792

	
1793 1793
      std::vector<int> map_index(_edge_maps.size());
1794 1794
      int map_num, label_index;
1795 1795

	
1796 1796
      char c;
1797 1797
      if (!readLine() || !(line >> c) || c == '@') {
1798 1798
        if (readSuccess() && line) line.putback(c);
1799 1799
        if (!_edge_maps.empty())
1800 1800
          throw FormatError("Cannot find map names");
1801 1801
        return;
1802 1802
      }
1803 1803
      line.putback(c);
1804 1804

	
1805 1805
      {
1806 1806
        std::map<std::string, int> maps;
1807 1807

	
1808 1808
        std::string map;
1809 1809
        int index = 0;
1810 1810
        while (_reader_bits::readToken(line, map)) {
1811 1811
          if (maps.find(map) != maps.end()) {
1812 1812
            std::ostringstream msg;
1813 1813
            msg << "Multiple occurence of edge map: " << map;
1814 1814
            throw FormatError(msg.str());
1815 1815
          }
1816 1816
          maps.insert(std::make_pair(map, index));
1817 1817
          ++index;
1818 1818
        }
1819 1819

	
1820 1820
        for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) {
1821 1821
          std::map<std::string, int>::iterator jt =
1822 1822
            maps.find(_edge_maps[i].first);
1823 1823
          if (jt == maps.end()) {
1824 1824
            std::ostringstream msg;
1825 1825
            msg << "Map not found: " << _edge_maps[i].first;
1826 1826
            throw FormatError(msg.str());
1827 1827
          }
1828 1828
          map_index[i] = jt->second;
1829 1829
        }
1830 1830

	
1831 1831
        {
1832 1832
          std::map<std::string, int>::iterator jt = maps.find("label");
1833 1833
          if (jt != maps.end()) {
1834 1834
            label_index = jt->second;
1835 1835
          } else {
1836 1836
            label_index = -1;
1837 1837
          }
1838 1838
        }
1839 1839
        map_num = maps.size();
1840 1840
      }
1841 1841

	
1842 1842
      while (readLine() && line >> c && c != '@') {
1843 1843
        line.putback(c);
1844 1844

	
1845 1845
        std::string source_token;
1846 1846
        std::string target_token;
1847 1847

	
1848 1848
        if (!_reader_bits::readToken(line, source_token))
1849 1849
          throw FormatError("Node u not found");
1850 1850

	
1851 1851
        if (!_reader_bits::readToken(line, target_token))
1852 1852
          throw FormatError("Node v not found");
1853 1853

	
1854 1854
        std::vector<std::string> tokens(map_num);
1855 1855
        for (int i = 0; i < map_num; ++i) {
1856 1856
          if (!_reader_bits::readToken(line, tokens[i])) {
1857 1857
            std::ostringstream msg;
1858 1858
            msg << "Column not found (" << i + 1 << ")";
1859 1859
            throw FormatError(msg.str());
1860 1860
          }
1861 1861
        }
1862 1862
        if (line >> std::ws >> c)
1863 1863
          throw FormatError("Extra character at the end of line");
1864 1864

	
1865 1865
        Edge e;
1866 1866
        if (!_use_edges) {
1867 1867

	
1868 1868
          typename NodeIndex::iterator it;
1869 1869

	
1870 1870
          it = _node_index.find(source_token);
1871 1871
          if (it == _node_index.end()) {
1872 1872
            std::ostringstream msg;
1873 1873
            msg << "Item not found: " << source_token;
1874 1874
            throw FormatError(msg.str());
1875 1875
          }
1876 1876
          Node source = it->second;
1877 1877

	
1878 1878
          it = _node_index.find(target_token);
1879 1879
          if (it == _node_index.end()) {
1880 1880
            std::ostringstream msg;
1881 1881
            msg << "Item not found: " << target_token;
1882 1882
            throw FormatError(msg.str());
1883 1883
          }
1884 1884
          Node target = it->second;
1885 1885

	
1886 1886
          e = _graph.addEdge(source, target);
1887 1887
          if (label_index != -1)
1888 1888
            _edge_index.insert(std::make_pair(tokens[label_index], e));
1889 1889
        } else {
1890 1890
          if (label_index == -1)
1891 1891
            throw FormatError("Label map not found");
1892 1892
          typename std::map<std::string, Edge>::iterator it =
1893 1893
            _edge_index.find(tokens[label_index]);
1894 1894
          if (it == _edge_index.end()) {
1895 1895
            std::ostringstream msg;
1896 1896
            msg << "Edge with label not found: " << tokens[label_index];
1897 1897
            throw FormatError(msg.str());
1898 1898
          }
1899 1899
          e = it->second;
1900 1900
        }
1901 1901

	
1902 1902
        for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) {
1903 1903
          _edge_maps[i].second->set(e, tokens[map_index[i]]);
1904 1904
        }
1905 1905

	
1906 1906
      }
1907 1907
      if (readSuccess()) {
1908 1908
        line.putback(c);
1909 1909
      }
1910 1910
    }
1911 1911

	
1912 1912
    void readAttributes() {
1913 1913

	
1914 1914
      std::set<std::string> read_attr;
1915 1915

	
1916 1916
      char c;
1917 1917
      while (readLine() && line >> c && c != '@') {
1918 1918
        line.putback(c);
1919 1919

	
1920 1920
        std::string attr, token;
1921 1921
        if (!_reader_bits::readToken(line, attr))
1922 1922
          throw FormatError("Attribute name not found");
1923 1923
        if (!_reader_bits::readToken(line, token))
1924 1924
          throw FormatError("Attribute value not found");
1925 1925
        if (line >> c)
1926 1926
          throw FormatError("Extra character at the end of line");
1927 1927

	
1928 1928
        {
1929 1929
          std::set<std::string>::iterator it = read_attr.find(attr);
1930 1930
          if (it != read_attr.end()) {
1931 1931
            std::ostringstream msg;
1932 1932
            msg << "Multiple occurence of attribute: " << attr;
1933 1933
            throw FormatError(msg.str());
1934 1934
          }
1935 1935
          read_attr.insert(attr);
1936 1936
        }
1937 1937

	
1938 1938
        {
1939 1939
          typename Attributes::iterator it = _attributes.lower_bound(attr);
1940 1940
          while (it != _attributes.end() && it->first == attr) {
1941 1941
            it->second->set(token);
1942 1942
            ++it;
1943 1943
          }
1944 1944
        }
1945 1945

	
1946 1946
      }
1947 1947
      if (readSuccess()) {
1948 1948
        line.putback(c);
1949 1949
      }
1950 1950
      for (typename Attributes::iterator it = _attributes.begin();
1951 1951
           it != _attributes.end(); ++it) {
1952 1952
        if (read_attr.find(it->first) == read_attr.end()) {
1953 1953
          std::ostringstream msg;
1954 1954
          msg << "Attribute not found: " << it->first;
1955 1955
          throw FormatError(msg.str());
1956 1956
        }
1957 1957
      }
1958 1958
    }
1959 1959

	
1960 1960
  public:
1961 1961

	
1962
    /// \name Execution of the reader
1962
    /// \name Execution of the Reader
1963 1963
    /// @{
1964 1964

	
1965 1965
    /// \brief Start the batch processing
1966 1966
    ///
1967 1967
    /// This function starts the batch processing
1968 1968
    void run() {
1969 1969

	
1970 1970
      LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
1971 1971

	
1972 1972
      bool nodes_done = _skip_nodes;
1973 1973
      bool edges_done = _skip_edges;
1974 1974
      bool attributes_done = false;
1975 1975

	
1976 1976
      line_num = 0;
1977 1977
      readLine();
1978 1978
      skipSection();
1979 1979

	
1980 1980
      while (readSuccess()) {
1981 1981
        try {
1982 1982
          char c;
1983 1983
          std::string section, caption;
1984 1984
          line >> c;
1985 1985
          _reader_bits::readToken(line, section);
1986 1986
          _reader_bits::readToken(line, caption);
1987 1987

	
1988 1988
          if (line >> c)
1989 1989
            throw FormatError("Extra character at the end of line");
1990 1990

	
1991 1991
          if (section == "nodes" && !nodes_done) {
1992 1992
            if (_nodes_caption.empty() || _nodes_caption == caption) {
1993 1993
              readNodes();
1994 1994
              nodes_done = true;
1995 1995
            }
1996 1996
          } else if ((section == "edges" || section == "arcs") &&
1997 1997
                     !edges_done) {
1998 1998
            if (_edges_caption.empty() || _edges_caption == caption) {
1999 1999
              readEdges();
2000 2000
              edges_done = true;
2001 2001
            }
2002 2002
          } else if (section == "attributes" && !attributes_done) {
2003 2003
            if (_attributes_caption.empty() || _attributes_caption == caption) {
2004 2004
              readAttributes();
2005 2005
              attributes_done = true;
2006 2006
            }
2007 2007
          } else {
2008 2008
            readLine();
2009 2009
            skipSection();
2010 2010
          }
2011 2011
        } catch (FormatError& error) {
2012 2012
          error.line(line_num);
2013 2013
          error.file(_filename);
2014 2014
          throw;
2015 2015
        }
2016 2016
      }
2017 2017

	
2018 2018
      if (!nodes_done) {
2019 2019
        throw FormatError("Section @nodes not found");
2020 2020
      }
2021 2021

	
2022 2022
      if (!edges_done) {
2023 2023
        throw FormatError("Section @edges not found");
2024 2024
      }
2025 2025

	
2026 2026
      if (!attributes_done && !_attributes.empty()) {
2027 2027
        throw FormatError("Section @attributes not found");
2028 2028
      }
2029 2029

	
2030 2030
    }
2031 2031

	
2032 2032
    /// @}
2033 2033

	
2034 2034
  };
2035 2035

	
2036 2036
  /// \brief Return a \ref GraphReader class
2037 2037
  ///
2038 2038
  /// This function just returns a \ref GraphReader class.
2039 2039
  /// \relates GraphReader
2040 2040
  template <typename Graph>
2041 2041
  GraphReader<Graph> graphReader(Graph& graph, std::istream& is) {
2042 2042
    GraphReader<Graph> tmp(graph, is);
2043 2043
    return tmp;
2044 2044
  }
2045 2045

	
2046 2046
  /// \brief Return a \ref GraphReader class
2047 2047
  ///
2048 2048
  /// This function just returns a \ref GraphReader class.
2049 2049
  /// \relates GraphReader
2050 2050
  template <typename Graph>
2051 2051
  GraphReader<Graph> graphReader(Graph& graph, const std::string& fn) {
2052 2052
    GraphReader<Graph> tmp(graph, fn);
2053 2053
    return tmp;
2054 2054
  }
2055 2055

	
2056 2056
  /// \brief Return a \ref GraphReader class
2057 2057
  ///
2058 2058
  /// This function just returns a \ref GraphReader class.
2059 2059
  /// \relates GraphReader
2060 2060
  template <typename Graph>
2061 2061
  GraphReader<Graph> graphReader(Graph& graph, const char* fn) {
2062 2062
    GraphReader<Graph> tmp(graph, fn);
2063 2063
    return tmp;
2064 2064
  }
2065 2065

	
2066 2066
  class SectionReader;
2067 2067

	
2068 2068
  SectionReader sectionReader(std::istream& is);
2069 2069
  SectionReader sectionReader(const std::string& fn);
2070 2070
  SectionReader sectionReader(const char* fn);
2071 2071

	
2072 2072
  /// \ingroup lemon_io
2073 2073
  ///
2074 2074
  /// \brief Section reader class
2075 2075
  ///
2076 2076
  /// In the \ref lgf-format "LGF" file extra sections can be placed,
2077 2077
  /// which contain any data in arbitrary format. Such sections can be
2078 2078
  /// read with this class. A reading rule can be added to the class
2079 2079
  /// with two different functions. With the \c sectionLines() function a
2080 2080
  /// functor can process the section line-by-line, while with the \c
2081 2081
  /// sectionStream() member the section can be read from an input
2082 2082
  /// stream.
2083 2083
  class SectionReader {
2084 2084
  private:
2085 2085

	
2086 2086
    std::istream* _is;
2087 2087
    bool local_is;
2088 2088
    std::string _filename;
2089 2089

	
2090 2090
    typedef std::map<std::string, _reader_bits::Section*> Sections;
2091 2091
    Sections _sections;
2092 2092

	
2093 2093
    int line_num;
2094 2094
    std::istringstream line;
2095 2095

	
2096 2096
  public:
2097 2097

	
2098 2098
    /// \brief Constructor
2099 2099
    ///
2100 2100
    /// Construct a section reader, which reads from the given input
2101 2101
    /// stream.
2102 2102
    SectionReader(std::istream& is)
2103 2103
      : _is(&is), local_is(false) {}
2104 2104

	
2105 2105
    /// \brief Constructor
2106 2106
    ///
2107 2107
    /// Construct a section reader, which reads from the given file.
2108 2108
    SectionReader(const std::string& fn)
2109 2109
      : _is(new std::ifstream(fn.c_str())), local_is(true),
2110 2110
        _filename(fn) {
2111 2111
      if (!(*_is)) {
2112 2112
        delete _is;
2113 2113
        throw IoError("Cannot open file", fn);
2114 2114
      }
2115 2115
    }
2116 2116

	
2117 2117
    /// \brief Constructor
2118 2118
    ///
2119 2119
    /// Construct a section reader, which reads from the given file.
2120 2120
    SectionReader(const char* fn)
2121 2121
      : _is(new std::ifstream(fn)), local_is(true),
2122 2122
        _filename(fn) {
2123 2123
      if (!(*_is)) {
2124 2124
        delete _is;
2125 2125
        throw IoError("Cannot open file", fn);
2126 2126
      }
2127 2127
    }
2128 2128

	
2129 2129
    /// \brief Destructor
2130 2130
    ~SectionReader() {
2131 2131
      for (Sections::iterator it = _sections.begin();
2132 2132
           it != _sections.end(); ++it) {
2133 2133
        delete it->second;
2134 2134
      }
2135 2135

	
2136 2136
      if (local_is) {
2137 2137
        delete _is;
2138 2138
      }
2139 2139

	
2140 2140
    }
2141 2141

	
2142 2142
  private:
2143 2143

	
2144 2144
    friend SectionReader sectionReader(std::istream& is);
2145 2145
    friend SectionReader sectionReader(const std::string& fn);
2146 2146
    friend SectionReader sectionReader(const char* fn);
2147 2147

	
2148 2148
    SectionReader(SectionReader& other)
2149 2149
      : _is(other._is), local_is(other.local_is) {
2150 2150

	
2151 2151
      other._is = 0;
2152 2152
      other.local_is = false;
2153 2153

	
2154 2154
      _sections.swap(other._sections);
2155 2155
    }
2156 2156

	
2157 2157
    SectionReader& operator=(const SectionReader&);
2158 2158

	
2159 2159
  public:
2160 2160

	
2161
    /// \name Section readers
2161
    /// \name Section Readers
2162 2162
    /// @{
2163 2163

	
2164 2164
    /// \brief Add a section processor with line oriented reading
2165 2165
    ///
2166 2166
    /// The first parameter is the type descriptor of the section, the
2167 2167
    /// second is a functor, which takes just one \c std::string
2168 2168
    /// parameter. At the reading process, each line of the section
2169 2169
    /// will be given to the functor object. However, the empty lines
2170 2170
    /// and the comment lines are filtered out, and the leading
2171 2171
    /// whitespaces are trimmed from each processed string.
2172 2172
    ///
2173 2173
    /// For example let's see a section, which contain several
2174 2174
    /// integers, which should be inserted into a vector.
2175 2175
    ///\code
2176 2176
    ///  @numbers
2177 2177
    ///  12 45 23
2178 2178
    ///  4
2179 2179
    ///  23 6
2180 2180
    ///\endcode
2181 2181
    ///
2182 2182
    /// The functor is implemented as a struct:
2183 2183
    ///\code
2184 2184
    ///  struct NumberSection {
2185 2185
    ///    std::vector<int>& _data;
2186 2186
    ///    NumberSection(std::vector<int>& data) : _data(data) {}
2187 2187
    ///    void operator()(const std::string& line) {
2188 2188
    ///      std::istringstream ls(line);
2189 2189
    ///      int value;
2190 2190
    ///      while (ls >> value) _data.push_back(value);
2191 2191
    ///    }
2192 2192
    ///  };
2193 2193
    ///
2194 2194
    ///  // ...
2195 2195
    ///
2196 2196
    ///  reader.sectionLines("numbers", NumberSection(vec));
2197 2197
    ///\endcode
2198 2198
    template <typename Functor>
2199 2199
    SectionReader& sectionLines(const std::string& type, Functor functor) {
2200 2200
      LEMON_ASSERT(!type.empty(), "Type is empty.");
2201 2201
      LEMON_ASSERT(_sections.find(type) == _sections.end(),
2202 2202
                   "Multiple reading of section.");
2203 2203
      _sections.insert(std::make_pair(type,
2204 2204
        new _reader_bits::LineSection<Functor>(functor)));
2205 2205
      return *this;
2206 2206
    }
2207 2207

	
2208 2208

	
2209 2209
    /// \brief Add a section processor with stream oriented reading
2210 2210
    ///
2211 2211
    /// The first parameter is the type of the section, the second is
2212 2212
    /// a functor, which takes an \c std::istream& and an \c int&
2213 2213
    /// parameter, the latter regard to the line number of stream. The
2214 2214
    /// functor can read the input while the section go on, and the
2215 2215
    /// line number should be modified accordingly.
2216 2216
    template <typename Functor>
2217 2217
    SectionReader& sectionStream(const std::string& type, Functor functor) {
2218 2218
      LEMON_ASSERT(!type.empty(), "Type is empty.");
2219 2219
      LEMON_ASSERT(_sections.find(type) == _sections.end(),
2220 2220
                   "Multiple reading of section.");
2221 2221
      _sections.insert(std::make_pair(type,
2222 2222
         new _reader_bits::StreamSection<Functor>(functor)));
2223 2223
      return *this;
2224 2224
    }
2225 2225

	
2226 2226
    /// @}
2227 2227

	
2228 2228
  private:
2229 2229

	
2230 2230
    bool readLine() {
2231 2231
      std::string str;
2232 2232
      while(++line_num, std::getline(*_is, str)) {
2233 2233
        line.clear(); line.str(str);
2234 2234
        char c;
2235 2235
        if (line >> std::ws >> c && c != '#') {
2236 2236
          line.putback(c);
2237 2237
          return true;
2238 2238
        }
2239 2239
      }
2240 2240
      return false;
2241 2241
    }
2242 2242

	
2243 2243
    bool readSuccess() {
2244 2244
      return static_cast<bool>(*_is);
2245 2245
    }
2246 2246

	
2247 2247
    void skipSection() {
2248 2248
      char c;
2249 2249
      while (readSuccess() && line >> c && c != '@') {
2250 2250
        readLine();
2251 2251
      }
2252 2252
      if (readSuccess()) {
2253 2253
        line.putback(c);
2254 2254
      }
2255 2255
    }
2256 2256

	
2257 2257
  public:
2258 2258

	
2259 2259

	
2260
    /// \name Execution of the reader
2260
    /// \name Execution of the Reader
2261 2261
    /// @{
2262 2262

	
2263 2263
    /// \brief Start the batch processing
2264 2264
    ///
2265 2265
    /// This function starts the batch processing.
2266 2266
    void run() {
2267 2267

	
2268 2268
      LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
2269 2269

	
2270 2270
      std::set<std::string> extra_sections;
2271 2271

	
2272 2272
      line_num = 0;
2273 2273
      readLine();
2274 2274
      skipSection();
2275 2275

	
2276 2276
      while (readSuccess()) {
2277 2277
        try {
2278 2278
          char c;
2279 2279
          std::string section, caption;
2280 2280
          line >> c;
2281 2281
          _reader_bits::readToken(line, section);
2282 2282
          _reader_bits::readToken(line, caption);
2283 2283

	
2284 2284
          if (line >> c)
2285 2285
            throw FormatError("Extra character at the end of line");
2286 2286

	
2287 2287
          if (extra_sections.find(section) != extra_sections.end()) {
2288 2288
            std::ostringstream msg;
2289 2289
            msg << "Multiple occurence of section: " << section;
2290 2290
            throw FormatError(msg.str());
2291 2291
          }
2292 2292
          Sections::iterator it = _sections.find(section);
2293 2293
          if (it != _sections.end()) {
2294 2294
            extra_sections.insert(section);
2295 2295
            it->second->process(*_is, line_num);
2296 2296
          }
2297 2297
          readLine();
2298 2298
          skipSection();
2299 2299
        } catch (FormatError& error) {
2300 2300
          error.line(line_num);
2301 2301
          error.file(_filename);
2302 2302
          throw;
2303 2303
        }
2304 2304
      }
2305 2305
      for (Sections::iterator it = _sections.begin();
2306 2306
           it != _sections.end(); ++it) {
2307 2307
        if (extra_sections.find(it->first) == extra_sections.end()) {
2308 2308
          std::ostringstream os;
2309 2309
          os << "Cannot find section: " << it->first;
2310 2310
          throw FormatError(os.str());
2311 2311
        }
2312 2312
      }
2313 2313
    }
2314 2314

	
2315 2315
    /// @}
2316 2316

	
2317 2317
  };
2318 2318

	
2319 2319
  /// \brief Return a \ref SectionReader class
2320 2320
  ///
2321 2321
  /// This function just returns a \ref SectionReader class.
2322 2322
  /// \relates SectionReader
2323 2323
  inline SectionReader sectionReader(std::istream& is) {
2324 2324
    SectionReader tmp(is);
2325 2325
    return tmp;
2326 2326
  }
2327 2327

	
2328 2328
  /// \brief Return a \ref SectionReader class
2329 2329
  ///
2330 2330
  /// This function just returns a \ref SectionReader class.
2331 2331
  /// \relates SectionReader
2332 2332
  inline SectionReader sectionReader(const std::string& fn) {
2333 2333
    SectionReader tmp(fn);
2334 2334
    return tmp;
2335 2335
  }
2336 2336

	
2337 2337
  /// \brief Return a \ref SectionReader class
2338 2338
  ///
2339 2339
  /// This function just returns a \ref SectionReader class.
2340 2340
  /// \relates SectionReader
2341 2341
  inline SectionReader sectionReader(const char* fn) {
2342 2342
    SectionReader tmp(fn);
2343 2343
    return tmp;
2344 2344
  }
2345 2345

	
2346 2346
  /// \ingroup lemon_io
2347 2347
  ///
2348 2348
  /// \brief Reader for the contents of the \ref lgf-format "LGF" file
2349 2349
  ///
2350 2350
  /// This class can be used to read the sections, the map names and
2351 2351
  /// the attributes from a file. Usually, the LEMON programs know
2352 2352
  /// that, which type of graph, which maps and which attributes
2353 2353
  /// should be read from a file, but in general tools (like glemon)
2354 2354
  /// the contents of an LGF file should be guessed somehow. This class
2355 2355
  /// reads the graph and stores the appropriate information for
2356 2356
  /// reading the graph.
2357 2357
  ///
2358 2358
  ///\code
2359 2359
  /// LgfContents contents("graph.lgf");
2360 2360
  /// contents.run();
2361 2361
  ///
2362 2362
  /// // Does it contain any node section and arc section?
2363 2363
  /// if (contents.nodeSectionNum() == 0 || contents.arcSectionNum()) {
2364 2364
  ///   std::cerr << "Failure, cannot find graph." << std::endl;
2365 2365
  ///   return -1;
2366 2366
  /// }
2367 2367
  /// std::cout << "The name of the default node section: "
2368 2368
  ///           << contents.nodeSection(0) << std::endl;
2369 2369
  /// std::cout << "The number of the arc maps: "
2370 2370
  ///           << contents.arcMaps(0).size() << std::endl;
2371 2371
  /// std::cout << "The name of second arc map: "
2372 2372
  ///           << contents.arcMaps(0)[1] << std::endl;
2373 2373
  ///\endcode
2374 2374
  class LgfContents {
2375 2375
  private:
2376 2376

	
2377 2377
    std::istream* _is;
2378 2378
    bool local_is;
2379 2379

	
2380 2380
    std::vector<std::string> _node_sections;
2381 2381
    std::vector<std::string> _edge_sections;
2382 2382
    std::vector<std::string> _attribute_sections;
2383 2383
    std::vector<std::string> _extra_sections;
2384 2384

	
2385 2385
    std::vector<bool> _arc_sections;
2386 2386

	
2387 2387
    std::vector<std::vector<std::string> > _node_maps;
2388 2388
    std::vector<std::vector<std::string> > _edge_maps;
2389 2389

	
2390 2390
    std::vector<std::vector<std::string> > _attributes;
2391 2391

	
2392 2392

	
2393 2393
    int line_num;
2394 2394
    std::istringstream line;
2395 2395

	
2396 2396
  public:
2397 2397

	
2398 2398
    /// \brief Constructor
2399 2399
    ///
2400 2400
    /// Construct an \e LGF contents reader, which reads from the given
2401 2401
    /// input stream.
2402 2402
    LgfContents(std::istream& is)
2403 2403
      : _is(&is), local_is(false) {}
2404 2404

	
2405 2405
    /// \brief Constructor
2406 2406
    ///
2407 2407
    /// Construct an \e LGF contents reader, which reads from the given
2408 2408
    /// file.
2409 2409
    LgfContents(const std::string& fn)
2410 2410
      : _is(new std::ifstream(fn.c_str())), local_is(true) {
2411 2411
      if (!(*_is)) {
2412 2412
        delete _is;
2413 2413
        throw IoError("Cannot open file", fn);
2414 2414
      }
2415 2415
    }
2416 2416

	
2417 2417
    /// \brief Constructor
2418 2418
    ///
2419 2419
    /// Construct an \e LGF contents reader, which reads from the given
2420 2420
    /// file.
2421 2421
    LgfContents(const char* fn)
2422 2422
      : _is(new std::ifstream(fn)), local_is(true) {
2423 2423
      if (!(*_is)) {
2424 2424
        delete _is;
2425 2425
        throw IoError("Cannot open file", fn);
2426 2426
      }
2427 2427
    }
2428 2428

	
2429 2429
    /// \brief Destructor
2430 2430
    ~LgfContents() {
2431 2431
      if (local_is) delete _is;
2432 2432
    }
2433 2433

	
2434 2434
  private:
2435 2435

	
2436 2436
    LgfContents(const LgfContents&);
2437 2437
    LgfContents& operator=(const LgfContents&);
2438 2438

	
2439 2439
  public:
2440 2440

	
2441 2441

	
2442
    /// \name Node sections
2442
    /// \name Node Sections
2443 2443
    /// @{
2444 2444

	
2445 2445
    /// \brief Gives back the number of node sections in the file.
2446 2446
    ///
2447 2447
    /// Gives back the number of node sections in the file.
2448 2448
    int nodeSectionNum() const {
2449 2449
      return _node_sections.size();
2450 2450
    }
2451 2451

	
2452 2452
    /// \brief Returns the node section name at the given position.
2453 2453
    ///
2454 2454
    /// Returns the node section name at the given position.
2455 2455
    const std::string& nodeSection(int i) const {
2456 2456
      return _node_sections[i];
2457 2457
    }
2458 2458

	
2459 2459
    /// \brief Gives back the node maps for the given section.
2460 2460
    ///
2461 2461
    /// Gives back the node maps for the given section.
2462 2462
    const std::vector<std::string>& nodeMapNames(int i) const {
2463 2463
      return _node_maps[i];
2464 2464
    }
2465 2465

	
2466 2466
    /// @}
2467 2467

	
2468
    /// \name Arc/Edge sections
2468
    /// \name Arc/Edge Sections
2469 2469
    /// @{
2470 2470

	
2471 2471
    /// \brief Gives back the number of arc/edge sections in the file.
2472 2472
    ///
2473 2473
    /// Gives back the number of arc/edge sections in the file.
2474 2474
    /// \note It is synonym of \c edgeSectionNum().
2475 2475
    int arcSectionNum() const {
2476 2476
      return _edge_sections.size();
2477 2477
    }
2478 2478

	
2479 2479
    /// \brief Returns the arc/edge section name at the given position.
2480 2480
    ///
2481 2481
    /// Returns the arc/edge section name at the given position.
2482 2482
    /// \note It is synonym of \c edgeSection().
2483 2483
    const std::string& arcSection(int i) const {
2484 2484
      return _edge_sections[i];
2485 2485
    }
2486 2486

	
2487 2487
    /// \brief Gives back the arc/edge maps for the given section.
2488 2488
    ///
2489 2489
    /// Gives back the arc/edge maps for the given section.
2490 2490
    /// \note It is synonym of \c edgeMapNames().
2491 2491
    const std::vector<std::string>& arcMapNames(int i) const {
2492 2492
      return _edge_maps[i];
2493 2493
    }
2494 2494

	
2495 2495
    /// @}
2496 2496

	
2497 2497
    /// \name Synonyms
2498 2498
    /// @{
2499 2499

	
2500 2500
    /// \brief Gives back the number of arc/edge sections in the file.
2501 2501
    ///
2502 2502
    /// Gives back the number of arc/edge sections in the file.
2503 2503
    /// \note It is synonym of \c arcSectionNum().
2504 2504
    int edgeSectionNum() const {
2505 2505
      return _edge_sections.size();
2506 2506
    }
2507 2507

	
2508 2508
    /// \brief Returns the section name at the given position.
2509 2509
    ///
2510 2510
    /// Returns the section name at the given position.
2511 2511
    /// \note It is synonym of \c arcSection().
2512 2512
    const std::string& edgeSection(int i) const {
2513 2513
      return _edge_sections[i];
2514 2514
    }
2515 2515

	
2516 2516
    /// \brief Gives back the edge maps for the given section.
2517 2517
    ///
2518 2518
    /// Gives back the edge maps for the given section.
2519 2519
    /// \note It is synonym of \c arcMapNames().
2520 2520
    const std::vector<std::string>& edgeMapNames(int i) const {
2521 2521
      return _edge_maps[i];
2522 2522
    }
2523 2523

	
2524 2524
    /// @}
2525 2525

	
2526
    /// \name Attribute sections
2526
    /// \name Attribute Sections
2527 2527
    /// @{
2528 2528

	
2529 2529
    /// \brief Gives back the number of attribute sections in the file.
2530 2530
    ///
2531 2531
    /// Gives back the number of attribute sections in the file.
2532 2532
    int attributeSectionNum() const {
2533 2533
      return _attribute_sections.size();
2534 2534
    }
2535 2535

	
2536 2536
    /// \brief Returns the attribute section name at the given position.
2537 2537
    ///
2538 2538
    /// Returns the attribute section name at the given position.
2539 2539
    const std::string& attributeSectionNames(int i) const {
2540 2540
      return _attribute_sections[i];
2541 2541
    }
2542 2542

	
2543 2543
    /// \brief Gives back the attributes for the given section.
2544 2544
    ///
2545 2545
    /// Gives back the attributes for the given section.
2546 2546
    const std::vector<std::string>& attributes(int i) const {
2547 2547
      return _attributes[i];
2548 2548
    }
2549 2549

	
2550 2550
    /// @}
2551 2551

	
2552
    /// \name Extra sections
2552
    /// \name Extra Sections
2553 2553
    /// @{
2554 2554

	
2555 2555
    /// \brief Gives back the number of extra sections in the file.
2556 2556
    ///
2557 2557
    /// Gives back the number of extra sections in the file.
2558 2558
    int extraSectionNum() const {
2559 2559
      return _extra_sections.size();
2560 2560
    }
2561 2561

	
2562 2562
    /// \brief Returns the extra section type at the given position.
2563 2563
    ///
2564 2564
    /// Returns the section type at the given position.
2565 2565
    const std::string& extraSection(int i) const {
2566 2566
      return _extra_sections[i];
2567 2567
    }
2568 2568

	
2569 2569
    /// @}
2570 2570

	
2571 2571
  private:
2572 2572

	
2573 2573
    bool readLine() {
2574 2574
      std::string str;
2575 2575
      while(++line_num, std::getline(*_is, str)) {
2576 2576
        line.clear(); line.str(str);
2577 2577
        char c;
2578 2578
        if (line >> std::ws >> c && c != '#') {
2579 2579
          line.putback(c);
2580 2580
          return true;
2581 2581
        }
2582 2582
      }
2583 2583
      return false;
2584 2584
    }
2585 2585

	
2586 2586
    bool readSuccess() {
2587 2587
      return static_cast<bool>(*_is);
2588 2588
    }
2589 2589

	
2590 2590
    void skipSection() {
2591 2591
      char c;
2592 2592
      while (readSuccess() && line >> c && c != '@') {
2593 2593
        readLine();
2594 2594
      }
2595 2595
      if (readSuccess()) {
2596 2596
        line.putback(c);
2597 2597
      }
2598 2598
    }
2599 2599

	
2600 2600
    void readMaps(std::vector<std::string>& maps) {
2601 2601
      char c;
2602 2602
      if (!readLine() || !(line >> c) || c == '@') {
2603 2603
        if (readSuccess() && line) line.putback(c);
2604 2604
        return;
2605 2605
      }
2606 2606
      line.putback(c);
2607 2607
      std::string map;
2608 2608
      while (_reader_bits::readToken(line, map)) {
2609 2609
        maps.push_back(map);
2610 2610
      }
2611 2611
    }
2612 2612

	
2613 2613
    void readAttributes(std::vector<std::string>& attrs) {
2614 2614
      readLine();
2615 2615
      char c;
2616 2616
      while (readSuccess() && line >> c && c != '@') {
2617 2617
        line.putback(c);
2618 2618
        std::string attr;
2619 2619
        _reader_bits::readToken(line, attr);
2620 2620
        attrs.push_back(attr);
2621 2621
        readLine();
2622 2622
      }
2623 2623
      line.putback(c);
2624 2624
    }
2625 2625

	
2626 2626
  public:
2627 2627

	
2628
    /// \name Execution of the contents reader
2628
    /// \name Execution of the Contents Reader
2629 2629
    /// @{
2630 2630

	
2631 2631
    /// \brief Starts the reading
2632 2632
    ///
2633 2633
    /// This function starts the reading.
2634 2634
    void run() {
2635 2635

	
2636 2636
      readLine();
2637 2637
      skipSection();
2638 2638

	
2639 2639
      while (readSuccess()) {
2640 2640

	
2641 2641
        char c;
2642 2642
        line >> c;
2643 2643

	
2644 2644
        std::string section, caption;
2645 2645
        _reader_bits::readToken(line, section);
2646 2646
        _reader_bits::readToken(line, caption);
2647 2647

	
2648 2648
        if (section == "nodes") {
2649 2649
          _node_sections.push_back(caption);
2650 2650
          _node_maps.push_back(std::vector<std::string>());
2651 2651
          readMaps(_node_maps.back());
2652 2652
          readLine(); skipSection();
2653 2653
        } else if (section == "arcs" || section == "edges") {
2654 2654
          _edge_sections.push_back(caption);
2655 2655
          _arc_sections.push_back(section == "arcs");
2656 2656
          _edge_maps.push_back(std::vector<std::string>());
2657 2657
          readMaps(_edge_maps.back());
2658 2658
          readLine(); skipSection();
2659 2659
        } else if (section == "attributes") {
2660 2660
          _attribute_sections.push_back(caption);
2661 2661
          _attributes.push_back(std::vector<std::string>());
2662 2662
          readAttributes(_attributes.back());
2663 2663
        } else {
2664 2664
          _extra_sections.push_back(section);
2665 2665
          readLine(); skipSection();
2666 2666
        }
2667 2667
      }
2668 2668
    }
2669 2669

	
2670 2670
    /// @}
2671 2671

	
2672 2672
  };
2673 2673
}
2674 2674

	
2675 2675
#endif
Ignore white space 6 line context
... ...
@@ -285,1493 +285,1493 @@
285 285
      char c;
286 286
      while (is.get(c)) {
287 287
        if (isWhiteSpace(c) || isEscaped(c)) {
288 288
          return true;
289 289
        }
290 290
      }
291 291
      return false;
292 292
    }
293 293

	
294 294
    inline std::ostream& writeToken(std::ostream& os, const std::string& str) {
295 295

	
296 296
      if (requireEscape(str)) {
297 297
        os << '\"';
298 298
        for (std::string::const_iterator it = str.begin();
299 299
             it != str.end(); ++it) {
300 300
          writeEscape(os, *it);
301 301
        }
302 302
        os << '\"';
303 303
      } else {
304 304
        os << str;
305 305
      }
306 306
      return os;
307 307
    }
308 308

	
309 309
    class Section {
310 310
    public:
311 311
      virtual ~Section() {}
312 312
      virtual void process(std::ostream& os) = 0;
313 313
    };
314 314

	
315 315
    template <typename Functor>
316 316
    class LineSection : public Section {
317 317
    private:
318 318

	
319 319
      Functor _functor;
320 320

	
321 321
    public:
322 322

	
323 323
      LineSection(const Functor& functor) : _functor(functor) {}
324 324
      virtual ~LineSection() {}
325 325

	
326 326
      virtual void process(std::ostream& os) {
327 327
        std::string line;
328 328
        while (!(line = _functor()).empty()) os << line << std::endl;
329 329
      }
330 330
    };
331 331

	
332 332
    template <typename Functor>
333 333
    class StreamSection : public Section {
334 334
    private:
335 335

	
336 336
      Functor _functor;
337 337

	
338 338
    public:
339 339

	
340 340
      StreamSection(const Functor& functor) : _functor(functor) {}
341 341
      virtual ~StreamSection() {}
342 342

	
343 343
      virtual void process(std::ostream& os) {
344 344
        _functor(os);
345 345
      }
346 346
    };
347 347

	
348 348
  }
349 349

	
350 350
  template <typename Digraph>
351 351
  class DigraphWriter;
352 352

	
353 353
  template <typename Digraph>
354 354
  DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
355 355
                                       std::ostream& os = std::cout);
356 356
  template <typename Digraph>
357 357
  DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
358 358
                                       const std::string& fn);
359 359

	
360 360
  template <typename Digraph>
361 361
  DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
362 362
                                       const char* fn);
363 363

	
364 364

	
365 365
  /// \ingroup lemon_io
366 366
  ///
367 367
  /// \brief \ref lgf-format "LGF" writer for directed graphs
368 368
  ///
369 369
  /// This utility writes an \ref lgf-format "LGF" file.
370 370
  ///
371 371
  /// The writing method does a batch processing. The user creates a
372 372
  /// writer object, then various writing rules can be added to the
373 373
  /// writer, and eventually the writing is executed with the \c run()
374 374
  /// member function. A map writing rule can be added to the writer
375 375
  /// with the \c nodeMap() or \c arcMap() members. An optional
376 376
  /// converter parameter can also be added as a standard functor
377 377
  /// converting from the value type of the map to \c std::string. If it
378 378
  /// is set, it will determine how the value type of the map is written to
379 379
  /// the output stream. If the functor is not set, then a default
380 380
  /// conversion will be used. The \c attribute(), \c node() and \c
381 381
  /// arc() functions are used to add attribute writing rules.
382 382
  ///
383 383
  ///\code
384 384
  /// DigraphWriter<Digraph>(digraph, std::cout).
385 385
  ///   nodeMap("coordinates", coord_map).
386 386
  ///   nodeMap("size", size).
387 387
  ///   nodeMap("title", title).
388 388
  ///   arcMap("capacity", cap_map).
389 389
  ///   node("source", src).
390 390
  ///   node("target", trg).
391 391
  ///   attribute("caption", caption).
392 392
  ///   run();
393 393
  ///\endcode
394 394
  ///
395 395
  ///
396 396
  /// By default, the writer does not write additional captions to the
397 397
  /// sections, but they can be give as an optional parameter of
398 398
  /// the \c nodes(), \c arcs() or \c
399 399
  /// attributes() functions.
400 400
  ///
401 401
  /// The \c skipNodes() and \c skipArcs() functions forbid the
402 402
  /// writing of the sections. If two arc sections should be written
403 403
  /// to the output, it can be done in two passes, the first pass
404 404
  /// writes the node section and the first arc section, then the
405 405
  /// second pass skips the node section and writes just the arc
406 406
  /// section to the stream. The output stream can be retrieved with
407 407
  /// the \c ostream() function, hence the second pass can append its
408 408
  /// output to the output of the first pass.
409 409
  template <typename GR>
410 410
  class DigraphWriter {
411 411
  public:
412 412

	
413 413
    typedef GR Digraph;
414 414
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
415 415

	
416 416
  private:
417 417

	
418 418

	
419 419
    std::ostream* _os;
420 420
    bool local_os;
421 421

	
422 422
    const Digraph& _digraph;
423 423

	
424 424
    std::string _nodes_caption;
425 425
    std::string _arcs_caption;
426 426
    std::string _attributes_caption;
427 427

	
428 428
    typedef std::map<Node, std::string> NodeIndex;
429 429
    NodeIndex _node_index;
430 430
    typedef std::map<Arc, std::string> ArcIndex;
431 431
    ArcIndex _arc_index;
432 432

	
433 433
    typedef std::vector<std::pair<std::string,
434 434
      _writer_bits::MapStorageBase<Node>* > > NodeMaps;
435 435
    NodeMaps _node_maps;
436 436

	
437 437
    typedef std::vector<std::pair<std::string,
438 438
      _writer_bits::MapStorageBase<Arc>* > >ArcMaps;
439 439
    ArcMaps _arc_maps;
440 440

	
441 441
    typedef std::vector<std::pair<std::string,
442 442
      _writer_bits::ValueStorageBase*> > Attributes;
443 443
    Attributes _attributes;
444 444

	
445 445
    bool _skip_nodes;
446 446
    bool _skip_arcs;
447 447

	
448 448
  public:
449 449

	
450 450
    /// \brief Constructor
451 451
    ///
452 452
    /// Construct a directed graph writer, which writes to the given
453 453
    /// output stream.
454 454
    DigraphWriter(const Digraph& digraph, std::ostream& os = std::cout)
455 455
      : _os(&os), local_os(false), _digraph(digraph),
456 456
        _skip_nodes(false), _skip_arcs(false) {}
457 457

	
458 458
    /// \brief Constructor
459 459
    ///
460 460
    /// Construct a directed graph writer, which writes to the given
461 461
    /// output file.
462 462
    DigraphWriter(const Digraph& digraph, const std::string& fn)
463 463
      : _os(new std::ofstream(fn.c_str())), local_os(true), _digraph(digraph),
464 464
        _skip_nodes(false), _skip_arcs(false) {
465 465
      if (!(*_os)) {
466 466
        delete _os;
467 467
        throw IoError("Cannot write file", fn);
468 468
      }
469 469
    }
470 470

	
471 471
    /// \brief Constructor
472 472
    ///
473 473
    /// Construct a directed graph writer, which writes to the given
474 474
    /// output file.
475 475
    DigraphWriter(const Digraph& digraph, const char* fn)
476 476
      : _os(new std::ofstream(fn)), local_os(true), _digraph(digraph),
477 477
        _skip_nodes(false), _skip_arcs(false) {
478 478
      if (!(*_os)) {
479 479
        delete _os;
480 480
        throw IoError("Cannot write file", fn);
481 481
      }
482 482
    }
483 483

	
484 484
    /// \brief Destructor
485 485
    ~DigraphWriter() {
486 486
      for (typename NodeMaps::iterator it = _node_maps.begin();
487 487
           it != _node_maps.end(); ++it) {
488 488
        delete it->second;
489 489
      }
490 490

	
491 491
      for (typename ArcMaps::iterator it = _arc_maps.begin();
492 492
           it != _arc_maps.end(); ++it) {
493 493
        delete it->second;
494 494
      }
495 495

	
496 496
      for (typename Attributes::iterator it = _attributes.begin();
497 497
           it != _attributes.end(); ++it) {
498 498
        delete it->second;
499 499
      }
500 500

	
501 501
      if (local_os) {
502 502
        delete _os;
503 503
      }
504 504
    }
505 505

	
506 506
  private:
507 507

	
508 508
    template <typename DGR>
509 509
    friend DigraphWriter<DGR> digraphWriter(const DGR& digraph, 
510 510
                                            std::ostream& os);
511 511
    template <typename DGR>
512 512
    friend DigraphWriter<DGR> digraphWriter(const DGR& digraph,
513 513
                                            const std::string& fn);
514 514
    template <typename DGR>
515 515
    friend DigraphWriter<DGR> digraphWriter(const DGR& digraph,
516 516
                                            const char *fn);
517 517

	
518 518
    DigraphWriter(DigraphWriter& other)
519 519
      : _os(other._os), local_os(other.local_os), _digraph(other._digraph),
520 520
        _skip_nodes(other._skip_nodes), _skip_arcs(other._skip_arcs) {
521 521

	
522 522
      other._os = 0;
523 523
      other.local_os = false;
524 524

	
525 525
      _node_index.swap(other._node_index);
526 526
      _arc_index.swap(other._arc_index);
527 527

	
528 528
      _node_maps.swap(other._node_maps);
529 529
      _arc_maps.swap(other._arc_maps);
530 530
      _attributes.swap(other._attributes);
531 531

	
532 532
      _nodes_caption = other._nodes_caption;
533 533
      _arcs_caption = other._arcs_caption;
534 534
      _attributes_caption = other._attributes_caption;
535 535
    }
536 536

	
537 537
    DigraphWriter& operator=(const DigraphWriter&);
538 538

	
539 539
  public:
540 540

	
541
    /// \name Writing rules
541
    /// \name Writing Rules
542 542
    /// @{
543 543

	
544 544
    /// \brief Node map writing rule
545 545
    ///
546 546
    /// Add a node map writing rule to the writer.
547 547
    template <typename Map>
548 548
    DigraphWriter& nodeMap(const std::string& caption, const Map& map) {
549 549
      checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
550 550
      _writer_bits::MapStorageBase<Node>* storage =
551 551
        new _writer_bits::MapStorage<Node, Map>(map);
552 552
      _node_maps.push_back(std::make_pair(caption, storage));
553 553
      return *this;
554 554
    }
555 555

	
556 556
    /// \brief Node map writing rule
557 557
    ///
558 558
    /// Add a node map writing rule with specialized converter to the
559 559
    /// writer.
560 560
    template <typename Map, typename Converter>
561 561
    DigraphWriter& nodeMap(const std::string& caption, const Map& map,
562 562
                           const Converter& converter = Converter()) {
563 563
      checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
564 564
      _writer_bits::MapStorageBase<Node>* storage =
565 565
        new _writer_bits::MapStorage<Node, Map, Converter>(map, converter);
566 566
      _node_maps.push_back(std::make_pair(caption, storage));
567 567
      return *this;
568 568
    }
569 569

	
570 570
    /// \brief Arc map writing rule
571 571
    ///
572 572
    /// Add an arc map writing rule to the writer.
573 573
    template <typename Map>
574 574
    DigraphWriter& arcMap(const std::string& caption, const Map& map) {
575 575
      checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
576 576
      _writer_bits::MapStorageBase<Arc>* storage =
577 577
        new _writer_bits::MapStorage<Arc, Map>(map);
578 578
      _arc_maps.push_back(std::make_pair(caption, storage));
579 579
      return *this;
580 580
    }
581 581

	
582 582
    /// \brief Arc map writing rule
583 583
    ///
584 584
    /// Add an arc map writing rule with specialized converter to the
585 585
    /// writer.
586 586
    template <typename Map, typename Converter>
587 587
    DigraphWriter& arcMap(const std::string& caption, const Map& map,
588 588
                          const Converter& converter = Converter()) {
589 589
      checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
590 590
      _writer_bits::MapStorageBase<Arc>* storage =
591 591
        new _writer_bits::MapStorage<Arc, Map, Converter>(map, converter);
592 592
      _arc_maps.push_back(std::make_pair(caption, storage));
593 593
      return *this;
594 594
    }
595 595

	
596 596
    /// \brief Attribute writing rule
597 597
    ///
598 598
    /// Add an attribute writing rule to the writer.
599 599
    template <typename Value>
600 600
    DigraphWriter& attribute(const std::string& caption, const Value& value) {
601 601
      _writer_bits::ValueStorageBase* storage =
602 602
        new _writer_bits::ValueStorage<Value>(value);
603 603
      _attributes.push_back(std::make_pair(caption, storage));
604 604
      return *this;
605 605
    }
606 606

	
607 607
    /// \brief Attribute writing rule
608 608
    ///
609 609
    /// Add an attribute writing rule with specialized converter to the
610 610
    /// writer.
611 611
    template <typename Value, typename Converter>
612 612
    DigraphWriter& attribute(const std::string& caption, const Value& value,
613 613
                             const Converter& converter = Converter()) {
614 614
      _writer_bits::ValueStorageBase* storage =
615 615
        new _writer_bits::ValueStorage<Value, Converter>(value, converter);
616 616
      _attributes.push_back(std::make_pair(caption, storage));
617 617
      return *this;
618 618
    }
619 619

	
620 620
    /// \brief Node writing rule
621 621
    ///
622 622
    /// Add a node writing rule to the writer.
623 623
    DigraphWriter& node(const std::string& caption, const Node& node) {
624 624
      typedef _writer_bits::MapLookUpConverter<Node> Converter;
625 625
      Converter converter(_node_index);
626 626
      _writer_bits::ValueStorageBase* storage =
627 627
        new _writer_bits::ValueStorage<Node, Converter>(node, converter);
628 628
      _attributes.push_back(std::make_pair(caption, storage));
629 629
      return *this;
630 630
    }
631 631

	
632 632
    /// \brief Arc writing rule
633 633
    ///
634 634
    /// Add an arc writing rule to writer.
635 635
    DigraphWriter& arc(const std::string& caption, const Arc& arc) {
636 636
      typedef _writer_bits::MapLookUpConverter<Arc> Converter;
637 637
      Converter converter(_arc_index);
638 638
      _writer_bits::ValueStorageBase* storage =
639 639
        new _writer_bits::ValueStorage<Arc, Converter>(arc, converter);
640 640
      _attributes.push_back(std::make_pair(caption, storage));
641 641
      return *this;
642 642
    }
643 643

	
644
    /// \name Section captions
644
    /// \name Section Captions
645 645
    /// @{
646 646

	
647 647
    /// \brief Add an additional caption to the \c \@nodes section
648 648
    ///
649 649
    /// Add an additional caption to the \c \@nodes section.
650 650
    DigraphWriter& nodes(const std::string& caption) {
651 651
      _nodes_caption = caption;
652 652
      return *this;
653 653
    }
654 654

	
655 655
    /// \brief Add an additional caption to the \c \@arcs section
656 656
    ///
657 657
    /// Add an additional caption to the \c \@arcs section.
658 658
    DigraphWriter& arcs(const std::string& caption) {
659 659
      _arcs_caption = caption;
660 660
      return *this;
661 661
    }
662 662

	
663 663
    /// \brief Add an additional caption to the \c \@attributes section
664 664
    ///
665 665
    /// Add an additional caption to the \c \@attributes section.
666 666
    DigraphWriter& attributes(const std::string& caption) {
667 667
      _attributes_caption = caption;
668 668
      return *this;
669 669
    }
670 670

	
671
    /// \name Skipping section
671
    /// \name Skipping Section
672 672
    /// @{
673 673

	
674 674
    /// \brief Skip writing the node set
675 675
    ///
676 676
    /// The \c \@nodes section will not be written to the stream.
677 677
    DigraphWriter& skipNodes() {
678 678
      LEMON_ASSERT(!_skip_nodes, "Multiple usage of skipNodes() member");
679 679
      _skip_nodes = true;
680 680
      return *this;
681 681
    }
682 682

	
683 683
    /// \brief Skip writing arc set
684 684
    ///
685 685
    /// The \c \@arcs section will not be written to the stream.
686 686
    DigraphWriter& skipArcs() {
687 687
      LEMON_ASSERT(!_skip_arcs, "Multiple usage of skipArcs() member");
688 688
      _skip_arcs = true;
689 689
      return *this;
690 690
    }
691 691

	
692 692
    /// @}
693 693

	
694 694
  private:
695 695

	
696 696
    void writeNodes() {
697 697
      _writer_bits::MapStorageBase<Node>* label = 0;
698 698
      for (typename NodeMaps::iterator it = _node_maps.begin();
699 699
           it != _node_maps.end(); ++it) {
700 700
        if (it->first == "label") {
701 701
          label = it->second;
702 702
          break;
703 703
        }
704 704
      }
705 705

	
706 706
      *_os << "@nodes";
707 707
      if (!_nodes_caption.empty()) {
708 708
        _writer_bits::writeToken(*_os << ' ', _nodes_caption);
709 709
      }
710 710
      *_os << std::endl;
711 711

	
712 712
      if (label == 0) {
713 713
        *_os << "label" << '\t';
714 714
      }
715 715
      for (typename NodeMaps::iterator it = _node_maps.begin();
716 716
           it != _node_maps.end(); ++it) {
717 717
        _writer_bits::writeToken(*_os, it->first) << '\t';
718 718
      }
719 719
      *_os << std::endl;
720 720

	
721 721
      std::vector<Node> nodes;
722 722
      for (NodeIt n(_digraph); n != INVALID; ++n) {
723 723
        nodes.push_back(n);
724 724
      }
725 725

	
726 726
      if (label == 0) {
727 727
        IdMap<Digraph, Node> id_map(_digraph);
728 728
        _writer_bits::MapLess<IdMap<Digraph, Node> > id_less(id_map);
729 729
        std::sort(nodes.begin(), nodes.end(), id_less);
730 730
      } else {
731 731
        label->sort(nodes);
732 732
      }
733 733

	
734 734
      for (int i = 0; i < static_cast<int>(nodes.size()); ++i) {
735 735
        Node n = nodes[i];
736 736
        if (label == 0) {
737 737
          std::ostringstream os;
738 738
          os << _digraph.id(n);
739 739
          _writer_bits::writeToken(*_os, os.str());
740 740
          *_os << '\t';
741 741
          _node_index.insert(std::make_pair(n, os.str()));
742 742
        }
743 743
        for (typename NodeMaps::iterator it = _node_maps.begin();
744 744
             it != _node_maps.end(); ++it) {
745 745
          std::string value = it->second->get(n);
746 746
          _writer_bits::writeToken(*_os, value);
747 747
          if (it->first == "label") {
748 748
            _node_index.insert(std::make_pair(n, value));
749 749
          }
750 750
          *_os << '\t';
751 751
        }
752 752
        *_os << std::endl;
753 753
      }
754 754
    }
755 755

	
756 756
    void createNodeIndex() {
757 757
      _writer_bits::MapStorageBase<Node>* label = 0;
758 758
      for (typename NodeMaps::iterator it = _node_maps.begin();
759 759
           it != _node_maps.end(); ++it) {
760 760
        if (it->first == "label") {
761 761
          label = it->second;
762 762
          break;
763 763
        }
764 764
      }
765 765

	
766 766
      if (label == 0) {
767 767
        for (NodeIt n(_digraph); n != INVALID; ++n) {
768 768
          std::ostringstream os;
769 769
          os << _digraph.id(n);
770 770
          _node_index.insert(std::make_pair(n, os.str()));
771 771
        }
772 772
      } else {
773 773
        for (NodeIt n(_digraph); n != INVALID; ++n) {
774 774
          std::string value = label->get(n);
775 775
          _node_index.insert(std::make_pair(n, value));
776 776
        }
777 777
      }
778 778
    }
779 779

	
780 780
    void writeArcs() {
781 781
      _writer_bits::MapStorageBase<Arc>* label = 0;
782 782
      for (typename ArcMaps::iterator it = _arc_maps.begin();
783 783
           it != _arc_maps.end(); ++it) {
784 784
        if (it->first == "label") {
785 785
          label = it->second;
786 786
          break;
787 787
        }
788 788
      }
789 789

	
790 790
      *_os << "@arcs";
791 791
      if (!_arcs_caption.empty()) {
792 792
        _writer_bits::writeToken(*_os << ' ', _arcs_caption);
793 793
      }
794 794
      *_os << std::endl;
795 795

	
796 796
      *_os << '\t' << '\t';
797 797
      if (label == 0) {
798 798
        *_os << "label" << '\t';
799 799
      }
800 800
      for (typename ArcMaps::iterator it = _arc_maps.begin();
801 801
           it != _arc_maps.end(); ++it) {
802 802
        _writer_bits::writeToken(*_os, it->first) << '\t';
803 803
      }
804 804
      *_os << std::endl;
805 805

	
806 806
      std::vector<Arc> arcs;
807 807
      for (ArcIt n(_digraph); n != INVALID; ++n) {
808 808
        arcs.push_back(n);
809 809
      }
810 810

	
811 811
      if (label == 0) {
812 812
        IdMap<Digraph, Arc> id_map(_digraph);
813 813
        _writer_bits::MapLess<IdMap<Digraph, Arc> > id_less(id_map);
814 814
        std::sort(arcs.begin(), arcs.end(), id_less);
815 815
      } else {
816 816
        label->sort(arcs);
817 817
      }
818 818

	
819 819
      for (int i = 0; i < static_cast<int>(arcs.size()); ++i) {
820 820
        Arc a = arcs[i];
821 821
        _writer_bits::writeToken(*_os, _node_index.
822 822
                                 find(_digraph.source(a))->second);
823 823
        *_os << '\t';
824 824
        _writer_bits::writeToken(*_os, _node_index.
825 825
                                 find(_digraph.target(a))->second);
826 826
        *_os << '\t';
827 827
        if (label == 0) {
828 828
          std::ostringstream os;
829 829
          os << _digraph.id(a);
830 830
          _writer_bits::writeToken(*_os, os.str());
831 831
          *_os << '\t';
832 832
          _arc_index.insert(std::make_pair(a, os.str()));
833 833
        }
834 834
        for (typename ArcMaps::iterator it = _arc_maps.begin();
835 835
             it != _arc_maps.end(); ++it) {
836 836
          std::string value = it->second->get(a);
837 837
          _writer_bits::writeToken(*_os, value);
838 838
          if (it->first == "label") {
839 839
            _arc_index.insert(std::make_pair(a, value));
840 840
          }
841 841
          *_os << '\t';
842 842
        }
843 843
        *_os << std::endl;
844 844
      }
845 845
    }
846 846

	
847 847
    void createArcIndex() {
848 848
      _writer_bits::MapStorageBase<Arc>* label = 0;
849 849
      for (typename ArcMaps::iterator it = _arc_maps.begin();
850 850
           it != _arc_maps.end(); ++it) {
851 851
        if (it->first == "label") {
852 852
          label = it->second;
853 853
          break;
854 854
        }
855 855
      }
856 856

	
857 857
      if (label == 0) {
858 858
        for (ArcIt a(_digraph); a != INVALID; ++a) {
859 859
          std::ostringstream os;
860 860
          os << _digraph.id(a);
861 861
          _arc_index.insert(std::make_pair(a, os.str()));
862 862
        }
863 863
      } else {
864 864
        for (ArcIt a(_digraph); a != INVALID; ++a) {
865 865
          std::string value = label->get(a);
866 866
          _arc_index.insert(std::make_pair(a, value));
867 867
        }
868 868
      }
869 869
    }
870 870

	
871 871
    void writeAttributes() {
872 872
      if (_attributes.empty()) return;
873 873
      *_os << "@attributes";
874 874
      if (!_attributes_caption.empty()) {
875 875
        _writer_bits::writeToken(*_os << ' ', _attributes_caption);
876 876
      }
877 877
      *_os << std::endl;
878 878
      for (typename Attributes::iterator it = _attributes.begin();
879 879
           it != _attributes.end(); ++it) {
880 880
        _writer_bits::writeToken(*_os, it->first) << ' ';
881 881
        _writer_bits::writeToken(*_os, it->second->get());
882 882
        *_os << std::endl;
883 883
      }
884 884
    }
885 885

	
886 886
  public:
887 887

	
888
    /// \name Execution of the writer
888
    /// \name Execution of the Writer
889 889
    /// @{
890 890

	
891 891
    /// \brief Start the batch processing
892 892
    ///
893 893
    /// This function starts the batch processing.
894 894
    void run() {
895 895
      if (!_skip_nodes) {
896 896
        writeNodes();
897 897
      } else {
898 898
        createNodeIndex();
899 899
      }
900 900
      if (!_skip_arcs) {
901 901
        writeArcs();
902 902
      } else {
903 903
        createArcIndex();
904 904
      }
905 905
      writeAttributes();
906 906
    }
907 907

	
908 908
    /// \brief Give back the stream of the writer
909 909
    ///
910 910
    /// Give back the stream of the writer.
911 911
    std::ostream& ostream() {
912 912
      return *_os;
913 913
    }
914 914

	
915 915
    /// @}
916 916
  };
917 917

	
918 918
  /// \brief Return a \ref DigraphWriter class
919 919
  ///
920 920
  /// This function just returns a \ref DigraphWriter class.
921 921
  /// \relates DigraphWriter
922 922
  template <typename Digraph>
923 923
  DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
924 924
                                       std::ostream& os) {
925 925
    DigraphWriter<Digraph> tmp(digraph, os);
926 926
    return tmp;
927 927
  }
928 928

	
929 929
  /// \brief Return a \ref DigraphWriter class
930 930
  ///
931 931
  /// This function just returns a \ref DigraphWriter class.
932 932
  /// \relates DigraphWriter
933 933
  template <typename Digraph>
934 934
  DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
935 935
                                       const std::string& fn) {
936 936
    DigraphWriter<Digraph> tmp(digraph, fn);
937 937
    return tmp;
938 938
  }
939 939

	
940 940
  /// \brief Return a \ref DigraphWriter class
941 941
  ///
942 942
  /// This function just returns a \ref DigraphWriter class.
943 943
  /// \relates DigraphWriter
944 944
  template <typename Digraph>
945 945
  DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
946 946
                                       const char* fn) {
947 947
    DigraphWriter<Digraph> tmp(digraph, fn);
948 948
    return tmp;
949 949
  }
950 950

	
951 951
  template <typename Graph>
952 952
  class GraphWriter;
953 953

	
954 954
  template <typename Graph>
955 955
  GraphWriter<Graph> graphWriter(const Graph& graph,
956 956
                                 std::ostream& os = std::cout);
957 957
  template <typename Graph>
958 958
  GraphWriter<Graph> graphWriter(const Graph& graph, const std::string& fn);
959 959
  template <typename Graph>
960 960
  GraphWriter<Graph> graphWriter(const Graph& graph, const char* fn);
961 961

	
962 962
  /// \ingroup lemon_io
963 963
  ///
964 964
  /// \brief \ref lgf-format "LGF" writer for directed graphs
965 965
  ///
966 966
  /// This utility writes an \ref lgf-format "LGF" file.
967 967
  ///
968 968
  /// It can be used almost the same way as \c DigraphWriter.
969 969
  /// The only difference is that this class can handle edges and
970 970
  /// edge maps as well as arcs and arc maps.
971 971
  ///
972 972
  /// The arc maps are written into the file as two columns, the
973 973
  /// caption of the columns are the name of the map prefixed with \c
974 974
  /// '+' and \c '-'. The arcs are written into the \c \@attributes
975 975
  /// section as a \c '+' or a \c '-' prefix (depends on the direction
976 976
  /// of the arc) and the label of corresponding edge.
977 977
  template <typename GR>
978 978
  class GraphWriter {
979 979
  public:
980 980

	
981 981
    typedef GR Graph;
982 982
    TEMPLATE_GRAPH_TYPEDEFS(Graph);
983 983

	
984 984
  private:
985 985

	
986 986

	
987 987
    std::ostream* _os;
988 988
    bool local_os;
989 989

	
990 990
    const Graph& _graph;
991 991

	
992 992
    std::string _nodes_caption;
993 993
    std::string _edges_caption;
994 994
    std::string _attributes_caption;
995 995

	
996 996
    typedef std::map<Node, std::string> NodeIndex;
997 997
    NodeIndex _node_index;
998 998
    typedef std::map<Edge, std::string> EdgeIndex;
999 999
    EdgeIndex _edge_index;
1000 1000

	
1001 1001
    typedef std::vector<std::pair<std::string,
1002 1002
      _writer_bits::MapStorageBase<Node>* > > NodeMaps;
1003 1003
    NodeMaps _node_maps;
1004 1004

	
1005 1005
    typedef std::vector<std::pair<std::string,
1006 1006
      _writer_bits::MapStorageBase<Edge>* > >EdgeMaps;
1007 1007
    EdgeMaps _edge_maps;
1008 1008

	
1009 1009
    typedef std::vector<std::pair<std::string,
1010 1010
      _writer_bits::ValueStorageBase*> > Attributes;
1011 1011
    Attributes _attributes;
1012 1012

	
1013 1013
    bool _skip_nodes;
1014 1014
    bool _skip_edges;
1015 1015

	
1016 1016
  public:
1017 1017

	
1018 1018
    /// \brief Constructor
1019 1019
    ///
1020 1020
    /// Construct a directed graph writer, which writes to the given
1021 1021
    /// output stream.
1022 1022
    GraphWriter(const Graph& graph, std::ostream& os = std::cout)
1023 1023
      : _os(&os), local_os(false), _graph(graph),
1024 1024
        _skip_nodes(false), _skip_edges(false) {}
1025 1025

	
1026 1026
    /// \brief Constructor
1027 1027
    ///
1028 1028
    /// Construct a directed graph writer, which writes to the given
1029 1029
    /// output file.
1030 1030
    GraphWriter(const Graph& graph, const std::string& fn)
1031 1031
      : _os(new std::ofstream(fn.c_str())), local_os(true), _graph(graph),
1032 1032
        _skip_nodes(false), _skip_edges(false) {
1033 1033
      if (!(*_os)) {
1034 1034
        delete _os;
1035 1035
        throw IoError("Cannot write file", fn);
1036 1036
      }
1037 1037
    }
1038 1038

	
1039 1039
    /// \brief Constructor
1040 1040
    ///
1041 1041
    /// Construct a directed graph writer, which writes to the given
1042 1042
    /// output file.
1043 1043
    GraphWriter(const Graph& graph, const char* fn)
1044 1044
      : _os(new std::ofstream(fn)), local_os(true), _graph(graph),
1045 1045
        _skip_nodes(false), _skip_edges(false) {
1046 1046
      if (!(*_os)) {
1047 1047
        delete _os;
1048 1048
        throw IoError("Cannot write file", fn);
1049 1049
      }
1050 1050
    }
1051 1051

	
1052 1052
    /// \brief Destructor
1053 1053
    ~GraphWriter() {
1054 1054
      for (typename NodeMaps::iterator it = _node_maps.begin();
1055 1055
           it != _node_maps.end(); ++it) {
1056 1056
        delete it->second;
1057 1057
      }
1058 1058

	
1059 1059
      for (typename EdgeMaps::iterator it = _edge_maps.begin();
1060 1060
           it != _edge_maps.end(); ++it) {
1061 1061
        delete it->second;
1062 1062
      }
1063 1063

	
1064 1064
      for (typename Attributes::iterator it = _attributes.begin();
1065 1065
           it != _attributes.end(); ++it) {
1066 1066
        delete it->second;
1067 1067
      }
1068 1068

	
1069 1069
      if (local_os) {
1070 1070
        delete _os;
1071 1071
      }
1072 1072
    }
1073 1073

	
1074 1074
  private:
1075 1075

	
1076 1076
    template <typename Graph>
1077 1077
    friend GraphWriter<Graph> graphWriter(const Graph& graph,
1078 1078
                                          std::ostream& os);
1079 1079
    template <typename Graph>
1080 1080
    friend GraphWriter<Graph> graphWriter(const Graph& graph,
1081 1081
                                          const std::string& fn);
1082 1082
    template <typename Graph>
1083 1083
    friend GraphWriter<Graph> graphWriter(const Graph& graph,
1084 1084
                                          const char *fn);
1085 1085
    
1086 1086
    GraphWriter(GraphWriter& other)
1087 1087
      : _os(other._os), local_os(other.local_os), _graph(other._graph),
1088 1088
        _skip_nodes(other._skip_nodes), _skip_edges(other._skip_edges) {
1089 1089

	
1090 1090
      other._os = 0;
1091 1091
      other.local_os = false;
1092 1092

	
1093 1093
      _node_index.swap(other._node_index);
1094 1094
      _edge_index.swap(other._edge_index);
1095 1095

	
1096 1096
      _node_maps.swap(other._node_maps);
1097 1097
      _edge_maps.swap(other._edge_maps);
1098 1098
      _attributes.swap(other._attributes);
1099 1099

	
1100 1100
      _nodes_caption = other._nodes_caption;
1101 1101
      _edges_caption = other._edges_caption;
1102 1102
      _attributes_caption = other._attributes_caption;
1103 1103
    }
1104 1104

	
1105 1105
    GraphWriter& operator=(const GraphWriter&);
1106 1106

	
1107 1107
  public:
1108 1108

	
1109
    /// \name Writing rules
1109
    /// \name Writing Rules
1110 1110
    /// @{
1111 1111

	
1112 1112
    /// \brief Node map writing rule
1113 1113
    ///
1114 1114
    /// Add a node map writing rule to the writer.
1115 1115
    template <typename Map>
1116 1116
    GraphWriter& nodeMap(const std::string& caption, const Map& map) {
1117 1117
      checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
1118 1118
      _writer_bits::MapStorageBase<Node>* storage =
1119 1119
        new _writer_bits::MapStorage<Node, Map>(map);
1120 1120
      _node_maps.push_back(std::make_pair(caption, storage));
1121 1121
      return *this;
1122 1122
    }
1123 1123

	
1124 1124
    /// \brief Node map writing rule
1125 1125
    ///
1126 1126
    /// Add a node map writing rule with specialized converter to the
1127 1127
    /// writer.
1128 1128
    template <typename Map, typename Converter>
1129 1129
    GraphWriter& nodeMap(const std::string& caption, const Map& map,
1130 1130
                           const Converter& converter = Converter()) {
1131 1131
      checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
1132 1132
      _writer_bits::MapStorageBase<Node>* storage =
1133 1133
        new _writer_bits::MapStorage<Node, Map, Converter>(map, converter);
1134 1134
      _node_maps.push_back(std::make_pair(caption, storage));
1135 1135
      return *this;
1136 1136
    }
1137 1137

	
1138 1138
    /// \brief Edge map writing rule
1139 1139
    ///
1140 1140
    /// Add an edge map writing rule to the writer.
1141 1141
    template <typename Map>
1142 1142
    GraphWriter& edgeMap(const std::string& caption, const Map& map) {
1143 1143
      checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
1144 1144
      _writer_bits::MapStorageBase<Edge>* storage =
1145 1145
        new _writer_bits::MapStorage<Edge, Map>(map);
1146 1146
      _edge_maps.push_back(std::make_pair(caption, storage));
1147 1147
      return *this;
1148 1148
    }
1149 1149

	
1150 1150
    /// \brief Edge map writing rule
1151 1151
    ///
1152 1152
    /// Add an edge map writing rule with specialized converter to the
1153 1153
    /// writer.
1154 1154
    template <typename Map, typename Converter>
1155 1155
    GraphWriter& edgeMap(const std::string& caption, const Map& map,
1156 1156
                          const Converter& converter = Converter()) {
1157 1157
      checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
1158 1158
      _writer_bits::MapStorageBase<Edge>* storage =
1159 1159
        new _writer_bits::MapStorage<Edge, Map, Converter>(map, converter);
1160 1160
      _edge_maps.push_back(std::make_pair(caption, storage));
1161 1161
      return *this;
1162 1162
    }
1163 1163

	
1164 1164
    /// \brief Arc map writing rule
1165 1165
    ///
1166 1166
    /// Add an arc map writing rule to the writer.
1167 1167
    template <typename Map>
1168 1168
    GraphWriter& arcMap(const std::string& caption, const Map& map) {
1169 1169
      checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
1170 1170
      _writer_bits::MapStorageBase<Edge>* forward_storage =
1171 1171
        new _writer_bits::GraphArcMapStorage<Graph, true, Map>(_graph, map);
1172 1172
      _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
1173 1173
      _writer_bits::MapStorageBase<Edge>* backward_storage =
1174 1174
        new _writer_bits::GraphArcMapStorage<Graph, false, Map>(_graph, map);
1175 1175
      _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
1176 1176
      return *this;
1177 1177
    }
1178 1178

	
1179 1179
    /// \brief Arc map writing rule
1180 1180
    ///
1181 1181
    /// Add an arc map writing rule with specialized converter to the
1182 1182
    /// writer.
1183 1183
    template <typename Map, typename Converter>
1184 1184
    GraphWriter& arcMap(const std::string& caption, const Map& map,
1185 1185
                          const Converter& converter = Converter()) {
1186 1186
      checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
1187 1187
      _writer_bits::MapStorageBase<Edge>* forward_storage =
1188 1188
        new _writer_bits::GraphArcMapStorage<Graph, true, Map, Converter>
1189 1189
        (_graph, map, converter);
1190 1190
      _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
1191 1191
      _writer_bits::MapStorageBase<Edge>* backward_storage =
1192 1192
        new _writer_bits::GraphArcMapStorage<Graph, false, Map, Converter>
1193 1193
        (_graph, map, converter);
1194 1194
      _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
1195 1195
      return *this;
1196 1196
    }
1197 1197

	
1198 1198
    /// \brief Attribute writing rule
1199 1199
    ///
1200 1200
    /// Add an attribute writing rule to the writer.
1201 1201
    template <typename Value>
1202 1202
    GraphWriter& attribute(const std::string& caption, const Value& value) {
1203 1203
      _writer_bits::ValueStorageBase* storage =
1204 1204
        new _writer_bits::ValueStorage<Value>(value);
1205 1205
      _attributes.push_back(std::make_pair(caption, storage));
1206 1206
      return *this;
1207 1207
    }
1208 1208

	
1209 1209
    /// \brief Attribute writing rule
1210 1210
    ///
1211 1211
    /// Add an attribute writing rule with specialized converter to the
1212 1212
    /// writer.
1213 1213
    template <typename Value, typename Converter>
1214 1214
    GraphWriter& attribute(const std::string& caption, const Value& value,
1215 1215
                             const Converter& converter = Converter()) {
1216 1216
      _writer_bits::ValueStorageBase* storage =
1217 1217
        new _writer_bits::ValueStorage<Value, Converter>(value, converter);
1218 1218
      _attributes.push_back(std::make_pair(caption, storage));
1219 1219
      return *this;
1220 1220
    }
1221 1221

	
1222 1222
    /// \brief Node writing rule
1223 1223
    ///
1224 1224
    /// Add a node writing rule to the writer.
1225 1225
    GraphWriter& node(const std::string& caption, const Node& node) {
1226 1226
      typedef _writer_bits::MapLookUpConverter<Node> Converter;
1227 1227
      Converter converter(_node_index);
1228 1228
      _writer_bits::ValueStorageBase* storage =
1229 1229
        new _writer_bits::ValueStorage<Node, Converter>(node, converter);
1230 1230
      _attributes.push_back(std::make_pair(caption, storage));
1231 1231
      return *this;
1232 1232
    }
1233 1233

	
1234 1234
    /// \brief Edge writing rule
1235 1235
    ///
1236 1236
    /// Add an edge writing rule to writer.
1237 1237
    GraphWriter& edge(const std::string& caption, const Edge& edge) {
1238 1238
      typedef _writer_bits::MapLookUpConverter<Edge> Converter;
1239 1239
      Converter converter(_edge_index);
1240 1240
      _writer_bits::ValueStorageBase* storage =
1241 1241
        new _writer_bits::ValueStorage<Edge, Converter>(edge, converter);
1242 1242
      _attributes.push_back(std::make_pair(caption, storage));
1243 1243
      return *this;
1244 1244
    }
1245 1245

	
1246 1246
    /// \brief Arc writing rule
1247 1247
    ///
1248 1248
    /// Add an arc writing rule to writer.
1249 1249
    GraphWriter& arc(const std::string& caption, const Arc& arc) {
1250 1250
      typedef _writer_bits::GraphArcLookUpConverter<Graph> Converter;
1251 1251
      Converter converter(_graph, _edge_index);
1252 1252
      _writer_bits::ValueStorageBase* storage =
1253 1253
        new _writer_bits::ValueStorage<Arc, Converter>(arc, converter);
1254 1254
      _attributes.push_back(std::make_pair(caption, storage));
1255 1255
      return *this;
1256 1256
    }
1257 1257

	
1258
    /// \name Section captions
1258
    /// \name Section Captions
1259 1259
    /// @{
1260 1260

	
1261 1261
    /// \brief Add an additional caption to the \c \@nodes section
1262 1262
    ///
1263 1263
    /// Add an additional caption to the \c \@nodes section.
1264 1264
    GraphWriter& nodes(const std::string& caption) {
1265 1265
      _nodes_caption = caption;
1266 1266
      return *this;
1267 1267
    }
1268 1268

	
1269 1269
    /// \brief Add an additional caption to the \c \@arcs section
1270 1270
    ///
1271 1271
    /// Add an additional caption to the \c \@arcs section.
1272 1272
    GraphWriter& edges(const std::string& caption) {
1273 1273
      _edges_caption = caption;
1274 1274
      return *this;
1275 1275
    }
1276 1276

	
1277 1277
    /// \brief Add an additional caption to the \c \@attributes section
1278 1278
    ///
1279 1279
    /// Add an additional caption to the \c \@attributes section.
1280 1280
    GraphWriter& attributes(const std::string& caption) {
1281 1281
      _attributes_caption = caption;
1282 1282
      return *this;
1283 1283
    }
1284 1284

	
1285
    /// \name Skipping section
1285
    /// \name Skipping Section
1286 1286
    /// @{
1287 1287

	
1288 1288
    /// \brief Skip writing the node set
1289 1289
    ///
1290 1290
    /// The \c \@nodes section will not be written to the stream.
1291 1291
    GraphWriter& skipNodes() {
1292 1292
      LEMON_ASSERT(!_skip_nodes, "Multiple usage of skipNodes() member");
1293 1293
      _skip_nodes = true;
1294 1294
      return *this;
1295 1295
    }
1296 1296

	
1297 1297
    /// \brief Skip writing edge set
1298 1298
    ///
1299 1299
    /// The \c \@edges section will not be written to the stream.
1300 1300
    GraphWriter& skipEdges() {
1301 1301
      LEMON_ASSERT(!_skip_edges, "Multiple usage of skipEdges() member");
1302 1302
      _skip_edges = true;
1303 1303
      return *this;
1304 1304
    }
1305 1305

	
1306 1306
    /// @}
1307 1307

	
1308 1308
  private:
1309 1309

	
1310 1310
    void writeNodes() {
1311 1311
      _writer_bits::MapStorageBase<Node>* label = 0;
1312 1312
      for (typename NodeMaps::iterator it = _node_maps.begin();
1313 1313
           it != _node_maps.end(); ++it) {
1314 1314
        if (it->first == "label") {
1315 1315
          label = it->second;
1316 1316
          break;
1317 1317
        }
1318 1318
      }
1319 1319

	
1320 1320
      *_os << "@nodes";
1321 1321
      if (!_nodes_caption.empty()) {
1322 1322
        _writer_bits::writeToken(*_os << ' ', _nodes_caption);
1323 1323
      }
1324 1324
      *_os << std::endl;
1325 1325

	
1326 1326
      if (label == 0) {
1327 1327
        *_os << "label" << '\t';
1328 1328
      }
1329 1329
      for (typename NodeMaps::iterator it = _node_maps.begin();
1330 1330
           it != _node_maps.end(); ++it) {
1331 1331
        _writer_bits::writeToken(*_os, it->first) << '\t';
1332 1332
      }
1333 1333
      *_os << std::endl;
1334 1334

	
1335 1335
      std::vector<Node> nodes;
1336 1336
      for (NodeIt n(_graph); n != INVALID; ++n) {
1337 1337
        nodes.push_back(n);
1338 1338
      }
1339 1339

	
1340 1340
      if (label == 0) {
1341 1341
        IdMap<Graph, Node> id_map(_graph);
1342 1342
        _writer_bits::MapLess<IdMap<Graph, Node> > id_less(id_map);
1343 1343
        std::sort(nodes.begin(), nodes.end(), id_less);
1344 1344
      } else {
1345 1345
        label->sort(nodes);
1346 1346
      }
1347 1347

	
1348 1348
      for (int i = 0; i < static_cast<int>(nodes.size()); ++i) {
1349 1349
        Node n = nodes[i];
1350 1350
        if (label == 0) {
1351 1351
          std::ostringstream os;
1352 1352
          os << _graph.id(n);
1353 1353
          _writer_bits::writeToken(*_os, os.str());
1354 1354
          *_os << '\t';
1355 1355
          _node_index.insert(std::make_pair(n, os.str()));
1356 1356
        }
1357 1357
        for (typename NodeMaps::iterator it = _node_maps.begin();
1358 1358
             it != _node_maps.end(); ++it) {
1359 1359
          std::string value = it->second->get(n);
1360 1360
          _writer_bits::writeToken(*_os, value);
1361 1361
          if (it->first == "label") {
1362 1362
            _node_index.insert(std::make_pair(n, value));
1363 1363
          }
1364 1364
          *_os << '\t';
1365 1365
        }
1366 1366
        *_os << std::endl;
1367 1367
      }
1368 1368
    }
1369 1369

	
1370 1370
    void createNodeIndex() {
1371 1371
      _writer_bits::MapStorageBase<Node>* label = 0;
1372 1372
      for (typename NodeMaps::iterator it = _node_maps.begin();
1373 1373
           it != _node_maps.end(); ++it) {
1374 1374
        if (it->first == "label") {
1375 1375
          label = it->second;
1376 1376
          break;
1377 1377
        }
1378 1378
      }
1379 1379

	
1380 1380
      if (label == 0) {
1381 1381
        for (NodeIt n(_graph); n != INVALID; ++n) {
1382 1382
          std::ostringstream os;
1383 1383
          os << _graph.id(n);
1384 1384
          _node_index.insert(std::make_pair(n, os.str()));
1385 1385
        }
1386 1386
      } else {
1387 1387
        for (NodeIt n(_graph); n != INVALID; ++n) {
1388 1388
          std::string value = label->get(n);
1389 1389
          _node_index.insert(std::make_pair(n, value));
1390 1390
        }
1391 1391
      }
1392 1392
    }
1393 1393

	
1394 1394
    void writeEdges() {
1395 1395
      _writer_bits::MapStorageBase<Edge>* label = 0;
1396 1396
      for (typename EdgeMaps::iterator it = _edge_maps.begin();
1397 1397
           it != _edge_maps.end(); ++it) {
1398 1398
        if (it->first == "label") {
1399 1399
          label = it->second;
1400 1400
          break;
1401 1401
        }
1402 1402
      }
1403 1403

	
1404 1404
      *_os << "@edges";
1405 1405
      if (!_edges_caption.empty()) {
1406 1406
        _writer_bits::writeToken(*_os << ' ', _edges_caption);
1407 1407
      }
1408 1408
      *_os << std::endl;
1409 1409

	
1410 1410
      *_os << '\t' << '\t';
1411 1411
      if (label == 0) {
1412 1412
        *_os << "label" << '\t';
1413 1413
      }
1414 1414
      for (typename EdgeMaps::iterator it = _edge_maps.begin();
1415 1415
           it != _edge_maps.end(); ++it) {
1416 1416
        _writer_bits::writeToken(*_os, it->first) << '\t';
1417 1417
      }
1418 1418
      *_os << std::endl;
1419 1419

	
1420 1420
      std::vector<Edge> edges;
1421 1421
      for (EdgeIt n(_graph); n != INVALID; ++n) {
1422 1422
        edges.push_back(n);
1423 1423
      }
1424 1424

	
1425 1425
      if (label == 0) {
1426 1426
        IdMap<Graph, Edge> id_map(_graph);
1427 1427
        _writer_bits::MapLess<IdMap<Graph, Edge> > id_less(id_map);
1428 1428
        std::sort(edges.begin(), edges.end(), id_less);
1429 1429
      } else {
1430 1430
        label->sort(edges);
1431 1431
      }
1432 1432

	
1433 1433
      for (int i = 0; i < static_cast<int>(edges.size()); ++i) {
1434 1434
        Edge e = edges[i];
1435 1435
        _writer_bits::writeToken(*_os, _node_index.
1436 1436
                                 find(_graph.u(e))->second);
1437 1437
        *_os << '\t';
1438 1438
        _writer_bits::writeToken(*_os, _node_index.
1439 1439
                                 find(_graph.v(e))->second);
1440 1440
        *_os << '\t';
1441 1441
        if (label == 0) {
1442 1442
          std::ostringstream os;
1443 1443
          os << _graph.id(e);
1444 1444
          _writer_bits::writeToken(*_os, os.str());
1445 1445
          *_os << '\t';
1446 1446
          _edge_index.insert(std::make_pair(e, os.str()));
1447 1447
        }
1448 1448
        for (typename EdgeMaps::iterator it = _edge_maps.begin();
1449 1449
             it != _edge_maps.end(); ++it) {
1450 1450
          std::string value = it->second->get(e);
1451 1451
          _writer_bits::writeToken(*_os, value);
1452 1452
          if (it->first == "label") {
1453 1453
            _edge_index.insert(std::make_pair(e, value));
1454 1454
          }
1455 1455
          *_os << '\t';
1456 1456
        }
1457 1457
        *_os << std::endl;
1458 1458
      }
1459 1459
    }
1460 1460

	
1461 1461
    void createEdgeIndex() {
1462 1462
      _writer_bits::MapStorageBase<Edge>* label = 0;
1463 1463
      for (typename EdgeMaps::iterator it = _edge_maps.begin();
1464 1464
           it != _edge_maps.end(); ++it) {
1465 1465
        if (it->first == "label") {
1466 1466
          label = it->second;
1467 1467
          break;
1468 1468
        }
1469 1469
      }
1470 1470

	
1471 1471
      if (label == 0) {
1472 1472
        for (EdgeIt e(_graph); e != INVALID; ++e) {
1473 1473
          std::ostringstream os;
1474 1474
          os << _graph.id(e);
1475 1475
          _edge_index.insert(std::make_pair(e, os.str()));
1476 1476
        }
1477 1477
      } else {
1478 1478
        for (EdgeIt e(_graph); e != INVALID; ++e) {
1479 1479
          std::string value = label->get(e);
1480 1480
          _edge_index.insert(std::make_pair(e, value));
1481 1481
        }
1482 1482
      }
1483 1483
    }
1484 1484

	
1485 1485
    void writeAttributes() {
1486 1486
      if (_attributes.empty()) return;
1487 1487
      *_os << "@attributes";
1488 1488
      if (!_attributes_caption.empty()) {
1489 1489
        _writer_bits::writeToken(*_os << ' ', _attributes_caption);
1490 1490
      }
1491 1491
      *_os << std::endl;
1492 1492
      for (typename Attributes::iterator it = _attributes.begin();
1493 1493
           it != _attributes.end(); ++it) {
1494 1494
        _writer_bits::writeToken(*_os, it->first) << ' ';
1495 1495
        _writer_bits::writeToken(*_os, it->second->get());
1496 1496
        *_os << std::endl;
1497 1497
      }
1498 1498
    }
1499 1499

	
1500 1500
  public:
1501 1501

	
1502
    /// \name Execution of the writer
1502
    /// \name Execution of the Writer
1503 1503
    /// @{
1504 1504

	
1505 1505
    /// \brief Start the batch processing
1506 1506
    ///
1507 1507
    /// This function starts the batch processing.
1508 1508
    void run() {
1509 1509
      if (!_skip_nodes) {
1510 1510
        writeNodes();
1511 1511
      } else {
1512 1512
        createNodeIndex();
1513 1513
      }
1514 1514
      if (!_skip_edges) {
1515 1515
        writeEdges();
1516 1516
      } else {
1517 1517
        createEdgeIndex();
1518 1518
      }
1519 1519
      writeAttributes();
1520 1520
    }
1521 1521

	
1522 1522
    /// \brief Give back the stream of the writer
1523 1523
    ///
1524 1524
    /// Give back the stream of the writer
1525 1525
    std::ostream& ostream() {
1526 1526
      return *_os;
1527 1527
    }
1528 1528

	
1529 1529
    /// @}
1530 1530
  };
1531 1531

	
1532 1532
  /// \brief Return a \ref GraphWriter class
1533 1533
  ///
1534 1534
  /// This function just returns a \ref GraphWriter class.
1535 1535
  /// \relates GraphWriter
1536 1536
  template <typename Graph>
1537 1537
  GraphWriter<Graph> graphWriter(const Graph& graph,
1538 1538
                                 std::ostream& os) {
1539 1539
    GraphWriter<Graph> tmp(graph, os);
1540 1540
    return tmp;
1541 1541
  }
1542 1542

	
1543 1543
  /// \brief Return a \ref GraphWriter class
1544 1544
  ///
1545 1545
  /// This function just returns a \ref GraphWriter class.
1546 1546
  /// \relates GraphWriter
1547 1547
  template <typename Graph>
1548 1548
  GraphWriter<Graph> graphWriter(const Graph& graph, const std::string& fn) {
1549 1549
    GraphWriter<Graph> tmp(graph, fn);
1550 1550
    return tmp;
1551 1551
  }
1552 1552

	
1553 1553
  /// \brief Return a \ref GraphWriter class
1554 1554
  ///
1555 1555
  /// This function just returns a \ref GraphWriter class.
1556 1556
  /// \relates GraphWriter
1557 1557
  template <typename Graph>
1558 1558
  GraphWriter<Graph> graphWriter(const Graph& graph, const char* fn) {
1559 1559
    GraphWriter<Graph> tmp(graph, fn);
1560 1560
    return tmp;
1561 1561
  }
1562 1562

	
1563 1563
  class SectionWriter;
1564 1564

	
1565 1565
  SectionWriter sectionWriter(std::istream& is);
1566 1566
  SectionWriter sectionWriter(const std::string& fn);
1567 1567
  SectionWriter sectionWriter(const char* fn);
1568 1568

	
1569 1569
  /// \ingroup lemon_io
1570 1570
  ///
1571 1571
  /// \brief Section writer class
1572 1572
  ///
1573 1573
  /// In the \ref lgf-format "LGF" file extra sections can be placed,
1574 1574
  /// which contain any data in arbitrary format. Such sections can be
1575 1575
  /// written with this class. A writing rule can be added to the
1576 1576
  /// class with two different functions. With the \c sectionLines()
1577 1577
  /// function a generator can write the section line-by-line, while
1578 1578
  /// with the \c sectionStream() member the section can be written to
1579 1579
  /// an output stream.
1580 1580
  class SectionWriter {
1581 1581
  private:
1582 1582

	
1583 1583
    std::ostream* _os;
1584 1584
    bool local_os;
1585 1585

	
1586 1586
    typedef std::vector<std::pair<std::string, _writer_bits::Section*> >
1587 1587
    Sections;
1588 1588

	
1589 1589
    Sections _sections;
1590 1590

	
1591 1591
  public:
1592 1592

	
1593 1593
    /// \brief Constructor
1594 1594
    ///
1595 1595
    /// Construct a section writer, which writes to the given output
1596 1596
    /// stream.
1597 1597
    SectionWriter(std::ostream& os)
1598 1598
      : _os(&os), local_os(false) {}
1599 1599

	
1600 1600
    /// \brief Constructor
1601 1601
    ///
1602 1602
    /// Construct a section writer, which writes into the given file.
1603 1603
    SectionWriter(const std::string& fn)
1604 1604
      : _os(new std::ofstream(fn.c_str())), local_os(true) {
1605 1605
      if (!(*_os)) {
1606 1606
        delete _os;
1607 1607
        throw IoError("Cannot write file", fn);
1608 1608
      }
1609 1609
    }
1610 1610

	
1611 1611
    /// \brief Constructor
1612 1612
    ///
1613 1613
    /// Construct a section writer, which writes into the given file.
1614 1614
    SectionWriter(const char* fn)
1615 1615
      : _os(new std::ofstream(fn)), local_os(true) {
1616 1616
      if (!(*_os)) {
1617 1617
        delete _os;
1618 1618
        throw IoError("Cannot write file", fn);
1619 1619
      }
1620 1620
    }
1621 1621

	
1622 1622
    /// \brief Destructor
1623 1623
    ~SectionWriter() {
1624 1624
      for (Sections::iterator it = _sections.begin();
1625 1625
           it != _sections.end(); ++it) {
1626 1626
        delete it->second;
1627 1627
      }
1628 1628

	
1629 1629
      if (local_os) {
1630 1630
        delete _os;
1631 1631
      }
1632 1632

	
1633 1633
    }
1634 1634

	
1635 1635
  private:
1636 1636

	
1637 1637
    friend SectionWriter sectionWriter(std::ostream& os);
1638 1638
    friend SectionWriter sectionWriter(const std::string& fn);
1639 1639
    friend SectionWriter sectionWriter(const char* fn);
1640 1640

	
1641 1641
    SectionWriter(SectionWriter& other)
1642 1642
      : _os(other._os), local_os(other.local_os) {
1643 1643

	
1644 1644
      other._os = 0;
1645 1645
      other.local_os = false;
1646 1646

	
1647 1647
      _sections.swap(other._sections);
1648 1648
    }
1649 1649

	
1650 1650
    SectionWriter& operator=(const SectionWriter&);
1651 1651

	
1652 1652
  public:
1653 1653

	
1654
    /// \name Section writers
1654
    /// \name Section Writers
1655 1655
    /// @{
1656 1656

	
1657 1657
    /// \brief Add a section writer with line oriented writing
1658 1658
    ///
1659 1659
    /// The first parameter is the type descriptor of the section, the
1660 1660
    /// second is a generator with std::string values. At the writing
1661 1661
    /// process, the returned \c std::string will be written into the
1662 1662
    /// output file until it is an empty string.
1663 1663
    ///
1664 1664
    /// For example, an integer vector is written into a section.
1665 1665
    ///\code
1666 1666
    ///  @numbers
1667 1667
    ///  12 45 23 78
1668 1668
    ///  4 28 38 28
1669 1669
    ///  23 6 16
1670 1670
    ///\endcode
1671 1671
    ///
1672 1672
    /// The generator is implemented as a struct.
1673 1673
    ///\code
1674 1674
    ///  struct NumberSection {
1675 1675
    ///    std::vector<int>::const_iterator _it, _end;
1676 1676
    ///    NumberSection(const std::vector<int>& data)
1677 1677
    ///      : _it(data.begin()), _end(data.end()) {}
1678 1678
    ///    std::string operator()() {
1679 1679
    ///      int rem_in_line = 4;
1680 1680
    ///      std::ostringstream ls;
1681 1681
    ///      while (rem_in_line > 0 && _it != _end) {
1682 1682
    ///        ls << *(_it++) << ' ';
1683 1683
    ///        --rem_in_line;
1684 1684
    ///      }
1685 1685
    ///      return ls.str();
1686 1686
    ///    }
1687 1687
    ///  };
1688 1688
    ///
1689 1689
    ///  // ...
1690 1690
    ///
1691 1691
    ///  writer.sectionLines("numbers", NumberSection(vec));
1692 1692
    ///\endcode
1693 1693
    template <typename Functor>
1694 1694
    SectionWriter& sectionLines(const std::string& type, Functor functor) {
1695 1695
      LEMON_ASSERT(!type.empty(), "Type is empty.");
1696 1696
      _sections.push_back(std::make_pair(type,
1697 1697
        new _writer_bits::LineSection<Functor>(functor)));
1698 1698
      return *this;
1699 1699
    }
1700 1700

	
1701 1701

	
1702 1702
    /// \brief Add a section writer with stream oriented writing
1703 1703
    ///
1704 1704
    /// The first parameter is the type of the section, the second is
1705 1705
    /// a functor, which takes a \c std::ostream& parameter. The
1706 1706
    /// functor writes the section to the output stream.
1707 1707
    /// \warning The last line must be closed with end-line character.
1708 1708
    template <typename Functor>
1709 1709
    SectionWriter& sectionStream(const std::string& type, Functor functor) {
1710 1710
      LEMON_ASSERT(!type.empty(), "Type is empty.");
1711 1711
      _sections.push_back(std::make_pair(type,
1712 1712
         new _writer_bits::StreamSection<Functor>(functor)));
1713 1713
      return *this;
1714 1714
    }
1715 1715

	
1716 1716
    /// @}
1717 1717

	
1718 1718
  public:
1719 1719

	
1720 1720

	
1721
    /// \name Execution of the writer
1721
    /// \name Execution of the Writer
1722 1722
    /// @{
1723 1723

	
1724 1724
    /// \brief Start the batch processing
1725 1725
    ///
1726 1726
    /// This function starts the batch processing.
1727 1727
    void run() {
1728 1728

	
1729 1729
      LEMON_ASSERT(_os != 0, "This writer is assigned to an other writer");
1730 1730

	
1731 1731
      for (Sections::iterator it = _sections.begin();
1732 1732
           it != _sections.end(); ++it) {
1733 1733
        (*_os) << '@' << it->first << std::endl;
1734 1734
        it->second->process(*_os);
1735 1735
      }
1736 1736
    }
1737 1737

	
1738 1738
    /// \brief Give back the stream of the writer
1739 1739
    ///
1740 1740
    /// Returns the stream of the writer
1741 1741
    std::ostream& ostream() {
1742 1742
      return *_os;
1743 1743
    }
1744 1744

	
1745 1745
    /// @}
1746 1746

	
1747 1747
  };
1748 1748

	
1749 1749
  /// \brief Return a \ref SectionWriter class
1750 1750
  ///
1751 1751
  /// This function just returns a \ref SectionWriter class.
1752 1752
  /// \relates SectionWriter
1753 1753
  inline SectionWriter sectionWriter(std::ostream& os) {
1754 1754
    SectionWriter tmp(os);
1755 1755
    return tmp;
1756 1756
  }
1757 1757

	
1758 1758
  /// \brief Return a \ref SectionWriter class
1759 1759
  ///
1760 1760
  /// This function just returns a \ref SectionWriter class.
1761 1761
  /// \relates SectionWriter
1762 1762
  inline SectionWriter sectionWriter(const std::string& fn) {
1763 1763
    SectionWriter tmp(fn);
1764 1764
    return tmp;
1765 1765
  }
1766 1766

	
1767 1767
  /// \brief Return a \ref SectionWriter class
1768 1768
  ///
1769 1769
  /// This function just returns a \ref SectionWriter class.
1770 1770
  /// \relates SectionWriter
1771 1771
  inline SectionWriter sectionWriter(const char* fn) {
1772 1772
    SectionWriter tmp(fn);
1773 1773
    return tmp;
1774 1774
  }
1775 1775
}
1776 1776

	
1777 1777
#endif
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_LP_BASE_H
20 20
#define LEMON_LP_BASE_H
21 21

	
22 22
#include<iostream>
23 23
#include<vector>
24 24
#include<map>
25 25
#include<limits>
26 26
#include<lemon/math.h>
27 27

	
28 28
#include<lemon/error.h>
29 29
#include<lemon/assert.h>
30 30

	
31 31
#include<lemon/core.h>
32 32
#include<lemon/bits/solver_bits.h>
33 33

	
34 34
///\file
35 35
///\brief The interface of the LP solver interface.
36 36
///\ingroup lp_group
37 37
namespace lemon {
38 38

	
39 39
  ///Common base class for LP and MIP solvers
40 40

	
41 41
  ///Usually this class is not used directly, please use one of the concrete
42 42
  ///implementations of the solver interface.
43 43
  ///\ingroup lp_group
44 44
  class LpBase {
45 45

	
46 46
  protected:
47 47

	
48 48
    _solver_bits::VarIndex rows;
49 49
    _solver_bits::VarIndex cols;
50 50

	
51 51
  public:
52 52

	
53 53
    ///Possible outcomes of an LP solving procedure
54 54
    enum SolveExitStatus {
55
      ///This means that the problem has been successfully solved: either
55
      /// = 0. It means that the problem has been successfully solved: either
56 56
      ///an optimal solution has been found or infeasibility/unboundedness
57 57
      ///has been proved.
58 58
      SOLVED = 0,
59
      ///Any other case (including the case when some user specified
60
      ///limit has been exceeded)
59
      /// = 1. Any other case (including the case when some user specified
60
      ///limit has been exceeded).
61 61
      UNSOLVED = 1
62 62
    };
63 63

	
64 64
    ///Direction of the optimization
65 65
    enum Sense {
66 66
      /// Minimization
67 67
      MIN,
68 68
      /// Maximization
69 69
      MAX
70 70
    };
71 71

	
72 72
    ///Enum for \c messageLevel() parameter
73 73
    enum MessageLevel {
74
      /// no output (default value)
74
      /// No output (default value).
75 75
      MESSAGE_NOTHING,
76
      /// error messages only
76
      /// Error messages only.
77 77
      MESSAGE_ERROR,
78
      /// warnings
78
      /// Warnings.
79 79
      MESSAGE_WARNING,
80
      /// normal output
80
      /// Normal output.
81 81
      MESSAGE_NORMAL,
82
      /// verbose output
82
      /// Verbose output.
83 83
      MESSAGE_VERBOSE
84 84
    };
85 85
    
86 86

	
87 87
    ///The floating point type used by the solver
88 88
    typedef double Value;
89 89
    ///The infinity constant
90 90
    static const Value INF;
91 91
    ///The not a number constant
92 92
    static const Value NaN;
93 93

	
94 94
    friend class Col;
95 95
    friend class ColIt;
96 96
    friend class Row;
97 97
    friend class RowIt;
98 98

	
99 99
    ///Refer to a column of the LP.
100 100

	
101 101
    ///This type is used to refer to a column of the LP.
102 102
    ///
103 103
    ///Its value remains valid and correct even after the addition or erase of
104 104
    ///other columns.
105 105
    ///
106 106
    ///\note This class is similar to other Item types in LEMON, like
107 107
    ///Node and Arc types in digraph.
108 108
    class Col {
109 109
      friend class LpBase;
110 110
    protected:
111 111
      int _id;
112 112
      explicit Col(int id) : _id(id) {}
113 113
    public:
114 114
      typedef Value ExprValue;
115 115
      typedef True LpCol;
116 116
      /// Default constructor
117 117
      
118 118
      /// \warning The default constructor sets the Col to an
119 119
      /// undefined value.
120 120
      Col() {}
121 121
      /// Invalid constructor \& conversion.
122 122
      
123 123
      /// This constructor initializes the Col to be invalid.
124 124
      /// \sa Invalid for more details.      
125 125
      Col(const Invalid&) : _id(-1) {}
126 126
      /// Equality operator
127 127

	
128 128
      /// Two \ref Col "Col"s are equal if and only if they point to
129 129
      /// the same LP column or both are invalid.
130 130
      bool operator==(Col c) const  {return _id == c._id;}
131 131
      /// Inequality operator
132 132

	
133 133
      /// \sa operator==(Col c)
134 134
      ///
135 135
      bool operator!=(Col c) const  {return _id != c._id;}
136 136
      /// Artificial ordering operator.
137 137

	
138 138
      /// To allow the use of this object in std::map or similar
139 139
      /// associative container we require this.
140 140
      ///
141 141
      /// \note This operator only have to define some strict ordering of
142 142
      /// the items; this order has nothing to do with the iteration
143 143
      /// ordering of the items.
144 144
      bool operator<(Col c) const  {return _id < c._id;}
145 145
    };
146 146

	
147 147
    ///Iterator for iterate over the columns of an LP problem
148 148

	
149 149
    /// Its usage is quite simple, for example you can count the number
150 150
    /// of columns in an LP \c lp:
151 151
    ///\code
152 152
    /// int count=0;
153 153
    /// for (LpBase::ColIt c(lp); c!=INVALID; ++c) ++count;
154 154
    ///\endcode
155 155
    class ColIt : public Col {
156 156
      const LpBase *_solver;
157 157
    public:
158 158
      /// Default constructor
159 159
      
160 160
      /// \warning The default constructor sets the iterator
161 161
      /// to an undefined value.
162 162
      ColIt() {}
163 163
      /// Sets the iterator to the first Col
164 164
      
165 165
      /// Sets the iterator to the first Col.
166 166
      ///
167 167
      ColIt(const LpBase &solver) : _solver(&solver)
168 168
      {
169 169
        _solver->cols.firstItem(_id);
170 170
      }
171 171
      /// Invalid constructor \& conversion
172 172
      
173 173
      /// Initialize the iterator to be invalid.
174 174
      /// \sa Invalid for more details.
175 175
      ColIt(const Invalid&) : Col(INVALID) {}
176 176
      /// Next column
177 177
      
178 178
      /// Assign the iterator to the next column.
179 179
      ///
180 180
      ColIt &operator++()
181 181
      {
182 182
        _solver->cols.nextItem(_id);
183 183
        return *this;
184 184
      }
185 185
    };
186 186

	
187 187
    /// \brief Returns the ID of the column.
188 188
    static int id(const Col& col) { return col._id; }
189 189
    /// \brief Returns the column with the given ID.
190 190
    ///
191 191
    /// \pre The argument should be a valid column ID in the LP problem.
192 192
    static Col colFromId(int id) { return Col(id); }
193 193

	
194 194
    ///Refer to a row of the LP.
195 195

	
196 196
    ///This type is used to refer to a row of the LP.
197 197
    ///
198 198
    ///Its value remains valid and correct even after the addition or erase of
199 199
    ///other rows.
200 200
    ///
201 201
    ///\note This class is similar to other Item types in LEMON, like
202 202
    ///Node and Arc types in digraph.
203 203
    class Row {
204 204
      friend class LpBase;
205 205
    protected:
206 206
      int _id;
207 207
      explicit Row(int id) : _id(id) {}
208 208
    public:
209 209
      typedef Value ExprValue;
210 210
      typedef True LpRow;
211 211
      /// Default constructor
212 212
      
213 213
      /// \warning The default constructor sets the Row to an
214 214
      /// undefined value.
215 215
      Row() {}
216 216
      /// Invalid constructor \& conversion.
217 217
      
218 218
      /// This constructor initializes the Row to be invalid.
219 219
      /// \sa Invalid for more details.      
220 220
      Row(const Invalid&) : _id(-1) {}
221 221
      /// Equality operator
222 222

	
223 223
      /// Two \ref Row "Row"s are equal if and only if they point to
224 224
      /// the same LP row or both are invalid.
225 225
      bool operator==(Row r) const  {return _id == r._id;}
226 226
      /// Inequality operator
227 227
      
228 228
      /// \sa operator==(Row r)
229 229
      ///
230 230
      bool operator!=(Row r) const  {return _id != r._id;}
231 231
      /// Artificial ordering operator.
232 232

	
233 233
      /// To allow the use of this object in std::map or similar
234 234
      /// associative container we require this.
235 235
      ///
236 236
      /// \note This operator only have to define some strict ordering of
237 237
      /// the items; this order has nothing to do with the iteration
238 238
      /// ordering of the items.
239 239
      bool operator<(Row r) const  {return _id < r._id;}
240 240
    };
241 241

	
242 242
    ///Iterator for iterate over the rows of an LP problem
243 243

	
244 244
    /// Its usage is quite simple, for example you can count the number
245 245
    /// of rows in an LP \c lp:
246 246
    ///\code
247 247
    /// int count=0;
248 248
    /// for (LpBase::RowIt c(lp); c!=INVALID; ++c) ++count;
249 249
    ///\endcode
250 250
    class RowIt : public Row {
251 251
      const LpBase *_solver;
252 252
    public:
253 253
      /// Default constructor
254 254
      
255 255
      /// \warning The default constructor sets the iterator
256 256
      /// to an undefined value.
257 257
      RowIt() {}
258 258
      /// Sets the iterator to the first Row
259 259
      
260 260
      /// Sets the iterator to the first Row.
261 261
      ///
262 262
      RowIt(const LpBase &solver) : _solver(&solver)
263 263
      {
264 264
        _solver->rows.firstItem(_id);
265 265
      }
266 266
      /// Invalid constructor \& conversion
267 267
      
268 268
      /// Initialize the iterator to be invalid.
269 269
      /// \sa Invalid for more details.
270 270
      RowIt(const Invalid&) : Row(INVALID) {}
271 271
      /// Next row
272 272
      
273 273
      /// Assign the iterator to the next row.
274 274
      ///
275 275
      RowIt &operator++()
276 276
      {
277 277
        _solver->rows.nextItem(_id);
278 278
        return *this;
279 279
      }
280 280
    };
281 281

	
282 282
    /// \brief Returns the ID of the row.
283 283
    static int id(const Row& row) { return row._id; }
284 284
    /// \brief Returns the row with the given ID.
285 285
    ///
286 286
    /// \pre The argument should be a valid row ID in the LP problem.
287 287
    static Row rowFromId(int id) { return Row(id); }
288 288

	
289 289
  public:
290 290

	
291 291
    ///Linear expression of variables and a constant component
292 292

	
293 293
    ///This data structure stores a linear expression of the variables
294 294
    ///(\ref Col "Col"s) and also has a constant component.
295 295
    ///
296 296
    ///There are several ways to access and modify the contents of this
297 297
    ///container.
298 298
    ///\code
299 299
    ///e[v]=5;
300 300
    ///e[v]+=12;
301 301
    ///e.erase(v);
302 302
    ///\endcode
303 303
    ///or you can also iterate through its elements.
304 304
    ///\code
305 305
    ///double s=0;
306 306
    ///for(LpBase::Expr::ConstCoeffIt i(e);i!=INVALID;++i)
307 307
    ///  s+=*i * primal(i);
308 308
    ///\endcode
309 309
    ///(This code computes the primal value of the expression).
310 310
    ///- Numbers (<tt>double</tt>'s)
311 311
    ///and variables (\ref Col "Col"s) directly convert to an
312 312
    ///\ref Expr and the usual linear operations are defined, so
313 313
    ///\code
314 314
    ///v+w
315 315
    ///2*v-3.12*(v-w/2)+2
316 316
    ///v*2.1+(3*v+(v*12+w+6)*3)/2
317 317
    ///\endcode
318 318
    ///are valid expressions.
319 319
    ///The usual assignment operations are also defined.
320 320
    ///\code
321 321
    ///e=v+w;
322 322
    ///e+=2*v-3.12*(v-w/2)+2;
323 323
    ///e*=3.4;
324 324
    ///e/=5;
325 325
    ///\endcode
326 326
    ///- The constant member can be set and read by dereference
327 327
    ///  operator (unary *)
328 328
    ///
329 329
    ///\code
330 330
    ///*e=12;
331 331
    ///double c=*e;
332 332
    ///\endcode
333 333
    ///
334 334
    ///\sa Constr
335 335
    class Expr {
336 336
      friend class LpBase;
337 337
    public:
338 338
      /// The key type of the expression
... ...
@@ -752,513 +752,513 @@
752 752
      DualExpr &operator/=(const Value &v) {
753 753
        for (std::map<int, Value>::iterator it=comps.begin();
754 754
             it!=comps.end(); ++it)
755 755
          it->second/=v;
756 756
        return *this;
757 757
      }
758 758

	
759 759
      ///Iterator over the expression
760 760
      
761 761
      ///The iterator iterates over the terms of the expression. 
762 762
      /// 
763 763
      ///\code
764 764
      ///double s=0;
765 765
      ///for(LpBase::DualExpr::CoeffIt i(e);i!=INVALID;++i)
766 766
      ///  s+= *i * dual(i);
767 767
      ///\endcode
768 768
      class CoeffIt {
769 769
      private:
770 770

	
771 771
        std::map<int, Value>::iterator _it, _end;
772 772

	
773 773
      public:
774 774

	
775 775
        /// Sets the iterator to the first term
776 776
        
777 777
        /// Sets the iterator to the first term of the expression.
778 778
        ///
779 779
        CoeffIt(DualExpr& e)
780 780
          : _it(e.comps.begin()), _end(e.comps.end()){}
781 781

	
782 782
        /// Convert the iterator to the row of the term
783 783
        operator Row() const {
784 784
          return rowFromId(_it->first);
785 785
        }
786 786

	
787 787
        /// Returns the coefficient of the term
788 788
        Value& operator*() { return _it->second; }
789 789

	
790 790
        /// Returns the coefficient of the term
791 791
        const Value& operator*() const { return _it->second; }
792 792

	
793 793
        /// Next term
794 794
        
795 795
        /// Assign the iterator to the next term.
796 796
        ///
797 797
        CoeffIt& operator++() { ++_it; return *this; }
798 798

	
799 799
        /// Equality operator
800 800
        bool operator==(Invalid) const { return _it == _end; }
801 801
        /// Inequality operator
802 802
        bool operator!=(Invalid) const { return _it != _end; }
803 803
      };
804 804

	
805 805
      ///Iterator over the expression
806 806
      
807 807
      ///The iterator iterates over the terms of the expression. 
808 808
      /// 
809 809
      ///\code
810 810
      ///double s=0;
811 811
      ///for(LpBase::DualExpr::ConstCoeffIt i(e);i!=INVALID;++i)
812 812
      ///  s+= *i * dual(i);
813 813
      ///\endcode
814 814
      class ConstCoeffIt {
815 815
      private:
816 816

	
817 817
        std::map<int, Value>::const_iterator _it, _end;
818 818

	
819 819
      public:
820 820

	
821 821
        /// Sets the iterator to the first term
822 822
        
823 823
        /// Sets the iterator to the first term of the expression.
824 824
        ///
825 825
        ConstCoeffIt(const DualExpr& e)
826 826
          : _it(e.comps.begin()), _end(e.comps.end()){}
827 827

	
828 828
        /// Convert the iterator to the row of the term
829 829
        operator Row() const {
830 830
          return rowFromId(_it->first);
831 831
        }
832 832

	
833 833
        /// Returns the coefficient of the term
834 834
        const Value& operator*() const { return _it->second; }
835 835

	
836 836
        /// Next term
837 837
        
838 838
        /// Assign the iterator to the next term.
839 839
        ///
840 840
        ConstCoeffIt& operator++() { ++_it; return *this; }
841 841

	
842 842
        /// Equality operator
843 843
        bool operator==(Invalid) const { return _it == _end; }
844 844
        /// Inequality operator
845 845
        bool operator!=(Invalid) const { return _it != _end; }
846 846
      };
847 847
    };
848 848

	
849 849

	
850 850
  protected:
851 851

	
852 852
    class InsertIterator {
853 853
    private:
854 854

	
855 855
      std::map<int, Value>& _host;
856 856
      const _solver_bits::VarIndex& _index;
857 857

	
858 858
    public:
859 859

	
860 860
      typedef std::output_iterator_tag iterator_category;
861 861
      typedef void difference_type;
862 862
      typedef void value_type;
863 863
      typedef void reference;
864 864
      typedef void pointer;
865 865

	
866 866
      InsertIterator(std::map<int, Value>& host,
867 867
                   const _solver_bits::VarIndex& index)
868 868
        : _host(host), _index(index) {}
869 869

	
870 870
      InsertIterator& operator=(const std::pair<int, Value>& value) {
871 871
        typedef std::map<int, Value>::value_type pair_type;
872 872
        _host.insert(pair_type(_index[value.first], value.second));
873 873
        return *this;
874 874
      }
875 875

	
876 876
      InsertIterator& operator*() { return *this; }
877 877
      InsertIterator& operator++() { return *this; }
878 878
      InsertIterator operator++(int) { return *this; }
879 879

	
880 880
    };
881 881

	
882 882
    class ExprIterator {
883 883
    private:
884 884
      std::map<int, Value>::const_iterator _host_it;
885 885
      const _solver_bits::VarIndex& _index;
886 886
    public:
887 887

	
888 888
      typedef std::bidirectional_iterator_tag iterator_category;
889 889
      typedef std::ptrdiff_t difference_type;
890 890
      typedef const std::pair<int, Value> value_type;
891 891
      typedef value_type reference;
892 892

	
893 893
      class pointer {
894 894
      public:
895 895
        pointer(value_type& _value) : value(_value) {}
896 896
        value_type* operator->() { return &value; }
897 897
      private:
898 898
        value_type value;
899 899
      };
900 900

	
901 901
      ExprIterator(const std::map<int, Value>::const_iterator& host_it,
902 902
                   const _solver_bits::VarIndex& index)
903 903
        : _host_it(host_it), _index(index) {}
904 904

	
905 905
      reference operator*() {
906 906
        return std::make_pair(_index(_host_it->first), _host_it->second);
907 907
      }
908 908

	
909 909
      pointer operator->() {
910 910
        return pointer(operator*());
911 911
      }
912 912

	
913 913
      ExprIterator& operator++() { ++_host_it; return *this; }
914 914
      ExprIterator operator++(int) {
915 915
        ExprIterator tmp(*this); ++_host_it; return tmp;
916 916
      }
917 917

	
918 918
      ExprIterator& operator--() { --_host_it; return *this; }
919 919
      ExprIterator operator--(int) {
920 920
        ExprIterator tmp(*this); --_host_it; return tmp;
921 921
      }
922 922

	
923 923
      bool operator==(const ExprIterator& it) const {
924 924
        return _host_it == it._host_it;
925 925
      }
926 926

	
927 927
      bool operator!=(const ExprIterator& it) const {
928 928
        return _host_it != it._host_it;
929 929
      }
930 930

	
931 931
    };
932 932

	
933 933
  protected:
934 934

	
935 935
    //Abstract virtual functions
936 936

	
937 937
    virtual int _addColId(int col) { return cols.addIndex(col); }
938 938
    virtual int _addRowId(int row) { return rows.addIndex(row); }
939 939

	
940 940
    virtual void _eraseColId(int col) { cols.eraseIndex(col); }
941 941
    virtual void _eraseRowId(int row) { rows.eraseIndex(row); }
942 942

	
943 943
    virtual int _addCol() = 0;
944 944
    virtual int _addRow() = 0;
945 945

	
946 946
    virtual void _eraseCol(int col) = 0;
947 947
    virtual void _eraseRow(int row) = 0;
948 948

	
949 949
    virtual void _getColName(int col, std::string& name) const = 0;
950 950
    virtual void _setColName(int col, const std::string& name) = 0;
951 951
    virtual int _colByName(const std::string& name) const = 0;
952 952

	
953 953
    virtual void _getRowName(int row, std::string& name) const = 0;
954 954
    virtual void _setRowName(int row, const std::string& name) = 0;
955 955
    virtual int _rowByName(const std::string& name) const = 0;
956 956

	
957 957
    virtual void _setRowCoeffs(int i, ExprIterator b, ExprIterator e) = 0;
958 958
    virtual void _getRowCoeffs(int i, InsertIterator b) const = 0;
959 959

	
960 960
    virtual void _setColCoeffs(int i, ExprIterator b, ExprIterator e) = 0;
961 961
    virtual void _getColCoeffs(int i, InsertIterator b) const = 0;
962 962

	
963 963
    virtual void _setCoeff(int row, int col, Value value) = 0;
964 964
    virtual Value _getCoeff(int row, int col) const = 0;
965 965

	
966 966
    virtual void _setColLowerBound(int i, Value value) = 0;
967 967
    virtual Value _getColLowerBound(int i) const = 0;
968 968

	
969 969
    virtual void _setColUpperBound(int i, Value value) = 0;
970 970
    virtual Value _getColUpperBound(int i) const = 0;
971 971

	
972 972
    virtual void _setRowLowerBound(int i, Value value) = 0;
973 973
    virtual Value _getRowLowerBound(int i) const = 0;
974 974

	
975 975
    virtual void _setRowUpperBound(int i, Value value) = 0;
976 976
    virtual Value _getRowUpperBound(int i) const = 0;
977 977

	
978 978
    virtual void _setObjCoeffs(ExprIterator b, ExprIterator e) = 0;
979 979
    virtual void _getObjCoeffs(InsertIterator b) const = 0;
980 980

	
981 981
    virtual void _setObjCoeff(int i, Value obj_coef) = 0;
982 982
    virtual Value _getObjCoeff(int i) const = 0;
983 983

	
984 984
    virtual void _setSense(Sense) = 0;
985 985
    virtual Sense _getSense() const = 0;
986 986

	
987 987
    virtual void _clear() = 0;
988 988

	
989 989
    virtual const char* _solverName() const = 0;
990 990

	
991 991
    virtual void _messageLevel(MessageLevel level) = 0;
992 992

	
993 993
    //Own protected stuff
994 994

	
995 995
    //Constant component of the objective function
996 996
    Value obj_const_comp;
997 997

	
998 998
    LpBase() : rows(), cols(), obj_const_comp(0) {}
999 999

	
1000 1000
  public:
1001 1001

	
1002 1002
    /// Virtual destructor
1003 1003
    virtual ~LpBase() {}
1004 1004

	
1005 1005
    ///Gives back the name of the solver.
1006 1006
    const char* solverName() const {return _solverName();}
1007 1007

	
1008
    ///\name Build up and modify the LP
1008
    ///\name Build Up and Modify the LP
1009 1009

	
1010 1010
    ///@{
1011 1011

	
1012 1012
    ///Add a new empty column (i.e a new variable) to the LP
1013 1013
    Col addCol() { Col c; c._id = _addColId(_addCol()); return c;}
1014 1014

	
1015 1015
    ///\brief Adds several new columns (i.e variables) at once
1016 1016
    ///
1017 1017
    ///This magic function takes a container as its argument and fills
1018 1018
    ///its elements with new columns (i.e. variables)
1019 1019
    ///\param t can be
1020 1020
    ///- a standard STL compatible iterable container with
1021 1021
    ///\ref Col as its \c values_type like
1022 1022
    ///\code
1023 1023
    ///std::vector<LpBase::Col>
1024 1024
    ///std::list<LpBase::Col>
1025 1025
    ///\endcode
1026 1026
    ///- a standard STL compatible iterable container with
1027 1027
    ///\ref Col as its \c mapped_type like
1028 1028
    ///\code
1029 1029
    ///std::map<AnyType,LpBase::Col>
1030 1030
    ///\endcode
1031 1031
    ///- an iterable lemon \ref concepts::WriteMap "write map" like
1032 1032
    ///\code
1033 1033
    ///ListGraph::NodeMap<LpBase::Col>
1034 1034
    ///ListGraph::ArcMap<LpBase::Col>
1035 1035
    ///\endcode
1036 1036
    ///\return The number of the created column.
1037 1037
#ifdef DOXYGEN
1038 1038
    template<class T>
1039 1039
    int addColSet(T &t) { return 0;}
1040 1040
#else
1041 1041
    template<class T>
1042 1042
    typename enable_if<typename T::value_type::LpCol,int>::type
1043 1043
    addColSet(T &t,dummy<0> = 0) {
1044 1044
      int s=0;
1045 1045
      for(typename T::iterator i=t.begin();i!=t.end();++i) {*i=addCol();s++;}
1046 1046
      return s;
1047 1047
    }
1048 1048
    template<class T>
1049 1049
    typename enable_if<typename T::value_type::second_type::LpCol,
1050 1050
                       int>::type
1051 1051
    addColSet(T &t,dummy<1> = 1) {
1052 1052
      int s=0;
1053 1053
      for(typename T::iterator i=t.begin();i!=t.end();++i) {
1054 1054
        i->second=addCol();
1055 1055
        s++;
1056 1056
      }
1057 1057
      return s;
1058 1058
    }
1059 1059
    template<class T>
1060 1060
    typename enable_if<typename T::MapIt::Value::LpCol,
1061 1061
                       int>::type
1062 1062
    addColSet(T &t,dummy<2> = 2) {
1063 1063
      int s=0;
1064 1064
      for(typename T::MapIt i(t); i!=INVALID; ++i)
1065 1065
        {
1066 1066
          i.set(addCol());
1067 1067
          s++;
1068 1068
        }
1069 1069
      return s;
1070 1070
    }
1071 1071
#endif
1072 1072

	
1073 1073
    ///Set a column (i.e a dual constraint) of the LP
1074 1074

	
1075 1075
    ///\param c is the column to be modified
1076 1076
    ///\param e is a dual linear expression (see \ref DualExpr)
1077 1077
    ///a better one.
1078 1078
    void col(Col c, const DualExpr &e) {
1079 1079
      e.simplify();
1080 1080
      _setColCoeffs(cols(id(c)), ExprIterator(e.comps.begin(), rows),
1081 1081
                    ExprIterator(e.comps.end(), rows));
1082 1082
    }
1083 1083

	
1084 1084
    ///Get a column (i.e a dual constraint) of the LP
1085 1085

	
1086 1086
    ///\param c is the column to get
1087 1087
    ///\return the dual expression associated to the column
1088 1088
    DualExpr col(Col c) const {
1089 1089
      DualExpr e;
1090 1090
      _getColCoeffs(cols(id(c)), InsertIterator(e.comps, rows));
1091 1091
      return e;
1092 1092
    }
1093 1093

	
1094 1094
    ///Add a new column to the LP
1095 1095

	
1096 1096
    ///\param e is a dual linear expression (see \ref DualExpr)
1097 1097
    ///\param o is the corresponding component of the objective
1098 1098
    ///function. It is 0 by default.
1099 1099
    ///\return The created column.
1100 1100
    Col addCol(const DualExpr &e, Value o = 0) {
1101 1101
      Col c=addCol();
1102 1102
      col(c,e);
1103 1103
      objCoeff(c,o);
1104 1104
      return c;
1105 1105
    }
1106 1106

	
1107 1107
    ///Add a new empty row (i.e a new constraint) to the LP
1108 1108

	
1109 1109
    ///This function adds a new empty row (i.e a new constraint) to the LP.
1110 1110
    ///\return The created row
1111 1111
    Row addRow() { Row r; r._id = _addRowId(_addRow()); return r;}
1112 1112

	
1113 1113
    ///\brief Add several new rows (i.e constraints) at once
1114 1114
    ///
1115 1115
    ///This magic function takes a container as its argument and fills
1116 1116
    ///its elements with new row (i.e. variables)
1117 1117
    ///\param t can be
1118 1118
    ///- a standard STL compatible iterable container with
1119 1119
    ///\ref Row as its \c values_type like
1120 1120
    ///\code
1121 1121
    ///std::vector<LpBase::Row>
1122 1122
    ///std::list<LpBase::Row>
1123 1123
    ///\endcode
1124 1124
    ///- a standard STL compatible iterable container with
1125 1125
    ///\ref Row as its \c mapped_type like
1126 1126
    ///\code
1127 1127
    ///std::map<AnyType,LpBase::Row>
1128 1128
    ///\endcode
1129 1129
    ///- an iterable lemon \ref concepts::WriteMap "write map" like
1130 1130
    ///\code
1131 1131
    ///ListGraph::NodeMap<LpBase::Row>
1132 1132
    ///ListGraph::ArcMap<LpBase::Row>
1133 1133
    ///\endcode
1134 1134
    ///\return The number of rows created.
1135 1135
#ifdef DOXYGEN
1136 1136
    template<class T>
1137 1137
    int addRowSet(T &t) { return 0;}
1138 1138
#else
1139 1139
    template<class T>
1140 1140
    typename enable_if<typename T::value_type::LpRow,int>::type
1141 1141
    addRowSet(T &t, dummy<0> = 0) {
1142 1142
      int s=0;
1143 1143
      for(typename T::iterator i=t.begin();i!=t.end();++i) {*i=addRow();s++;}
1144 1144
      return s;
1145 1145
    }
1146 1146
    template<class T>
1147 1147
    typename enable_if<typename T::value_type::second_type::LpRow, int>::type
1148 1148
    addRowSet(T &t, dummy<1> = 1) {
1149 1149
      int s=0;
1150 1150
      for(typename T::iterator i=t.begin();i!=t.end();++i) {
1151 1151
        i->second=addRow();
1152 1152
        s++;
1153 1153
      }
1154 1154
      return s;
1155 1155
    }
1156 1156
    template<class T>
1157 1157
    typename enable_if<typename T::MapIt::Value::LpRow, int>::type
1158 1158
    addRowSet(T &t, dummy<2> = 2) {
1159 1159
      int s=0;
1160 1160
      for(typename T::MapIt i(t); i!=INVALID; ++i)
1161 1161
        {
1162 1162
          i.set(addRow());
1163 1163
          s++;
1164 1164
        }
1165 1165
      return s;
1166 1166
    }
1167 1167
#endif
1168 1168

	
1169 1169
    ///Set a row (i.e a constraint) of the LP
1170 1170

	
1171 1171
    ///\param r is the row to be modified
1172 1172
    ///\param l is lower bound (-\ref INF means no bound)
1173 1173
    ///\param e is a linear expression (see \ref Expr)
1174 1174
    ///\param u is the upper bound (\ref INF means no bound)
1175 1175
    void row(Row r, Value l, const Expr &e, Value u) {
1176 1176
      e.simplify();
1177 1177
      _setRowCoeffs(rows(id(r)), ExprIterator(e.comps.begin(), cols),
1178 1178
                    ExprIterator(e.comps.end(), cols));
1179 1179
      _setRowLowerBound(rows(id(r)),l - *e);
1180 1180
      _setRowUpperBound(rows(id(r)),u - *e);
1181 1181
    }
1182 1182

	
1183 1183
    ///Set a row (i.e a constraint) of the LP
1184 1184

	
1185 1185
    ///\param r is the row to be modified
1186 1186
    ///\param c is a linear expression (see \ref Constr)
1187 1187
    void row(Row r, const Constr &c) {
1188 1188
      row(r, c.lowerBounded()?c.lowerBound():-INF,
1189 1189
          c.expr(), c.upperBounded()?c.upperBound():INF);
1190 1190
    }
1191 1191

	
1192 1192

	
1193 1193
    ///Get a row (i.e a constraint) of the LP
1194 1194

	
1195 1195
    ///\param r is the row to get
1196 1196
    ///\return the expression associated to the row
1197 1197
    Expr row(Row r) const {
1198 1198
      Expr e;
1199 1199
      _getRowCoeffs(rows(id(r)), InsertIterator(e.comps, cols));
1200 1200
      return e;
1201 1201
    }
1202 1202

	
1203 1203
    ///Add a new row (i.e a new constraint) to the LP
1204 1204

	
1205 1205
    ///\param l is the lower bound (-\ref INF means no bound)
1206 1206
    ///\param e is a linear expression (see \ref Expr)
1207 1207
    ///\param u is the upper bound (\ref INF means no bound)
1208 1208
    ///\return The created row.
1209 1209
    Row addRow(Value l,const Expr &e, Value u) {
1210 1210
      Row r=addRow();
1211 1211
      row(r,l,e,u);
1212 1212
      return r;
1213 1213
    }
1214 1214

	
1215 1215
    ///Add a new row (i.e a new constraint) to the LP
1216 1216

	
1217 1217
    ///\param c is a linear expression (see \ref Constr)
1218 1218
    ///\return The created row.
1219 1219
    Row addRow(const Constr &c) {
1220 1220
      Row r=addRow();
1221 1221
      row(r,c);
1222 1222
      return r;
1223 1223
    }
1224 1224
    ///Erase a column (i.e a variable) from the LP
1225 1225

	
1226 1226
    ///\param c is the column to be deleted
1227 1227
    void erase(Col c) {
1228 1228
      _eraseCol(cols(id(c)));
1229 1229
      _eraseColId(cols(id(c)));
1230 1230
    }
1231 1231
    ///Erase a row (i.e a constraint) from the LP
1232 1232

	
1233 1233
    ///\param r is the row to be deleted
1234 1234
    void erase(Row r) {
1235 1235
      _eraseRow(rows(id(r)));
1236 1236
      _eraseRowId(rows(id(r)));
1237 1237
    }
1238 1238

	
1239 1239
    /// Get the name of a column
1240 1240

	
1241 1241
    ///\param c is the coresponding column
1242 1242
    ///\return The name of the colunm
1243 1243
    std::string colName(Col c) const {
1244 1244
      std::string name;
1245 1245
      _getColName(cols(id(c)), name);
1246 1246
      return name;
1247 1247
    }
1248 1248

	
1249 1249
    /// Set the name of a column
1250 1250

	
1251 1251
    ///\param c is the coresponding column
1252 1252
    ///\param name The name to be given
1253 1253
    void colName(Col c, const std::string& name) {
1254 1254
      _setColName(cols(id(c)), name);
1255 1255
    }
1256 1256

	
1257 1257
    /// Get the column by its name
1258 1258

	
1259 1259
    ///\param name The name of the column
1260 1260
    ///\return the proper column or \c INVALID
1261 1261
    Col colByName(const std::string& name) const {
1262 1262
      int k = _colByName(name);
1263 1263
      return k != -1 ? Col(cols[k]) : Col(INVALID);
1264 1264
    }
... ...
@@ -1535,555 +1535,554 @@
1535 1535
    ///Query the direction of the optimization
1536 1536
    Sense sense() const {return _getSense(); }
1537 1537

	
1538 1538
    ///Set the sense to maximization
1539 1539
    void max() { _setSense(MAX); }
1540 1540

	
1541 1541
    ///Set the sense to maximization
1542 1542
    void min() { _setSense(MIN); }
1543 1543

	
1544 1544
    ///Clears the problem
1545 1545
    void clear() { _clear(); }
1546 1546

	
1547 1547
    /// Sets the message level of the solver
1548 1548
    void messageLevel(MessageLevel level) { _messageLevel(level); }
1549 1549

	
1550 1550
    ///@}
1551 1551

	
1552 1552
  };
1553 1553

	
1554 1554
  /// Addition
1555 1555

	
1556 1556
  ///\relates LpBase::Expr
1557 1557
  ///
1558 1558
  inline LpBase::Expr operator+(const LpBase::Expr &a, const LpBase::Expr &b) {
1559 1559
    LpBase::Expr tmp(a);
1560 1560
    tmp+=b;
1561 1561
    return tmp;
1562 1562
  }
1563 1563
  ///Substraction
1564 1564

	
1565 1565
  ///\relates LpBase::Expr
1566 1566
  ///
1567 1567
  inline LpBase::Expr operator-(const LpBase::Expr &a, const LpBase::Expr &b) {
1568 1568
    LpBase::Expr tmp(a);
1569 1569
    tmp-=b;
1570 1570
    return tmp;
1571 1571
  }
1572 1572
  ///Multiply with constant
1573 1573

	
1574 1574
  ///\relates LpBase::Expr
1575 1575
  ///
1576 1576
  inline LpBase::Expr operator*(const LpBase::Expr &a, const LpBase::Value &b) {
1577 1577
    LpBase::Expr tmp(a);
1578 1578
    tmp*=b;
1579 1579
    return tmp;
1580 1580
  }
1581 1581

	
1582 1582
  ///Multiply with constant
1583 1583

	
1584 1584
  ///\relates LpBase::Expr
1585 1585
  ///
1586 1586
  inline LpBase::Expr operator*(const LpBase::Value &a, const LpBase::Expr &b) {
1587 1587
    LpBase::Expr tmp(b);
1588 1588
    tmp*=a;
1589 1589
    return tmp;
1590 1590
  }
1591 1591
  ///Divide with constant
1592 1592

	
1593 1593
  ///\relates LpBase::Expr
1594 1594
  ///
1595 1595
  inline LpBase::Expr operator/(const LpBase::Expr &a, const LpBase::Value &b) {
1596 1596
    LpBase::Expr tmp(a);
1597 1597
    tmp/=b;
1598 1598
    return tmp;
1599 1599
  }
1600 1600

	
1601 1601
  ///Create constraint
1602 1602

	
1603 1603
  ///\relates LpBase::Constr
1604 1604
  ///
1605 1605
  inline LpBase::Constr operator<=(const LpBase::Expr &e,
1606 1606
                                   const LpBase::Expr &f) {
1607 1607
    return LpBase::Constr(0, f - e, LpBase::INF);
1608 1608
  }
1609 1609

	
1610 1610
  ///Create constraint
1611 1611

	
1612 1612
  ///\relates LpBase::Constr
1613 1613
  ///
1614 1614
  inline LpBase::Constr operator<=(const LpBase::Value &e,
1615 1615
                                   const LpBase::Expr &f) {
1616 1616
    return LpBase::Constr(e, f, LpBase::NaN);
1617 1617
  }
1618 1618

	
1619 1619
  ///Create constraint
1620 1620

	
1621 1621
  ///\relates LpBase::Constr
1622 1622
  ///
1623 1623
  inline LpBase::Constr operator<=(const LpBase::Expr &e,
1624 1624
                                   const LpBase::Value &f) {
1625 1625
    return LpBase::Constr(- LpBase::INF, e, f);
1626 1626
  }
1627 1627

	
1628 1628
  ///Create constraint
1629 1629

	
1630 1630
  ///\relates LpBase::Constr
1631 1631
  ///
1632 1632
  inline LpBase::Constr operator>=(const LpBase::Expr &e,
1633 1633
                                   const LpBase::Expr &f) {
1634 1634
    return LpBase::Constr(0, e - f, LpBase::INF);
1635 1635
  }
1636 1636

	
1637 1637

	
1638 1638
  ///Create constraint
1639 1639

	
1640 1640
  ///\relates LpBase::Constr
1641 1641
  ///
1642 1642
  inline LpBase::Constr operator>=(const LpBase::Value &e,
1643 1643
                                   const LpBase::Expr &f) {
1644 1644
    return LpBase::Constr(LpBase::NaN, f, e);
1645 1645
  }
1646 1646

	
1647 1647

	
1648 1648
  ///Create constraint
1649 1649

	
1650 1650
  ///\relates LpBase::Constr
1651 1651
  ///
1652 1652
  inline LpBase::Constr operator>=(const LpBase::Expr &e,
1653 1653
                                   const LpBase::Value &f) {
1654 1654
    return LpBase::Constr(f, e, LpBase::INF);
1655 1655
  }
1656 1656

	
1657 1657
  ///Create constraint
1658 1658

	
1659 1659
  ///\relates LpBase::Constr
1660 1660
  ///
1661 1661
  inline LpBase::Constr operator==(const LpBase::Expr &e,
1662 1662
                                   const LpBase::Value &f) {
1663 1663
    return LpBase::Constr(f, e, f);
1664 1664
  }
1665 1665

	
1666 1666
  ///Create constraint
1667 1667

	
1668 1668
  ///\relates LpBase::Constr
1669 1669
  ///
1670 1670
  inline LpBase::Constr operator==(const LpBase::Expr &e,
1671 1671
                                   const LpBase::Expr &f) {
1672 1672
    return LpBase::Constr(0, f - e, 0);
1673 1673
  }
1674 1674

	
1675 1675
  ///Create constraint
1676 1676

	
1677 1677
  ///\relates LpBase::Constr
1678 1678
  ///
1679 1679
  inline LpBase::Constr operator<=(const LpBase::Value &n,
1680 1680
                                   const LpBase::Constr &c) {
1681 1681
    LpBase::Constr tmp(c);
1682 1682
    LEMON_ASSERT(isNaN(tmp.lowerBound()), "Wrong LP constraint");
1683 1683
    tmp.lowerBound()=n;
1684 1684
    return tmp;
1685 1685
  }
1686 1686
  ///Create constraint
1687 1687

	
1688 1688
  ///\relates LpBase::Constr
1689 1689
  ///
1690 1690
  inline LpBase::Constr operator<=(const LpBase::Constr &c,
1691 1691
                                   const LpBase::Value &n)
1692 1692
  {
1693 1693
    LpBase::Constr tmp(c);
1694 1694
    LEMON_ASSERT(isNaN(tmp.upperBound()), "Wrong LP constraint");
1695 1695
    tmp.upperBound()=n;
1696 1696
    return tmp;
1697 1697
  }
1698 1698

	
1699 1699
  ///Create constraint
1700 1700

	
1701 1701
  ///\relates LpBase::Constr
1702 1702
  ///
1703 1703
  inline LpBase::Constr operator>=(const LpBase::Value &n,
1704 1704
                                   const LpBase::Constr &c) {
1705 1705
    LpBase::Constr tmp(c);
1706 1706
    LEMON_ASSERT(isNaN(tmp.upperBound()), "Wrong LP constraint");
1707 1707
    tmp.upperBound()=n;
1708 1708
    return tmp;
1709 1709
  }
1710 1710
  ///Create constraint
1711 1711

	
1712 1712
  ///\relates LpBase::Constr
1713 1713
  ///
1714 1714
  inline LpBase::Constr operator>=(const LpBase::Constr &c,
1715 1715
                                   const LpBase::Value &n)
1716 1716
  {
1717 1717
    LpBase::Constr tmp(c);
1718 1718
    LEMON_ASSERT(isNaN(tmp.lowerBound()), "Wrong LP constraint");
1719 1719
    tmp.lowerBound()=n;
1720 1720
    return tmp;
1721 1721
  }
1722 1722

	
1723 1723
  ///Addition
1724 1724

	
1725 1725
  ///\relates LpBase::DualExpr
1726 1726
  ///
1727 1727
  inline LpBase::DualExpr operator+(const LpBase::DualExpr &a,
1728 1728
                                    const LpBase::DualExpr &b) {
1729 1729
    LpBase::DualExpr tmp(a);
1730 1730
    tmp+=b;
1731 1731
    return tmp;
1732 1732
  }
1733 1733
  ///Substraction
1734 1734

	
1735 1735
  ///\relates LpBase::DualExpr
1736 1736
  ///
1737 1737
  inline LpBase::DualExpr operator-(const LpBase::DualExpr &a,
1738 1738
                                    const LpBase::DualExpr &b) {
1739 1739
    LpBase::DualExpr tmp(a);
1740 1740
    tmp-=b;
1741 1741
    return tmp;
1742 1742
  }
1743 1743
  ///Multiply with constant
1744 1744

	
1745 1745
  ///\relates LpBase::DualExpr
1746 1746
  ///
1747 1747
  inline LpBase::DualExpr operator*(const LpBase::DualExpr &a,
1748 1748
                                    const LpBase::Value &b) {
1749 1749
    LpBase::DualExpr tmp(a);
1750 1750
    tmp*=b;
1751 1751
    return tmp;
1752 1752
  }
1753 1753

	
1754 1754
  ///Multiply with constant
1755 1755

	
1756 1756
  ///\relates LpBase::DualExpr
1757 1757
  ///
1758 1758
  inline LpBase::DualExpr operator*(const LpBase::Value &a,
1759 1759
                                    const LpBase::DualExpr &b) {
1760 1760
    LpBase::DualExpr tmp(b);
1761 1761
    tmp*=a;
1762 1762
    return tmp;
1763 1763
  }
1764 1764
  ///Divide with constant
1765 1765

	
1766 1766
  ///\relates LpBase::DualExpr
1767 1767
  ///
1768 1768
  inline LpBase::DualExpr operator/(const LpBase::DualExpr &a,
1769 1769
                                    const LpBase::Value &b) {
1770 1770
    LpBase::DualExpr tmp(a);
1771 1771
    tmp/=b;
1772 1772
    return tmp;
1773 1773
  }
1774 1774

	
1775 1775
  /// \ingroup lp_group
1776 1776
  ///
1777 1777
  /// \brief Common base class for LP solvers
1778 1778
  ///
1779 1779
  /// This class is an abstract base class for LP solvers. This class
1780 1780
  /// provides a full interface for set and modify an LP problem,
1781 1781
  /// solve it and retrieve the solution. You can use one of the
1782 1782
  /// descendants as a concrete implementation, or the \c Lp
1783 1783
  /// default LP solver. However, if you would like to handle LP
1784 1784
  /// solvers as reference or pointer in a generic way, you can use
1785 1785
  /// this class directly.
1786 1786
  class LpSolver : virtual public LpBase {
1787 1787
  public:
1788 1788

	
1789 1789
    /// The problem types for primal and dual problems
1790 1790
    enum ProblemType {
1791
      ///Feasible solution hasn't been found (but may exist).
1791
      /// = 0. Feasible solution hasn't been found (but may exist).
1792 1792
      UNDEFINED = 0,
1793
      ///The problem has no feasible solution
1793
      /// = 1. The problem has no feasible solution.
1794 1794
      INFEASIBLE = 1,
1795
      ///Feasible solution found
1795
      /// = 2. Feasible solution found.
1796 1796
      FEASIBLE = 2,
1797
      ///Optimal solution exists and found
1797
      /// = 3. Optimal solution exists and found.
1798 1798
      OPTIMAL = 3,
1799
      ///The cost function is unbounded
1799
      /// = 4. The cost function is unbounded.
1800 1800
      UNBOUNDED = 4
1801 1801
    };
1802 1802

	
1803 1803
    ///The basis status of variables
1804 1804
    enum VarStatus {
1805 1805
      /// The variable is in the basis
1806 1806
      BASIC, 
1807 1807
      /// The variable is free, but not basic
1808 1808
      FREE,
1809 1809
      /// The variable has active lower bound 
1810 1810
      LOWER,
1811 1811
      /// The variable has active upper bound
1812 1812
      UPPER,
1813 1813
      /// The variable is non-basic and fixed
1814 1814
      FIXED
1815 1815
    };
1816 1816

	
1817 1817
  protected:
1818 1818

	
1819 1819
    virtual SolveExitStatus _solve() = 0;
1820 1820

	
1821 1821
    virtual Value _getPrimal(int i) const = 0;
1822 1822
    virtual Value _getDual(int i) const = 0;
1823 1823

	
1824 1824
    virtual Value _getPrimalRay(int i) const = 0;
1825 1825
    virtual Value _getDualRay(int i) const = 0;
1826 1826

	
1827 1827
    virtual Value _getPrimalValue() const = 0;
1828 1828

	
1829 1829
    virtual VarStatus _getColStatus(int i) const = 0;
1830 1830
    virtual VarStatus _getRowStatus(int i) const = 0;
1831 1831

	
1832 1832
    virtual ProblemType _getPrimalType() const = 0;
1833 1833
    virtual ProblemType _getDualType() const = 0;
1834 1834

	
1835 1835
  public:
1836 1836

	
1837 1837
    ///Allocate a new LP problem instance
1838 1838
    virtual LpSolver* newSolver() const = 0;
1839 1839
    ///Make a copy of the LP problem
1840 1840
    virtual LpSolver* cloneSolver() const = 0;
1841 1841

	
1842 1842
    ///\name Solve the LP
1843 1843

	
1844 1844
    ///@{
1845 1845

	
1846 1846
    ///\e Solve the LP problem at hand
1847 1847
    ///
1848 1848
    ///\return The result of the optimization procedure. Possible
1849 1849
    ///values and their meanings can be found in the documentation of
1850 1850
    ///\ref SolveExitStatus.
1851 1851
    SolveExitStatus solve() { return _solve(); }
1852 1852

	
1853 1853
    ///@}
1854 1854

	
1855
    ///\name Obtain the solution
1855
    ///\name Obtain the Solution
1856 1856

	
1857 1857
    ///@{
1858 1858

	
1859 1859
    /// The type of the primal problem
1860 1860
    ProblemType primalType() const {
1861 1861
      return _getPrimalType();
1862 1862
    }
1863 1863

	
1864 1864
    /// The type of the dual problem
1865 1865
    ProblemType dualType() const {
1866 1866
      return _getDualType();
1867 1867
    }
1868 1868

	
1869 1869
    /// Return the primal value of the column
1870 1870

	
1871 1871
    /// Return the primal value of the column.
1872 1872
    /// \pre The problem is solved.
1873 1873
    Value primal(Col c) const { return _getPrimal(cols(id(c))); }
1874 1874

	
1875 1875
    /// Return the primal value of the expression
1876 1876

	
1877 1877
    /// Return the primal value of the expression, i.e. the dot
1878 1878
    /// product of the primal solution and the expression.
1879 1879
    /// \pre The problem is solved.
1880 1880
    Value primal(const Expr& e) const {
1881 1881
      double res = *e;
1882 1882
      for (Expr::ConstCoeffIt c(e); c != INVALID; ++c) {
1883 1883
        res += *c * primal(c);
1884 1884
      }
1885 1885
      return res;
1886 1886
    }
1887 1887
    /// Returns a component of the primal ray
1888 1888
    
1889 1889
    /// The primal ray is solution of the modified primal problem,
1890 1890
    /// where we change each finite bound to 0, and we looking for a
1891 1891
    /// negative objective value in case of minimization, and positive
1892 1892
    /// objective value for maximization. If there is such solution,
1893 1893
    /// that proofs the unsolvability of the dual problem, and if a
1894 1894
    /// feasible primal solution exists, then the unboundness of
1895 1895
    /// primal problem.
1896 1896
    ///
1897 1897
    /// \pre The problem is solved and the dual problem is infeasible.
1898 1898
    /// \note Some solvers does not provide primal ray calculation
1899 1899
    /// functions.
1900 1900
    Value primalRay(Col c) const { return _getPrimalRay(cols(id(c))); }
1901 1901

	
1902 1902
    /// Return the dual value of the row
1903 1903

	
1904 1904
    /// Return the dual value of the row.
1905 1905
    /// \pre The problem is solved.
1906 1906
    Value dual(Row r) const { return _getDual(rows(id(r))); }
1907 1907

	
1908 1908
    /// Return the dual value of the dual expression
1909 1909

	
1910 1910
    /// Return the dual value of the dual expression, i.e. the dot
1911 1911
    /// product of the dual solution and the dual expression.
1912 1912
    /// \pre The problem is solved.
1913 1913
    Value dual(const DualExpr& e) const {
1914 1914
      double res = 0.0;
1915 1915
      for (DualExpr::ConstCoeffIt r(e); r != INVALID; ++r) {
1916 1916
        res += *r * dual(r);
1917 1917
      }
1918 1918
      return res;
1919 1919
    }
1920 1920

	
1921 1921
    /// Returns a component of the dual ray
1922 1922
    
1923 1923
    /// The dual ray is solution of the modified primal problem, where
1924 1924
    /// we change each finite bound to 0 (i.e. the objective function
1925 1925
    /// coefficients in the primal problem), and we looking for a
1926 1926
    /// ositive objective value. If there is such solution, that
1927 1927
    /// proofs the unsolvability of the primal problem, and if a
1928 1928
    /// feasible dual solution exists, then the unboundness of
1929 1929
    /// dual problem.
1930 1930
    ///
1931 1931
    /// \pre The problem is solved and the primal problem is infeasible.
1932 1932
    /// \note Some solvers does not provide dual ray calculation
1933 1933
    /// functions.
1934 1934
    Value dualRay(Row r) const { return _getDualRay(rows(id(r))); }
1935 1935

	
1936 1936
    /// Return the basis status of the column
1937 1937

	
1938 1938
    /// \see VarStatus
1939 1939
    VarStatus colStatus(Col c) const { return _getColStatus(cols(id(c))); }
1940 1940

	
1941 1941
    /// Return the basis status of the row
1942 1942

	
1943 1943
    /// \see VarStatus
1944 1944
    VarStatus rowStatus(Row r) const { return _getRowStatus(rows(id(r))); }
1945 1945

	
1946 1946
    ///The value of the objective function
1947 1947

	
1948 1948
    ///\return
1949 1949
    ///- \ref INF or -\ref INF means either infeasibility or unboundedness
1950 1950
    /// of the primal problem, depending on whether we minimize or maximize.
1951 1951
    ///- \ref NaN if no primal solution is found.
1952 1952
    ///- The (finite) objective value if an optimal solution is found.
1953 1953
    Value primal() const { return _getPrimalValue()+obj_const_comp;}
1954 1954
    ///@}
1955 1955

	
1956 1956
  protected:
1957 1957

	
1958 1958
  };
1959 1959

	
1960 1960

	
1961 1961
  /// \ingroup lp_group
1962 1962
  ///
1963 1963
  /// \brief Common base class for MIP solvers
1964 1964
  ///
1965 1965
  /// This class is an abstract base class for MIP solvers. This class
1966 1966
  /// provides a full interface for set and modify an MIP problem,
1967 1967
  /// solve it and retrieve the solution. You can use one of the
1968 1968
  /// descendants as a concrete implementation, or the \c Lp
1969 1969
  /// default MIP solver. However, if you would like to handle MIP
1970 1970
  /// solvers as reference or pointer in a generic way, you can use
1971 1971
  /// this class directly.
1972 1972
  class MipSolver : virtual public LpBase {
1973 1973
  public:
1974 1974

	
1975 1975
    /// The problem types for MIP problems
1976 1976
    enum ProblemType {
1977
      ///Feasible solution hasn't been found (but may exist).
1977
      /// = 0. Feasible solution hasn't been found (but may exist).
1978 1978
      UNDEFINED = 0,
1979
      ///The problem has no feasible solution
1979
      /// = 1. The problem has no feasible solution.
1980 1980
      INFEASIBLE = 1,
1981
      ///Feasible solution found
1981
      /// = 2. Feasible solution found.
1982 1982
      FEASIBLE = 2,
1983
      ///Optimal solution exists and found
1983
      /// = 3. Optimal solution exists and found.
1984 1984
      OPTIMAL = 3,
1985
      ///The cost function is unbounded
1986
      ///
1987
      ///The Mip or at least the relaxed problem is unbounded
1985
      /// = 4. The cost function is unbounded.
1986
      ///The Mip or at least the relaxed problem is unbounded.
1988 1987
      UNBOUNDED = 4
1989 1988
    };
1990 1989

	
1991 1990
    ///Allocate a new MIP problem instance
1992 1991
    virtual MipSolver* newSolver() const = 0;
1993 1992
    ///Make a copy of the MIP problem
1994 1993
    virtual MipSolver* cloneSolver() const = 0;
1995 1994

	
1996 1995
    ///\name Solve the MIP
1997 1996

	
1998 1997
    ///@{
1999 1998

	
2000 1999
    /// Solve the MIP problem at hand
2001 2000
    ///
2002 2001
    ///\return The result of the optimization procedure. Possible
2003 2002
    ///values and their meanings can be found in the documentation of
2004 2003
    ///\ref SolveExitStatus.
2005 2004
    SolveExitStatus solve() { return _solve(); }
2006 2005

	
2007 2006
    ///@}
2008 2007

	
2009
    ///\name Setting column type
2008
    ///\name Set Column Type
2010 2009
    ///@{
2011 2010

	
2012 2011
    ///Possible variable (column) types (e.g. real, integer, binary etc.)
2013 2012
    enum ColTypes {
2014
      ///Continuous variable (default)
2013
      /// = 0. Continuous variable (default).
2015 2014
      REAL = 0,
2016
      ///Integer variable
2015
      /// = 1. Integer variable.
2017 2016
      INTEGER = 1
2018 2017
    };
2019 2018

	
2020 2019
    ///Sets the type of the given column to the given type
2021 2020

	
2022 2021
    ///Sets the type of the given column to the given type.
2023 2022
    ///
2024 2023
    void colType(Col c, ColTypes col_type) {
2025 2024
      _setColType(cols(id(c)),col_type);
2026 2025
    }
2027 2026

	
2028 2027
    ///Gives back the type of the column.
2029 2028

	
2030 2029
    ///Gives back the type of the column.
2031 2030
    ///
2032 2031
    ColTypes colType(Col c) const {
2033 2032
      return _getColType(cols(id(c)));
2034 2033
    }
2035 2034
    ///@}
2036 2035

	
2037
    ///\name Obtain the solution
2036
    ///\name Obtain the Solution
2038 2037

	
2039 2038
    ///@{
2040 2039

	
2041 2040
    /// The type of the MIP problem
2042 2041
    ProblemType type() const {
2043 2042
      return _getType();
2044 2043
    }
2045 2044

	
2046 2045
    /// Return the value of the row in the solution
2047 2046

	
2048 2047
    ///  Return the value of the row in the solution.
2049 2048
    /// \pre The problem is solved.
2050 2049
    Value sol(Col c) const { return _getSol(cols(id(c))); }
2051 2050

	
2052 2051
    /// Return the value of the expression in the solution
2053 2052

	
2054 2053
    /// Return the value of the expression in the solution, i.e. the
2055 2054
    /// dot product of the solution and the expression.
2056 2055
    /// \pre The problem is solved.
2057 2056
    Value sol(const Expr& e) const {
2058 2057
      double res = *e;
2059 2058
      for (Expr::ConstCoeffIt c(e); c != INVALID; ++c) {
2060 2059
        res += *c * sol(c);
2061 2060
      }
2062 2061
      return res;
2063 2062
    }
2064 2063
    ///The value of the objective function
2065 2064
    
2066 2065
    ///\return
2067 2066
    ///- \ref INF or -\ref INF means either infeasibility or unboundedness
2068 2067
    /// of the problem, depending on whether we minimize or maximize.
2069 2068
    ///- \ref NaN if no primal solution is found.
2070 2069
    ///- The (finite) objective value if an optimal solution is found.
2071 2070
    Value solValue() const { return _getSolValue()+obj_const_comp;}
2072 2071
    ///@}
2073 2072

	
2074 2073
  protected:
2075 2074

	
2076 2075
    virtual SolveExitStatus _solve() = 0;
2077 2076
    virtual ColTypes _getColType(int col) const = 0;
2078 2077
    virtual void _setColType(int col, ColTypes col_type) = 0;
2079 2078
    virtual ProblemType _getType() const = 0;
2080 2079
    virtual Value _getSol(int i) const = 0;
2081 2080
    virtual Value _getSolValue() const = 0;
2082 2081

	
2083 2082
  };
2084 2083

	
2085 2084

	
2086 2085

	
2087 2086
} //namespace lemon
2088 2087

	
2089 2088
#endif //LEMON_LP_BASE_H
Ignore white space 6 line context
... ...
@@ -2475,308 +2475,308 @@
2475 2475
  /// This map returns the in-degree of a node. Once it is constructed,
2476 2476
  /// the degrees are stored in a standard \c NodeMap, so each query is done
2477 2477
  /// in constant time. On the other hand, the values are updated automatically
2478 2478
  /// whenever the digraph changes.
2479 2479
  ///
2480 2480
  /// \warning Besides \c addNode() and \c addArc(), a digraph structure 
2481 2481
  /// may provide alternative ways to modify the digraph.
2482 2482
  /// The correct behavior of InDegMap is not guarantied if these additional
2483 2483
  /// features are used. For example the functions
2484 2484
  /// \ref ListDigraph::changeSource() "changeSource()",
2485 2485
  /// \ref ListDigraph::changeTarget() "changeTarget()" and
2486 2486
  /// \ref ListDigraph::reverseArc() "reverseArc()"
2487 2487
  /// of \ref ListDigraph will \e not update the degree values correctly.
2488 2488
  ///
2489 2489
  /// \sa OutDegMap
2490 2490
  template <typename GR>
2491 2491
  class InDegMap
2492 2492
    : protected ItemSetTraits<GR, typename GR::Arc>
2493 2493
      ::ItemNotifier::ObserverBase {
2494 2494

	
2495 2495
  public:
2496 2496
    
2497 2497
    /// The digraph type
2498 2498
    typedef GR Digraph;
2499 2499
    /// The key type
2500 2500
    typedef typename Digraph::Node Key;
2501 2501
    /// The value type
2502 2502
    typedef int Value;
2503 2503

	
2504 2504
    typedef typename ItemSetTraits<Digraph, typename Digraph::Arc>
2505 2505
    ::ItemNotifier::ObserverBase Parent;
2506 2506

	
2507 2507
  private:
2508 2508

	
2509 2509
    class AutoNodeMap
2510 2510
      : public ItemSetTraits<Digraph, Key>::template Map<int>::Type {
2511 2511
    public:
2512 2512

	
2513 2513
      typedef typename ItemSetTraits<Digraph, Key>::
2514 2514
      template Map<int>::Type Parent;
2515 2515

	
2516 2516
      AutoNodeMap(const Digraph& digraph) : Parent(digraph, 0) {}
2517 2517

	
2518 2518
      virtual void add(const Key& key) {
2519 2519
        Parent::add(key);
2520 2520
        Parent::set(key, 0);
2521 2521
      }
2522 2522

	
2523 2523
      virtual void add(const std::vector<Key>& keys) {
2524 2524
        Parent::add(keys);
2525 2525
        for (int i = 0; i < int(keys.size()); ++i) {
2526 2526
          Parent::set(keys[i], 0);
2527 2527
        }
2528 2528
      }
2529 2529

	
2530 2530
      virtual void build() {
2531 2531
        Parent::build();
2532 2532
        Key it;
2533 2533
        typename Parent::Notifier* nf = Parent::notifier();
2534 2534
        for (nf->first(it); it != INVALID; nf->next(it)) {
2535 2535
          Parent::set(it, 0);
2536 2536
        }
2537 2537
      }
2538 2538
    };
2539 2539

	
2540 2540
  public:
2541 2541

	
2542 2542
    /// \brief Constructor.
2543 2543
    ///
2544 2544
    /// Constructor for creating an in-degree map.
2545 2545
    explicit InDegMap(const Digraph& graph)
2546 2546
      : _digraph(graph), _deg(graph) {
2547 2547
      Parent::attach(_digraph.notifier(typename Digraph::Arc()));
2548 2548

	
2549 2549
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2550 2550
        _deg[it] = countInArcs(_digraph, it);
2551 2551
      }
2552 2552
    }
2553 2553

	
2554 2554
    /// \brief Gives back the in-degree of a Node.
2555 2555
    ///
2556 2556
    /// Gives back the in-degree of a Node.
2557 2557
    int operator[](const Key& key) const {
2558 2558
      return _deg[key];
2559 2559
    }
2560 2560

	
2561 2561
  protected:
2562 2562

	
2563 2563
    typedef typename Digraph::Arc Arc;
2564 2564

	
2565 2565
    virtual void add(const Arc& arc) {
2566 2566
      ++_deg[_digraph.target(arc)];
2567 2567
    }
2568 2568

	
2569 2569
    virtual void add(const std::vector<Arc>& arcs) {
2570 2570
      for (int i = 0; i < int(arcs.size()); ++i) {
2571 2571
        ++_deg[_digraph.target(arcs[i])];
2572 2572
      }
2573 2573
    }
2574 2574

	
2575 2575
    virtual void erase(const Arc& arc) {
2576 2576
      --_deg[_digraph.target(arc)];
2577 2577
    }
2578 2578

	
2579 2579
    virtual void erase(const std::vector<Arc>& arcs) {
2580 2580
      for (int i = 0; i < int(arcs.size()); ++i) {
2581 2581
        --_deg[_digraph.target(arcs[i])];
2582 2582
      }
2583 2583
    }
2584 2584

	
2585 2585
    virtual void build() {
2586 2586
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2587 2587
        _deg[it] = countInArcs(_digraph, it);
2588 2588
      }
2589 2589
    }
2590 2590

	
2591 2591
    virtual void clear() {
2592 2592
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2593 2593
        _deg[it] = 0;
2594 2594
      }
2595 2595
    }
2596 2596
  private:
2597 2597

	
2598 2598
    const Digraph& _digraph;
2599 2599
    AutoNodeMap _deg;
2600 2600
  };
2601 2601

	
2602 2602
  /// \brief Map of the out-degrees of nodes in a digraph.
2603 2603
  ///
2604 2604
  /// This map returns the out-degree of a node. Once it is constructed,
2605 2605
  /// the degrees are stored in a standard \c NodeMap, so each query is done
2606 2606
  /// in constant time. On the other hand, the values are updated automatically
2607 2607
  /// whenever the digraph changes.
2608 2608
  ///
2609 2609
  /// \warning Besides \c addNode() and \c addArc(), a digraph structure 
2610 2610
  /// may provide alternative ways to modify the digraph.
2611 2611
  /// The correct behavior of OutDegMap is not guarantied if these additional
2612 2612
  /// features are used. For example the functions
2613 2613
  /// \ref ListDigraph::changeSource() "changeSource()",
2614 2614
  /// \ref ListDigraph::changeTarget() "changeTarget()" and
2615 2615
  /// \ref ListDigraph::reverseArc() "reverseArc()"
2616 2616
  /// of \ref ListDigraph will \e not update the degree values correctly.
2617 2617
  ///
2618 2618
  /// \sa InDegMap
2619 2619
  template <typename GR>
2620 2620
  class OutDegMap
2621 2621
    : protected ItemSetTraits<GR, typename GR::Arc>
2622 2622
      ::ItemNotifier::ObserverBase {
2623 2623

	
2624 2624
  public:
2625 2625

	
2626 2626
    /// The digraph type
2627 2627
    typedef GR Digraph;
2628 2628
    /// The key type
2629 2629
    typedef typename Digraph::Node Key;
2630 2630
    /// The value type
2631 2631
    typedef int Value;
2632 2632

	
2633 2633
    typedef typename ItemSetTraits<Digraph, typename Digraph::Arc>
2634 2634
    ::ItemNotifier::ObserverBase Parent;
2635 2635

	
2636 2636
  private:
2637 2637

	
2638 2638
    class AutoNodeMap
2639 2639
      : public ItemSetTraits<Digraph, Key>::template Map<int>::Type {
2640 2640
    public:
2641 2641

	
2642 2642
      typedef typename ItemSetTraits<Digraph, Key>::
2643 2643
      template Map<int>::Type Parent;
2644 2644

	
2645 2645
      AutoNodeMap(const Digraph& digraph) : Parent(digraph, 0) {}
2646 2646

	
2647 2647
      virtual void add(const Key& key) {
2648 2648
        Parent::add(key);
2649 2649
        Parent::set(key, 0);
2650 2650
      }
2651 2651
      virtual void add(const std::vector<Key>& keys) {
2652 2652
        Parent::add(keys);
2653 2653
        for (int i = 0; i < int(keys.size()); ++i) {
2654 2654
          Parent::set(keys[i], 0);
2655 2655
        }
2656 2656
      }
2657 2657
      virtual void build() {
2658 2658
        Parent::build();
2659 2659
        Key it;
2660 2660
        typename Parent::Notifier* nf = Parent::notifier();
2661 2661
        for (nf->first(it); it != INVALID; nf->next(it)) {
2662 2662
          Parent::set(it, 0);
2663 2663
        }
2664 2664
      }
2665 2665
    };
2666 2666

	
2667 2667
  public:
2668 2668

	
2669 2669
    /// \brief Constructor.
2670 2670
    ///
2671 2671
    /// Constructor for creating an out-degree map.
2672 2672
    explicit OutDegMap(const Digraph& graph)
2673 2673
      : _digraph(graph), _deg(graph) {
2674 2674
      Parent::attach(_digraph.notifier(typename Digraph::Arc()));
2675 2675

	
2676 2676
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2677 2677
        _deg[it] = countOutArcs(_digraph, it);
2678 2678
      }
2679 2679
    }
2680 2680

	
2681 2681
    /// \brief Gives back the out-degree of a Node.
2682 2682
    ///
2683 2683
    /// Gives back the out-degree of a Node.
2684 2684
    int operator[](const Key& key) const {
2685 2685
      return _deg[key];
2686 2686
    }
2687 2687

	
2688 2688
  protected:
2689 2689

	
2690 2690
    typedef typename Digraph::Arc Arc;
2691 2691

	
2692 2692
    virtual void add(const Arc& arc) {
2693 2693
      ++_deg[_digraph.source(arc)];
2694 2694
    }
2695 2695

	
2696 2696
    virtual void add(const std::vector<Arc>& arcs) {
2697 2697
      for (int i = 0; i < int(arcs.size()); ++i) {
2698 2698
        ++_deg[_digraph.source(arcs[i])];
2699 2699
      }
2700 2700
    }
2701 2701

	
2702 2702
    virtual void erase(const Arc& arc) {
2703 2703
      --_deg[_digraph.source(arc)];
2704 2704
    }
2705 2705

	
2706 2706
    virtual void erase(const std::vector<Arc>& arcs) {
2707 2707
      for (int i = 0; i < int(arcs.size()); ++i) {
2708 2708
        --_deg[_digraph.source(arcs[i])];
2709 2709
      }
2710 2710
    }
2711 2711

	
2712 2712
    virtual void build() {
2713 2713
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2714 2714
        _deg[it] = countOutArcs(_digraph, it);
2715 2715
      }
2716 2716
    }
2717 2717

	
2718 2718
    virtual void clear() {
2719 2719
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2720 2720
        _deg[it] = 0;
2721 2721
      }
2722 2722
    }
2723 2723
  private:
2724 2724

	
2725 2725
    const Digraph& _digraph;
2726 2726
    AutoNodeMap _deg;
2727 2727
  };
2728 2728

	
2729 2729
  /// \brief Potential difference map
2730 2730
  ///
2731
  /// PotentialMap returns the difference between the potentials of the
2732
  /// source and target nodes of each arc in a digraph, i.e. it returns
2731
  /// PotentialDifferenceMap returns the difference between the potentials of
2732
  /// the source and target nodes of each arc in a digraph, i.e. it returns
2733 2733
  /// \code
2734 2734
  ///   potential[gr.target(arc)] - potential[gr.source(arc)].
2735 2735
  /// \endcode
2736 2736
  /// \tparam GR The digraph type.
2737 2737
  /// \tparam POT A node map storing the potentials.
2738 2738
  template <typename GR, typename POT>
2739 2739
  class PotentialDifferenceMap {
2740 2740
  public:
2741 2741
    /// Key type
2742 2742
    typedef typename GR::Arc Key;
2743 2743
    /// Value type
2744 2744
    typedef typename POT::Value Value;
2745 2745

	
2746 2746
    /// \brief Constructor
2747 2747
    ///
2748 2748
    /// Contructor of the map.
2749 2749
    explicit PotentialDifferenceMap(const GR& gr,
2750 2750
                                    const POT& potential)
2751 2751
      : _digraph(gr), _potential(potential) {}
2752 2752

	
2753 2753
    /// \brief Returns the potential difference for the given arc.
2754 2754
    ///
2755 2755
    /// Returns the potential difference for the given arc, i.e.
2756 2756
    /// \code
2757 2757
    ///   potential[gr.target(arc)] - potential[gr.source(arc)].
2758 2758
    /// \endcode
2759 2759
    Value operator[](const Key& arc) const {
2760 2760
      return _potential[_digraph.target(arc)] -
2761 2761
        _potential[_digraph.source(arc)];
2762 2762
    }
2763 2763

	
2764 2764
  private:
2765 2765
    const GR& _digraph;
2766 2766
    const POT& _potential;
2767 2767
  };
2768 2768

	
2769 2769
  /// \brief Returns a PotentialDifferenceMap.
2770 2770
  ///
2771 2771
  /// This function just returns a PotentialDifferenceMap.
2772 2772
  /// \relates PotentialDifferenceMap
2773 2773
  template <typename GR, typename POT>
2774 2774
  PotentialDifferenceMap<GR, POT>
2775 2775
  potentialDifferenceMap(const GR& gr, const POT& potential) {
2776 2776
    return PotentialDifferenceMap<GR, POT>(gr, potential);
2777 2777
  }
2778 2778

	
2779 2779
  /// @}
2780 2780
}
2781 2781

	
2782 2782
#endif // LEMON_MAPS_H
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_MIN_COST_ARBORESCENCE_H
20 20
#define LEMON_MIN_COST_ARBORESCENCE_H
21 21

	
22 22
///\ingroup spantree
23 23
///\file
24 24
///\brief Minimum Cost Arborescence algorithm.
25 25

	
26 26
#include <vector>
27 27

	
28 28
#include <lemon/list_graph.h>
29 29
#include <lemon/bin_heap.h>
30 30
#include <lemon/assert.h>
31 31

	
32 32
namespace lemon {
33 33

	
34 34

	
35 35
  /// \brief Default traits class for MinCostArborescence class.
36 36
  ///
37 37
  /// Default traits class for MinCostArborescence class.
38 38
  /// \param GR Digraph type.
39 39
  /// \param CM Type of cost map.
40 40
  template <class GR, class CM>
41 41
  struct MinCostArborescenceDefaultTraits{
42 42

	
43 43
    /// \brief The digraph type the algorithm runs on.
44 44
    typedef GR Digraph;
45 45

	
46 46
    /// \brief The type of the map that stores the arc costs.
47 47
    ///
48 48
    /// The type of the map that stores the arc costs.
49 49
    /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
50 50
    typedef CM CostMap;
51 51

	
52 52
    /// \brief The value type of the costs.
53 53
    ///
54 54
    /// The value type of the costs.
55 55
    typedef typename CostMap::Value Value;
56 56

	
57 57
    /// \brief The type of the map that stores which arcs are in the
58 58
    /// arborescence.
59 59
    ///
60 60
    /// The type of the map that stores which arcs are in the
61 61
    /// arborescence.  It must meet the \ref concepts::WriteMap
62 62
    /// "WriteMap" concept.  Initially it will be set to false on each
63 63
    /// arc. After it will set all arborescence arcs once.
64 64
    typedef typename Digraph::template ArcMap<bool> ArborescenceMap;
65 65

	
66 66
    /// \brief Instantiates a \c ArborescenceMap.
67 67
    ///
68 68
    /// This function instantiates a \c ArborescenceMap.
69 69
    /// \param digraph is the graph, to which we would like to
70 70
    /// calculate the \c ArborescenceMap.
71 71
    static ArborescenceMap *createArborescenceMap(const Digraph &digraph){
72 72
      return new ArborescenceMap(digraph);
73 73
    }
74 74

	
75 75
    /// \brief The type of the \c PredMap
76 76
    ///
77 77
    /// The type of the \c PredMap. It is a node map with an arc value type.
78 78
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
79 79

	
80 80
    /// \brief Instantiates a \c PredMap.
81 81
    ///
82 82
    /// This function instantiates a \c PredMap.
83 83
    /// \param digraph The digraph to which we would like to define the
84 84
    /// \c PredMap.
85 85
    static PredMap *createPredMap(const Digraph &digraph){
86 86
      return new PredMap(digraph);
87 87
    }
88 88

	
89 89
  };
90 90

	
91 91
  /// \ingroup spantree
92 92
  ///
93
  /// \brief %MinCostArborescence algorithm class.
93
  /// \brief Minimum Cost Arborescence algorithm class.
94 94
  ///
95 95
  /// This class provides an efficient implementation of
96
  /// %MinCostArborescence algorithm. The arborescence is a tree
96
  /// Minimum Cost Arborescence algorithm. The arborescence is a tree
97 97
  /// which is directed from a given source node of the digraph. One or
98 98
  /// more sources should be given for the algorithm and it will calculate
99 99
  /// the minimum cost subgraph which are union of arborescences with the
100 100
  /// given sources and spans all the nodes which are reachable from the
101 101
  /// sources. The time complexity of the algorithm is O(n<sup>2</sup>+e).
102 102
  ///
103 103
  /// The algorithm provides also an optimal dual solution, therefore
104 104
  /// the optimality of the solution can be checked.
105 105
  ///
106 106
  /// \param GR The digraph type the algorithm runs on. The default value
107 107
  /// is \ref ListDigraph.
108 108
  /// \param CM This read-only ArcMap determines the costs of the
109 109
  /// arcs. It is read once for each arc, so the map may involve in
110 110
  /// relatively time consuming process to compute the arc cost if
111 111
  /// it is necessary. The default map type is \ref
112 112
  /// concepts::Digraph::ArcMap "Digraph::ArcMap<int>".
113 113
  /// \param TR Traits class to set various data types used
114 114
  /// by the algorithm. The default traits class is
115 115
  /// \ref MinCostArborescenceDefaultTraits
116 116
  /// "MinCostArborescenceDefaultTraits<GR, CM>".  See \ref
117 117
  /// MinCostArborescenceDefaultTraits for the documentation of a
118 118
  /// MinCostArborescence traits class.
119 119
#ifndef DOXYGEN
120 120
  template <typename GR = ListDigraph,
121 121
            typename CM = typename GR::template ArcMap<int>,
122 122
            typename TR =
123 123
              MinCostArborescenceDefaultTraits<GR, CM> >
124 124
#else
125 125
  template <typename GR, typename CM, typedef TR>
126 126
#endif
127 127
  class MinCostArborescence {
128 128
  public:
129 129

	
130 130
    /// The traits.
131 131
    typedef TR Traits;
132 132
    /// The type of the underlying digraph.
133 133
    typedef typename Traits::Digraph Digraph;
134 134
    /// The type of the map that stores the arc costs.
135 135
    typedef typename Traits::CostMap CostMap;
136 136
    ///The type of the costs of the arcs.
137 137
    typedef typename Traits::Value Value;
138 138
    ///The type of the predecessor map.
139 139
    typedef typename Traits::PredMap PredMap;
140 140
    ///The type of the map that stores which arcs are in the arborescence.
141 141
    typedef typename Traits::ArborescenceMap ArborescenceMap;
142 142

	
143 143
    typedef MinCostArborescence Create;
144 144

	
145 145
  private:
146 146

	
147 147
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
148 148

	
149 149
    struct CostArc {
150 150

	
151 151
      Arc arc;
152 152
      Value value;
153 153

	
154 154
      CostArc() {}
155 155
      CostArc(Arc _arc, Value _value) : arc(_arc), value(_value) {}
156 156

	
157 157
    };
158 158

	
159 159
    const Digraph *_digraph;
160 160
    const CostMap *_cost;
161 161

	
162 162
    PredMap *_pred;
163 163
    bool local_pred;
164 164

	
165 165
    ArborescenceMap *_arborescence;
166 166
    bool local_arborescence;
167 167

	
168 168
    typedef typename Digraph::template ArcMap<int> ArcOrder;
169 169
    ArcOrder *_arc_order;
170 170

	
171 171
    typedef typename Digraph::template NodeMap<int> NodeOrder;
172 172
    NodeOrder *_node_order;
173 173

	
174 174
    typedef typename Digraph::template NodeMap<CostArc> CostArcMap;
175 175
    CostArcMap *_cost_arcs;
176 176

	
177 177
    struct StackLevel {
178 178

	
179 179
      std::vector<CostArc> arcs;
180 180
      int node_level;
181 181

	
182 182
    };
183 183

	
184 184
    std::vector<StackLevel> level_stack;
185 185
    std::vector<Node> queue;
186 186

	
187 187
    typedef std::vector<typename Digraph::Node> DualNodeList;
188 188

	
189 189
    DualNodeList _dual_node_list;
190 190

	
191 191
    struct DualVariable {
192 192
      int begin, end;
193 193
      Value value;
194 194

	
195 195
      DualVariable(int _begin, int _end, Value _value)
196 196
        : begin(_begin), end(_end), value(_value) {}
197 197

	
198 198
    };
199 199

	
200 200
    typedef std::vector<DualVariable> DualVariables;
201 201

	
202 202
    DualVariables _dual_variables;
203 203

	
204 204
    typedef typename Digraph::template NodeMap<int> HeapCrossRef;
205 205

	
206 206
    HeapCrossRef *_heap_cross_ref;
207 207

	
208 208
    typedef BinHeap<int, HeapCrossRef> Heap;
209 209

	
210 210
    Heap *_heap;
211 211

	
212 212
  protected:
213 213

	
214 214
    MinCostArborescence() {}
215 215

	
216 216
  private:
217 217

	
218 218
    void createStructures() {
219 219
      if (!_pred) {
220 220
        local_pred = true;
221 221
        _pred = Traits::createPredMap(*_digraph);
222 222
      }
223 223
      if (!_arborescence) {
224 224
        local_arborescence = true;
225 225
        _arborescence = Traits::createArborescenceMap(*_digraph);
226 226
      }
227 227
      if (!_arc_order) {
228 228
        _arc_order = new ArcOrder(*_digraph);
229 229
      }
230 230
      if (!_node_order) {
231 231
        _node_order = new NodeOrder(*_digraph);
232 232
      }
233 233
      if (!_cost_arcs) {
234 234
        _cost_arcs = new CostArcMap(*_digraph);
235 235
      }
236 236
      if (!_heap_cross_ref) {
237 237
        _heap_cross_ref = new HeapCrossRef(*_digraph, -1);
238 238
      }
239 239
      if (!_heap) {
240 240
        _heap = new Heap(*_heap_cross_ref);
241 241
      }
242 242
    }
243 243

	
244 244
    void destroyStructures() {
245 245
      if (local_arborescence) {
246 246
        delete _arborescence;
247 247
      }
248 248
      if (local_pred) {
249 249
        delete _pred;
250 250
      }
251 251
      if (_arc_order) {
252 252
        delete _arc_order;
253 253
      }
254 254
      if (_node_order) {
255 255
        delete _node_order;
256 256
      }
257 257
      if (_cost_arcs) {
258 258
        delete _cost_arcs;
259 259
      }
260 260
      if (_heap) {
261 261
        delete _heap;
262 262
      }
263 263
      if (_heap_cross_ref) {
264 264
        delete _heap_cross_ref;
265 265
      }
266 266
    }
267 267

	
268 268
    Arc prepare(Node node) {
269 269
      std::vector<Node> nodes;
270 270
      (*_node_order)[node] = _dual_node_list.size();
271 271
      StackLevel level;
272 272
      level.node_level = _dual_node_list.size();
273 273
      _dual_node_list.push_back(node);
274 274
      for (InArcIt it(*_digraph, node); it != INVALID; ++it) {
275 275
        Arc arc = it;
276 276
        Node source = _digraph->source(arc);
277 277
        Value value = (*_cost)[it];
278 278
        if (source == node || (*_node_order)[source] == -3) continue;
279 279
        if ((*_cost_arcs)[source].arc == INVALID) {
280 280
          (*_cost_arcs)[source].arc = arc;
281 281
          (*_cost_arcs)[source].value = value;
282 282
          nodes.push_back(source);
283 283
        } else {
284 284
          if ((*_cost_arcs)[source].value > value) {
285 285
            (*_cost_arcs)[source].arc = arc;
286 286
            (*_cost_arcs)[source].value = value;
287 287
          }
288 288
        }
289 289
      }
290 290
      CostArc minimum = (*_cost_arcs)[nodes[0]];
291 291
      for (int i = 1; i < int(nodes.size()); ++i) {
292 292
        if ((*_cost_arcs)[nodes[i]].value < minimum.value) {
293 293
          minimum = (*_cost_arcs)[nodes[i]];
294 294
        }
295 295
      }
296 296
      (*_arc_order)[minimum.arc] = _dual_variables.size();
297 297
      DualVariable var(_dual_node_list.size() - 1,
298 298
                       _dual_node_list.size(), minimum.value);
299 299
      _dual_variables.push_back(var);
300 300
      for (int i = 0; i < int(nodes.size()); ++i) {
301 301
        (*_cost_arcs)[nodes[i]].value -= minimum.value;
302 302
        level.arcs.push_back((*_cost_arcs)[nodes[i]]);
303 303
        (*_cost_arcs)[nodes[i]].arc = INVALID;
304 304
      }
305 305
      level_stack.push_back(level);
306 306
      return minimum.arc;
307 307
    }
308 308

	
309 309
    Arc contract(Node node) {
310 310
      int node_bottom = bottom(node);
311 311
      std::vector<Node> nodes;
312 312
      while (!level_stack.empty() &&
313 313
             level_stack.back().node_level >= node_bottom) {
314 314
        for (int i = 0; i < int(level_stack.back().arcs.size()); ++i) {
315 315
          Arc arc = level_stack.back().arcs[i].arc;
316 316
          Node source = _digraph->source(arc);
317 317
          Value value = level_stack.back().arcs[i].value;
318 318
          if ((*_node_order)[source] >= node_bottom) continue;
319 319
          if ((*_cost_arcs)[source].arc == INVALID) {
320 320
            (*_cost_arcs)[source].arc = arc;
321 321
            (*_cost_arcs)[source].value = value;
322 322
            nodes.push_back(source);
323 323
          } else {
324 324
            if ((*_cost_arcs)[source].value > value) {
325 325
              (*_cost_arcs)[source].arc = arc;
326 326
              (*_cost_arcs)[source].value = value;
327 327
            }
328 328
          }
329 329
        }
330 330
        level_stack.pop_back();
331 331
      }
332 332
      CostArc minimum = (*_cost_arcs)[nodes[0]];
333 333
      for (int i = 1; i < int(nodes.size()); ++i) {
334 334
        if ((*_cost_arcs)[nodes[i]].value < minimum.value) {
335 335
          minimum = (*_cost_arcs)[nodes[i]];
336 336
        }
337 337
      }
338 338
      (*_arc_order)[minimum.arc] = _dual_variables.size();
339 339
      DualVariable var(node_bottom, _dual_node_list.size(), minimum.value);
340 340
      _dual_variables.push_back(var);
341 341
      StackLevel level;
342 342
      level.node_level = node_bottom;
343 343
      for (int i = 0; i < int(nodes.size()); ++i) {
344 344
        (*_cost_arcs)[nodes[i]].value -= minimum.value;
345 345
        level.arcs.push_back((*_cost_arcs)[nodes[i]]);
346 346
        (*_cost_arcs)[nodes[i]].arc = INVALID;
347 347
      }
348 348
      level_stack.push_back(level);
349 349
      return minimum.arc;
350 350
    }
351 351

	
352 352
    int bottom(Node node) {
353 353
      int k = level_stack.size() - 1;
354 354
      while (level_stack[k].node_level > (*_node_order)[node]) {
355 355
        --k;
356 356
      }
357 357
      return level_stack[k].node_level;
358 358
    }
359 359

	
360 360
    void finalize(Arc arc) {
361 361
      Node node = _digraph->target(arc);
362 362
      _heap->push(node, (*_arc_order)[arc]);
363 363
      _pred->set(node, arc);
364 364
      while (!_heap->empty()) {
365 365
        Node source = _heap->top();
366 366
        _heap->pop();
367 367
        (*_node_order)[source] = -1;
368 368
        for (OutArcIt it(*_digraph, source); it != INVALID; ++it) {
369 369
          if ((*_arc_order)[it] < 0) continue;
370 370
          Node target = _digraph->target(it);
371 371
          switch(_heap->state(target)) {
372 372
          case Heap::PRE_HEAP:
373 373
            _heap->push(target, (*_arc_order)[it]);
374 374
            _pred->set(target, it);
375 375
            break;
376 376
          case Heap::IN_HEAP:
377 377
            if ((*_arc_order)[it] < (*_heap)[target]) {
378 378
              _heap->decrease(target, (*_arc_order)[it]);
379 379
              _pred->set(target, it);
380 380
            }
381 381
            break;
382 382
          case Heap::POST_HEAP:
383 383
            break;
384 384
          }
385 385
        }
386 386
        _arborescence->set((*_pred)[source], true);
387 387
      }
388 388
    }
389 389

	
390 390

	
391 391
  public:
392 392

	
393
    /// \name Named template parameters
393
    /// \name Named Template Parameters
394 394

	
395 395
    /// @{
396 396

	
397 397
    template <class T>
398 398
    struct DefArborescenceMapTraits : public Traits {
399 399
      typedef T ArborescenceMap;
400 400
      static ArborescenceMap *createArborescenceMap(const Digraph &)
401 401
      {
402 402
        LEMON_ASSERT(false, "ArborescenceMap is not initialized");
403 403
        return 0; // ignore warnings
404 404
      }
405 405
    };
406 406

	
407 407
    /// \brief \ref named-templ-param "Named parameter" for
408 408
    /// setting ArborescenceMap type
409 409
    ///
410 410
    /// \ref named-templ-param "Named parameter" for setting
411 411
    /// ArborescenceMap type
412 412
    template <class T>
413 413
    struct DefArborescenceMap
414 414
      : public MinCostArborescence<Digraph, CostMap,
415 415
                                   DefArborescenceMapTraits<T> > {
416 416
    };
417 417

	
418 418
    template <class T>
419 419
    struct DefPredMapTraits : public Traits {
420 420
      typedef T PredMap;
421 421
      static PredMap *createPredMap(const Digraph &)
422 422
      {
423 423
        LEMON_ASSERT(false, "PredMap is not initialized");
424 424
      }
425 425
    };
426 426

	
427 427
    /// \brief \ref named-templ-param "Named parameter" for
428 428
    /// setting PredMap type
429 429
    ///
430 430
    /// \ref named-templ-param "Named parameter" for setting
431 431
    /// PredMap type
432 432
    template <class T>
433 433
    struct DefPredMap
434 434
      : public MinCostArborescence<Digraph, CostMap, DefPredMapTraits<T> > {
435 435
    };
436 436

	
437 437
    /// @}
438 438

	
439 439
    /// \brief Constructor.
440 440
    ///
441 441
    /// \param digraph The digraph the algorithm will run on.
442 442
    /// \param cost The cost map used by the algorithm.
443 443
    MinCostArborescence(const Digraph& digraph, const CostMap& cost)
444 444
      : _digraph(&digraph), _cost(&cost), _pred(0), local_pred(false),
445 445
        _arborescence(0), local_arborescence(false),
446 446
        _arc_order(0), _node_order(0), _cost_arcs(0),
447 447
        _heap_cross_ref(0), _heap(0) {}
448 448

	
449 449
    /// \brief Destructor.
450 450
    ~MinCostArborescence() {
451 451
      destroyStructures();
452 452
    }
453 453

	
454 454
    /// \brief Sets the arborescence map.
455 455
    ///
456 456
    /// Sets the arborescence map.
457 457
    /// \return <tt>(*this)</tt>
458 458
    MinCostArborescence& arborescenceMap(ArborescenceMap& m) {
459 459
      if (local_arborescence) {
460 460
        delete _arborescence;
461 461
      }
462 462
      local_arborescence = false;
463 463
      _arborescence = &m;
464 464
      return *this;
465 465
    }
466 466

	
467 467
    /// \brief Sets the arborescence map.
468 468
    ///
469 469
    /// Sets the arborescence map.
470 470
    /// \return <tt>(*this)</tt>
471 471
    MinCostArborescence& predMap(PredMap& m) {
472 472
      if (local_pred) {
473 473
        delete _pred;
474 474
      }
475 475
      local_pred = false;
476 476
      _pred = &m;
477 477
      return *this;
478 478
    }
479 479

	
480 480
    /// \name Query Functions
481 481
    /// The result of the %MinCostArborescence algorithm can be obtained
482 482
    /// using these functions.\n
483 483
    /// Before the use of these functions,
484 484
    /// either run() or start() must be called.
485 485

	
486 486
    /// @{
487 487

	
488 488
    /// \brief Returns a reference to the arborescence map.
489 489
    ///
490 490
    /// Returns a reference to the arborescence map.
491 491
    const ArborescenceMap& arborescenceMap() const {
492 492
      return *_arborescence;
493 493
    }
494 494

	
495 495
    /// \brief Returns true if the arc is in the arborescence.
496 496
    ///
497 497
    /// Returns true if the arc is in the arborescence.
498 498
    /// \param arc The arc of the digraph.
499 499
    /// \pre \ref run() must be called before using this function.
500 500
    bool arborescence(Arc arc) const {
501 501
      return (*_pred)[_digraph->target(arc)] == arc;
502 502
    }
503 503

	
504 504
    /// \brief Returns a reference to the pred map.
505 505
    ///
506 506
    /// Returns a reference to the pred map.
507 507
    const PredMap& predMap() const {
508 508
      return *_pred;
509 509
    }
510 510

	
511 511
    /// \brief Returns the predecessor arc of the given node.
512 512
    ///
513 513
    /// Returns the predecessor arc of the given node.
514 514
    Arc pred(Node node) const {
515 515
      return (*_pred)[node];
516 516
    }
517 517

	
518 518
    /// \brief Returns the cost of the arborescence.
519 519
    ///
520 520
    /// Returns the cost of the arborescence.
521 521
    Value arborescenceValue() const {
522 522
      Value sum = 0;
523 523
      for (ArcIt it(*_digraph); it != INVALID; ++it) {
524 524
        if (arborescence(it)) {
525 525
          sum += (*_cost)[it];
526 526
        }
527 527
      }
528 528
      return sum;
529 529
    }
530 530

	
531 531
    /// \brief Indicates that a node is reachable from the sources.
532 532
    ///
533 533
    /// Indicates that a node is reachable from the sources.
534 534
    bool reached(Node node) const {
535 535
      return (*_node_order)[node] != -3;
536 536
    }
537 537

	
538 538
    /// \brief Indicates that a node is processed.
539 539
    ///
540 540
    /// Indicates that a node is processed. The arborescence path exists
541 541
    /// from the source to the given node.
542 542
    bool processed(Node node) const {
543 543
      return (*_node_order)[node] == -1;
544 544
    }
545 545

	
546 546
    /// \brief Returns the number of the dual variables in basis.
547 547
    ///
548 548
    /// Returns the number of the dual variables in basis.
549 549
    int dualNum() const {
550 550
      return _dual_variables.size();
551 551
    }
552 552

	
553 553
    /// \brief Returns the value of the dual solution.
554 554
    ///
555 555
    /// Returns the value of the dual solution. It should be
556 556
    /// equal to the arborescence value.
557 557
    Value dualValue() const {
558 558
      Value sum = 0;
559 559
      for (int i = 0; i < int(_dual_variables.size()); ++i) {
560 560
        sum += _dual_variables[i].value;
561 561
      }
562 562
      return sum;
563 563
    }
564 564

	
565 565
    /// \brief Returns the number of the nodes in the dual variable.
566 566
    ///
567 567
    /// Returns the number of the nodes in the dual variable.
568 568
    int dualSize(int k) const {
569 569
      return _dual_variables[k].end - _dual_variables[k].begin;
570 570
    }
571 571

	
572 572
    /// \brief Returns the value of the dual variable.
573 573
    ///
574 574
    /// Returns the the value of the dual variable.
575 575
    const Value& dualValue(int k) const {
576 576
      return _dual_variables[k].value;
577 577
    }
578 578

	
579 579
    /// \brief Lemon iterator for get a dual variable.
580 580
    ///
581 581
    /// Lemon iterator for get a dual variable. This class provides
582 582
    /// a common style lemon iterator which gives back a subset of
583 583
    /// the nodes.
584 584
    class DualIt {
585 585
    public:
586 586

	
587 587
      /// \brief Constructor.
588 588
      ///
589 589
      /// Constructor for get the nodeset of the variable.
590 590
      DualIt(const MinCostArborescence& algorithm, int variable)
591 591
        : _algorithm(&algorithm)
592 592
      {
593 593
        _index = _algorithm->_dual_variables[variable].begin;
594 594
        _last = _algorithm->_dual_variables[variable].end;
595 595
      }
596 596

	
597 597
      /// \brief Conversion to node.
598 598
      ///
599 599
      /// Conversion to node.
600 600
      operator Node() const {
601 601
        return _algorithm->_dual_node_list[_index];
602 602
      }
603 603

	
604 604
      /// \brief Increment operator.
605 605
      ///
606 606
      /// Increment operator.
607 607
      DualIt& operator++() {
608 608
        ++_index;
609 609
        return *this;
610 610
      }
611 611

	
612 612
      /// \brief Validity checking
613 613
      ///
614 614
      /// Checks whether the iterator is invalid.
615 615
      bool operator==(Invalid) const {
616 616
        return _index == _last;
617 617
      }
618 618

	
619 619
      /// \brief Validity checking
620 620
      ///
621 621
      /// Checks whether the iterator is valid.
622 622
      bool operator!=(Invalid) const {
623 623
        return _index != _last;
624 624
      }
625 625

	
626 626
    private:
627 627
      const MinCostArborescence* _algorithm;
628 628
      int _index, _last;
629 629
    };
630 630

	
631 631
    /// @}
632 632

	
633
    /// \name Execution control
633
    /// \name Execution Control
634 634
    /// The simplest way to execute the algorithm is to use
635 635
    /// one of the member functions called \c run(...). \n
636 636
    /// If you need more control on the execution,
637 637
    /// first you must call \ref init(), then you can add several
638 638
    /// source nodes with \ref addSource().
639 639
    /// Finally \ref start() will perform the arborescence
640 640
    /// computation.
641 641

	
642 642
    ///@{
643 643

	
644 644
    /// \brief Initializes the internal data structures.
645 645
    ///
646 646
    /// Initializes the internal data structures.
647 647
    ///
648 648
    void init() {
649 649
      createStructures();
650 650
      _heap->clear();
651 651
      for (NodeIt it(*_digraph); it != INVALID; ++it) {
652 652
        (*_cost_arcs)[it].arc = INVALID;
653 653
        (*_node_order)[it] = -3;
654 654
        (*_heap_cross_ref)[it] = Heap::PRE_HEAP;
655 655
        _pred->set(it, INVALID);
656 656
      }
657 657
      for (ArcIt it(*_digraph); it != INVALID; ++it) {
658 658
        _arborescence->set(it, false);
659 659
        (*_arc_order)[it] = -1;
660 660
      }
661 661
      _dual_node_list.clear();
662 662
      _dual_variables.clear();
663 663
    }
664 664

	
665 665
    /// \brief Adds a new source node.
666 666
    ///
667 667
    /// Adds a new source node to the algorithm.
668 668
    void addSource(Node source) {
669 669
      std::vector<Node> nodes;
670 670
      nodes.push_back(source);
671 671
      while (!nodes.empty()) {
672 672
        Node node = nodes.back();
673 673
        nodes.pop_back();
674 674
        for (OutArcIt it(*_digraph, node); it != INVALID; ++it) {
675 675
          Node target = _digraph->target(it);
676 676
          if ((*_node_order)[target] == -3) {
677 677
            (*_node_order)[target] = -2;
678 678
            nodes.push_back(target);
679 679
            queue.push_back(target);
680 680
          }
681 681
        }
682 682
      }
683 683
      (*_node_order)[source] = -1;
684 684
    }
685 685

	
686 686
    /// \brief Processes the next node in the priority queue.
687 687
    ///
688 688
    /// Processes the next node in the priority queue.
689 689
    ///
690 690
    /// \return The processed node.
691 691
    ///
692 692
    /// \warning The queue must not be empty!
693 693
    Node processNextNode() {
694 694
      Node node = queue.back();
695 695
      queue.pop_back();
696 696
      if ((*_node_order)[node] == -2) {
697 697
        Arc arc = prepare(node);
698 698
        Node source = _digraph->source(arc);
699 699
        while ((*_node_order)[source] != -1) {
700 700
          if ((*_node_order)[source] >= 0) {
701 701
            arc = contract(source);
702 702
          } else {
703 703
            arc = prepare(source);
704 704
          }
705 705
          source = _digraph->source(arc);
706 706
        }
707 707
        finalize(arc);
708 708
        level_stack.clear();
709 709
      }
710 710
      return node;
711 711
    }
712 712

	
713 713
    /// \brief Returns the number of the nodes to be processed.
714 714
    ///
715 715
    /// Returns the number of the nodes to be processed.
716 716
    int queueSize() const {
717 717
      return queue.size();
718 718
    }
719 719

	
720 720
    /// \brief Returns \c false if there are nodes to be processed.
721 721
    ///
722 722
    /// Returns \c false if there are nodes to be processed.
723 723
    bool emptyQueue() const {
724 724
      return queue.empty();
725 725
    }
726 726

	
727 727
    /// \brief Executes the algorithm.
728 728
    ///
729 729
    /// Executes the algorithm.
730 730
    ///
731 731
    /// \pre init() must be called and at least one node should be added
732 732
    /// with addSource() before using this function.
733 733
    ///
734 734
    ///\note mca.start() is just a shortcut of the following code.
735 735
    ///\code
736 736
    ///while (!mca.emptyQueue()) {
737 737
    ///  mca.processNextNode();
738 738
    ///}
739 739
    ///\endcode
740 740
    void start() {
741 741
      while (!emptyQueue()) {
742 742
        processNextNode();
743 743
      }
744 744
    }
745 745

	
746 746
    /// \brief Runs %MinCostArborescence algorithm from node \c s.
747 747
    ///
748 748
    /// This method runs the %MinCostArborescence algorithm from
749 749
    /// a root node \c s.
750 750
    ///
751 751
    /// \note mca.run(s) is just a shortcut of the following code.
752 752
    /// \code
753 753
    /// mca.init();
754 754
    /// mca.addSource(s);
755 755
    /// mca.start();
756 756
    /// \endcode
757 757
    void run(Node node) {
758 758
      init();
759 759
      addSource(node);
760 760
      start();
761 761
    }
762 762

	
763 763
    ///@}
764 764

	
765 765
  };
766 766

	
767 767
  /// \ingroup spantree
768 768
  ///
769 769
  /// \brief Function type interface for MinCostArborescence algorithm.
770 770
  ///
771 771
  /// Function type interface for MinCostArborescence algorithm.
772 772
  /// \param digraph The Digraph that the algorithm runs on.
773 773
  /// \param cost The CostMap of the arcs.
774 774
  /// \param source The source of the arborescence.
775 775
  /// \retval arborescence The bool ArcMap which stores the arborescence.
776 776
  /// \return The cost of the arborescence.
777 777
  ///
778 778
  /// \sa MinCostArborescence
779 779
  template <typename Digraph, typename CostMap, typename ArborescenceMap>
780 780
  typename CostMap::Value minCostArborescence(const Digraph& digraph,
781 781
                                              const CostMap& cost,
782 782
                                              typename Digraph::Node source,
783 783
                                              ArborescenceMap& arborescence) {
784 784
    typename MinCostArborescence<Digraph, CostMap>
785 785
      ::template DefArborescenceMap<ArborescenceMap>
786 786
      ::Create mca(digraph, cost);
787 787
    mca.arborescenceMap(arborescence);
788 788
    mca.run(source);
789 789
    return mca.arborescenceValue();
790 790
  }
791 791

	
792 792
}
793 793

	
794 794
#endif
Ignore white space 6 line context
... ...
@@ -406,600 +406,600 @@
406 406
        return Shifting<Result, shift + rest>::
407 407
          shift(static_cast<Result>(rnd() >> (bits - rest)));
408 408
      }
409 409
    };
410 410

	
411 411
    template <typename Result, typename Word, int rest, int shift>
412 412
    struct RealConversion<Result, Word, rest, shift, false> {
413 413
      static const int bits = std::numeric_limits<Word>::digits;
414 414

	
415 415
      static Result convert(RandomCore<Word>& rnd) {
416 416
        return Shifting<Result, shift + bits>::
417 417
          shift(static_cast<Result>(rnd())) +
418 418
          RealConversion<Result, Word, rest-bits, shift + bits>::
419 419
          convert(rnd);
420 420
      }
421 421
    };
422 422

	
423 423
    template <typename Result, typename Word>
424 424
    struct Initializer {
425 425

	
426 426
      template <typename Iterator>
427 427
      static void init(RandomCore<Word>& rnd, Iterator begin, Iterator end) {
428 428
        std::vector<Word> ws;
429 429
        for (Iterator it = begin; it != end; ++it) {
430 430
          ws.push_back(Word(*it));
431 431
        }
432 432
        rnd.initState(ws.begin(), ws.end());
433 433
      }
434 434

	
435 435
      static void init(RandomCore<Word>& rnd, Result seed) {
436 436
        rnd.initState(seed);
437 437
      }
438 438
    };
439 439

	
440 440
    template <typename Word>
441 441
    struct BoolConversion {
442 442
      static bool convert(RandomCore<Word>& rnd) {
443 443
        return (rnd() & 1) == 1;
444 444
      }
445 445
    };
446 446

	
447 447
    template <typename Word>
448 448
    struct BoolProducer {
449 449
      Word buffer;
450 450
      int num;
451 451

	
452 452
      BoolProducer() : num(0) {}
453 453

	
454 454
      bool convert(RandomCore<Word>& rnd) {
455 455
        if (num == 0) {
456 456
          buffer = rnd();
457 457
          num = RandomTraits<Word>::bits;
458 458
        }
459 459
        bool r = (buffer & 1);
460 460
        buffer >>= 1;
461 461
        --num;
462 462
        return r;
463 463
      }
464 464
    };
465 465

	
466 466
  }
467 467

	
468 468
  /// \ingroup misc
469 469
  ///
470 470
  /// \brief Mersenne Twister random number generator
471 471
  ///
472 472
  /// The Mersenne Twister is a twisted generalized feedback
473 473
  /// shift-register generator of Matsumoto and Nishimura. The period
474 474
  /// of this generator is \f$ 2^{19937} - 1 \f$ and it is
475 475
  /// equi-distributed in 623 dimensions for 32-bit numbers. The time
476 476
  /// performance of this generator is comparable to the commonly used
477 477
  /// generators.
478 478
  ///
479 479
  /// This implementation is specialized for both 32-bit and 64-bit
480 480
  /// architectures. The generators differ sligthly in the
481 481
  /// initialization and generation phase so they produce two
482 482
  /// completly different sequences.
483 483
  ///
484 484
  /// The generator gives back random numbers of serveral types. To
485 485
  /// get a random number from a range of a floating point type you
486 486
  /// can use one form of the \c operator() or the \c real() member
487 487
  /// function. If you want to get random number from the {0, 1, ...,
488 488
  /// n-1} integer range use the \c operator[] or the \c integer()
489 489
  /// method. And to get random number from the whole range of an
490 490
  /// integer type you can use the argumentless \c integer() or \c
491 491
  /// uinteger() functions. After all you can get random bool with
492 492
  /// equal chance of true and false or given probability of true
493 493
  /// result with the \c boolean() member functions.
494 494
  ///
495 495
  ///\code
496 496
  /// // The commented code is identical to the other
497 497
  /// double a = rnd();                     // [0.0, 1.0)
498 498
  /// // double a = rnd.real();             // [0.0, 1.0)
499 499
  /// double b = rnd(100.0);                // [0.0, 100.0)
500 500
  /// // double b = rnd.real(100.0);        // [0.0, 100.0)
501 501
  /// double c = rnd(1.0, 2.0);             // [1.0, 2.0)
502 502
  /// // double c = rnd.real(1.0, 2.0);     // [1.0, 2.0)
503 503
  /// int d = rnd[100000];                  // 0..99999
504 504
  /// // int d = rnd.integer(100000);       // 0..99999
505 505
  /// int e = rnd[6] + 1;                   // 1..6
506 506
  /// // int e = rnd.integer(1, 1 + 6);     // 1..6
507 507
  /// int b = rnd.uinteger<int>();          // 0 .. 2^31 - 1
508 508
  /// int c = rnd.integer<int>();           // - 2^31 .. 2^31 - 1
509 509
  /// bool g = rnd.boolean();               // P(g = true) = 0.5
510 510
  /// bool h = rnd.boolean(0.8);            // P(h = true) = 0.8
511 511
  ///\endcode
512 512
  ///
513 513
  /// LEMON provides a global instance of the random number
514 514
  /// generator which name is \ref lemon::rnd "rnd". Usually it is a
515 515
  /// good programming convenience to use this global generator to get
516 516
  /// random numbers.
517 517
  class Random {
518 518
  private:
519 519

	
520 520
    // Architecture word
521 521
    typedef unsigned long Word;
522 522

	
523 523
    _random_bits::RandomCore<Word> core;
524 524
    _random_bits::BoolProducer<Word> bool_producer;
525 525

	
526 526

	
527 527
  public:
528 528

	
529 529
    ///\name Initialization
530 530
    ///
531 531
    /// @{
532 532

	
533 533
    /// \brief Default constructor
534 534
    ///
535 535
    /// Constructor with constant seeding.
536 536
    Random() { core.initState(); }
537 537

	
538 538
    /// \brief Constructor with seed
539 539
    ///
540 540
    /// Constructor with seed. The current number type will be converted
541 541
    /// to the architecture word type.
542 542
    template <typename Number>
543 543
    Random(Number seed) {
544 544
      _random_bits::Initializer<Number, Word>::init(core, seed);
545 545
    }
546 546

	
547 547
    /// \brief Constructor with array seeding
548 548
    ///
549 549
    /// Constructor with array seeding. The given range should contain
550 550
    /// any number type and the numbers will be converted to the
551 551
    /// architecture word type.
552 552
    template <typename Iterator>
553 553
    Random(Iterator begin, Iterator end) {
554 554
      typedef typename std::iterator_traits<Iterator>::value_type Number;
555 555
      _random_bits::Initializer<Number, Word>::init(core, begin, end);
556 556
    }
557 557

	
558 558
    /// \brief Copy constructor
559 559
    ///
560 560
    /// Copy constructor. The generated sequence will be identical to
561 561
    /// the other sequence. It can be used to save the current state
562 562
    /// of the generator and later use it to generate the same
563 563
    /// sequence.
564 564
    Random(const Random& other) {
565 565
      core.copyState(other.core);
566 566
    }
567 567

	
568 568
    /// \brief Assign operator
569 569
    ///
570 570
    /// Assign operator. The generated sequence will be identical to
571 571
    /// the other sequence. It can be used to save the current state
572 572
    /// of the generator and later use it to generate the same
573 573
    /// sequence.
574 574
    Random& operator=(const Random& other) {
575 575
      if (&other != this) {
576 576
        core.copyState(other.core);
577 577
      }
578 578
      return *this;
579 579
    }
580 580

	
581 581
    /// \brief Seeding random sequence
582 582
    ///
583 583
    /// Seeding the random sequence. The current number type will be
584 584
    /// converted to the architecture word type.
585 585
    template <typename Number>
586 586
    void seed(Number seed) {
587 587
      _random_bits::Initializer<Number, Word>::init(core, seed);
588 588
    }
589 589

	
590 590
    /// \brief Seeding random sequence
591 591
    ///
592 592
    /// Seeding the random sequence. The given range should contain
593 593
    /// any number type and the numbers will be converted to the
594 594
    /// architecture word type.
595 595
    template <typename Iterator>
596 596
    void seed(Iterator begin, Iterator end) {
597 597
      typedef typename std::iterator_traits<Iterator>::value_type Number;
598 598
      _random_bits::Initializer<Number, Word>::init(core, begin, end);
599 599
    }
600 600

	
601 601
    /// \brief Seeding from file or from process id and time
602 602
    ///
603 603
    /// By default, this function calls the \c seedFromFile() member
604 604
    /// function with the <tt>/dev/urandom</tt> file. If it does not success,
605 605
    /// it uses the \c seedFromTime().
606 606
    /// \return Currently always \c true.
607 607
    bool seed() {
608 608
#ifndef WIN32
609 609
      if (seedFromFile("/dev/urandom", 0)) return true;
610 610
#endif
611 611
      if (seedFromTime()) return true;
612 612
      return false;
613 613
    }
614 614

	
615 615
    /// \brief Seeding from file
616 616
    ///
617 617
    /// Seeding the random sequence from file. The linux kernel has two
618 618
    /// devices, <tt>/dev/random</tt> and <tt>/dev/urandom</tt> which
619 619
    /// could give good seed values for pseudo random generators (The
620 620
    /// difference between two devices is that the <tt>random</tt> may
621 621
    /// block the reading operation while the kernel can give good
622 622
    /// source of randomness, while the <tt>urandom</tt> does not
623 623
    /// block the input, but it could give back bytes with worse
624 624
    /// entropy).
625 625
    /// \param file The source file
626 626
    /// \param offset The offset, from the file read.
627 627
    /// \return \c true when the seeding successes.
628 628
#ifndef WIN32
629 629
    bool seedFromFile(const std::string& file = "/dev/urandom", int offset = 0)
630 630
#else
631 631
    bool seedFromFile(const std::string& file = "", int offset = 0)
632 632
#endif
633 633
    {
634 634
      std::ifstream rs(file.c_str());
635 635
      const int size = 4;
636 636
      Word buf[size];
637 637
      if (offset != 0 && !rs.seekg(offset)) return false;
638 638
      if (!rs.read(reinterpret_cast<char*>(buf), sizeof(buf))) return false;
639 639
      seed(buf, buf + size);
640 640
      return true;
641 641
    }
642 642

	
643 643
    /// \brief Seding from process id and time
644 644
    ///
645 645
    /// Seding from process id and time. This function uses the
646 646
    /// current process id and the current time for initialize the
647 647
    /// random sequence.
648 648
    /// \return Currently always \c true.
649 649
    bool seedFromTime() {
650 650
#ifndef WIN32
651 651
      timeval tv;
652 652
      gettimeofday(&tv, 0);
653 653
      seed(getpid() + tv.tv_sec + tv.tv_usec);
654 654
#else
655 655
      seed(bits::getWinRndSeed());
656 656
#endif
657 657
      return true;
658 658
    }
659 659

	
660 660
    /// @}
661 661

	
662
    ///\name Uniform distributions
662
    ///\name Uniform Distributions
663 663
    ///
664 664
    /// @{
665 665

	
666 666
    /// \brief Returns a random real number from the range [0, 1)
667 667
    ///
668 668
    /// It returns a random real number from the range [0, 1). The
669 669
    /// default Number type is \c double.
670 670
    template <typename Number>
671 671
    Number real() {
672 672
      return _random_bits::RealConversion<Number, Word>::convert(core);
673 673
    }
674 674

	
675 675
    double real() {
676 676
      return real<double>();
677 677
    }
678 678

	
679 679
    /// \brief Returns a random real number from the range [0, 1)
680 680
    ///
681 681
    /// It returns a random double from the range [0, 1).
682 682
    double operator()() {
683 683
      return real<double>();
684 684
    }
685 685

	
686 686
    /// \brief Returns a random real number from the range [0, b)
687 687
    ///
688 688
    /// It returns a random real number from the range [0, b).
689 689
    double operator()(double b) {
690 690
      return real<double>() * b;
691 691
    }
692 692

	
693 693
    /// \brief Returns a random real number from the range [a, b)
694 694
    ///
695 695
    /// It returns a random real number from the range [a, b).
696 696
    double operator()(double a, double b) {
697 697
      return real<double>() * (b - a) + a;
698 698
    }
699 699

	
700 700
    /// \brief Returns a random integer from a range
701 701
    ///
702 702
    /// It returns a random integer from the range {0, 1, ..., b - 1}.
703 703
    template <typename Number>
704 704
    Number integer(Number b) {
705 705
      return _random_bits::Mapping<Number, Word>::map(core, b);
706 706
    }
707 707

	
708 708
    /// \brief Returns a random integer from a range
709 709
    ///
710 710
    /// It returns a random integer from the range {a, a + 1, ..., b - 1}.
711 711
    template <typename Number>
712 712
    Number integer(Number a, Number b) {
713 713
      return _random_bits::Mapping<Number, Word>::map(core, b - a) + a;
714 714
    }
715 715

	
716 716
    /// \brief Returns a random integer from a range
717 717
    ///
718 718
    /// It returns a random integer from the range {0, 1, ..., b - 1}.
719 719
    template <typename Number>
720 720
    Number operator[](Number b) {
721 721
      return _random_bits::Mapping<Number, Word>::map(core, b);
722 722
    }
723 723

	
724 724
    /// \brief Returns a random non-negative integer
725 725
    ///
726 726
    /// It returns a random non-negative integer uniformly from the
727 727
    /// whole range of the current \c Number type. The default result
728 728
    /// type of this function is <tt>unsigned int</tt>.
729 729
    template <typename Number>
730 730
    Number uinteger() {
731 731
      return _random_bits::IntConversion<Number, Word>::convert(core);
732 732
    }
733 733

	
734 734
    unsigned int uinteger() {
735 735
      return uinteger<unsigned int>();
736 736
    }
737 737

	
738 738
    /// \brief Returns a random integer
739 739
    ///
740 740
    /// It returns a random integer uniformly from the whole range of
741 741
    /// the current \c Number type. The default result type of this
742 742
    /// function is \c int.
743 743
    template <typename Number>
744 744
    Number integer() {
745 745
      static const int nb = std::numeric_limits<Number>::digits +
746 746
        (std::numeric_limits<Number>::is_signed ? 1 : 0);
747 747
      return _random_bits::IntConversion<Number, Word, nb>::convert(core);
748 748
    }
749 749

	
750 750
    int integer() {
751 751
      return integer<int>();
752 752
    }
753 753

	
754 754
    /// \brief Returns a random bool
755 755
    ///
756 756
    /// It returns a random bool. The generator holds a buffer for
757 757
    /// random bits. Every time when it become empty the generator makes
758 758
    /// a new random word and fill the buffer up.
759 759
    bool boolean() {
760 760
      return bool_producer.convert(core);
761 761
    }
762 762

	
763 763
    /// @}
764 764

	
765
    ///\name Non-uniform distributions
765
    ///\name Non-uniform Distributions
766 766
    ///
767 767
    ///@{
768 768

	
769 769
    /// \brief Returns a random bool with given probability of true result.
770 770
    ///
771 771
    /// It returns a random bool with given probability of true result.
772 772
    bool boolean(double p) {
773 773
      return operator()() < p;
774 774
    }
775 775

	
776 776
    /// Standard normal (Gauss) distribution
777 777

	
778 778
    /// Standard normal (Gauss) distribution.
779 779
    /// \note The Cartesian form of the Box-Muller
780 780
    /// transformation is used to generate a random normal distribution.
781 781
    double gauss()
782 782
    {
783 783
      double V1,V2,S;
784 784
      do {
785 785
        V1=2*real<double>()-1;
786 786
        V2=2*real<double>()-1;
787 787
        S=V1*V1+V2*V2;
788 788
      } while(S>=1);
789 789
      return std::sqrt(-2*std::log(S)/S)*V1;
790 790
    }
791 791
    /// Normal (Gauss) distribution with given mean and standard deviation
792 792

	
793 793
    /// Normal (Gauss) distribution with given mean and standard deviation.
794 794
    /// \sa gauss()
795 795
    double gauss(double mean,double std_dev)
796 796
    {
797 797
      return gauss()*std_dev+mean;
798 798
    }
799 799

	
800 800
    /// Lognormal distribution
801 801

	
802 802
    /// Lognormal distribution. The parameters are the mean and the standard
803 803
    /// deviation of <tt>exp(X)</tt>.
804 804
    ///
805 805
    double lognormal(double n_mean,double n_std_dev)
806 806
    {
807 807
      return std::exp(gauss(n_mean,n_std_dev));
808 808
    }
809 809
    /// Lognormal distribution
810 810

	
811 811
    /// Lognormal distribution. The parameter is an <tt>std::pair</tt> of
812 812
    /// the mean and the standard deviation of <tt>exp(X)</tt>.
813 813
    ///
814 814
    double lognormal(const std::pair<double,double> &params)
815 815
    {
816 816
      return std::exp(gauss(params.first,params.second));
817 817
    }
818 818
    /// Compute the lognormal parameters from mean and standard deviation
819 819

	
820 820
    /// This function computes the lognormal parameters from mean and
821 821
    /// standard deviation. The return value can direcly be passed to
822 822
    /// lognormal().
823 823
    std::pair<double,double> lognormalParamsFromMD(double mean,
824 824
                                                   double std_dev)
825 825
    {
826 826
      double fr=std_dev/mean;
827 827
      fr*=fr;
828 828
      double lg=std::log(1+fr);
829 829
      return std::pair<double,double>(std::log(mean)-lg/2.0,std::sqrt(lg));
830 830
    }
831 831
    /// Lognormal distribution with given mean and standard deviation
832 832

	
833 833
    /// Lognormal distribution with given mean and standard deviation.
834 834
    ///
835 835
    double lognormalMD(double mean,double std_dev)
836 836
    {
837 837
      return lognormal(lognormalParamsFromMD(mean,std_dev));
838 838
    }
839 839

	
840 840
    /// Exponential distribution with given mean
841 841

	
842 842
    /// This function generates an exponential distribution random number
843 843
    /// with mean <tt>1/lambda</tt>.
844 844
    ///
845 845
    double exponential(double lambda=1.0)
846 846
    {
847 847
      return -std::log(1.0-real<double>())/lambda;
848 848
    }
849 849

	
850 850
    /// Gamma distribution with given integer shape
851 851

	
852 852
    /// This function generates a gamma distribution random number.
853 853
    ///
854 854
    ///\param k shape parameter (<tt>k>0</tt> integer)
855 855
    double gamma(int k)
856 856
    {
857 857
      double s = 0;
858 858
      for(int i=0;i<k;i++) s-=std::log(1.0-real<double>());
859 859
      return s;
860 860
    }
861 861

	
862 862
    /// Gamma distribution with given shape and scale parameter
863 863

	
864 864
    /// This function generates a gamma distribution random number.
865 865
    ///
866 866
    ///\param k shape parameter (<tt>k>0</tt>)
867 867
    ///\param theta scale parameter
868 868
    ///
869 869
    double gamma(double k,double theta=1.0)
870 870
    {
871 871
      double xi,nu;
872 872
      const double delta = k-std::floor(k);
873 873
      const double v0=E/(E-delta);
874 874
      do {
875 875
        double V0=1.0-real<double>();
876 876
        double V1=1.0-real<double>();
877 877
        double V2=1.0-real<double>();
878 878
        if(V2<=v0)
879 879
          {
880 880
            xi=std::pow(V1,1.0/delta);
881 881
            nu=V0*std::pow(xi,delta-1.0);
882 882
          }
883 883
        else
884 884
          {
885 885
            xi=1.0-std::log(V1);
886 886
            nu=V0*std::exp(-xi);
887 887
          }
888 888
      } while(nu>std::pow(xi,delta-1.0)*std::exp(-xi));
889 889
      return theta*(xi+gamma(int(std::floor(k))));
890 890
    }
891 891

	
892 892
    /// Weibull distribution
893 893

	
894 894
    /// This function generates a Weibull distribution random number.
895 895
    ///
896 896
    ///\param k shape parameter (<tt>k>0</tt>)
897 897
    ///\param lambda scale parameter (<tt>lambda>0</tt>)
898 898
    ///
899 899
    double weibull(double k,double lambda)
900 900
    {
901 901
      return lambda*pow(-std::log(1.0-real<double>()),1.0/k);
902 902
    }
903 903

	
904 904
    /// Pareto distribution
905 905

	
906 906
    /// This function generates a Pareto distribution random number.
907 907
    ///
908 908
    ///\param k shape parameter (<tt>k>0</tt>)
909 909
    ///\param x_min location parameter (<tt>x_min>0</tt>)
910 910
    ///
911 911
    double pareto(double k,double x_min)
912 912
    {
913 913
      return exponential(gamma(k,1.0/x_min))+x_min;
914 914
    }
915 915

	
916 916
    /// Poisson distribution
917 917

	
918 918
    /// This function generates a Poisson distribution random number with
919 919
    /// parameter \c lambda.
920 920
    ///
921 921
    /// The probability mass function of this distribusion is
922 922
    /// \f[ \frac{e^{-\lambda}\lambda^k}{k!} \f]
923 923
    /// \note The algorithm is taken from the book of Donald E. Knuth titled
924 924
    /// ''Seminumerical Algorithms'' (1969). Its running time is linear in the
925 925
    /// return value.
926 926

	
927 927
    int poisson(double lambda)
928 928
    {
929 929
      const double l = std::exp(-lambda);
930 930
      int k=0;
931 931
      double p = 1.0;
932 932
      do {
933 933
        k++;
934 934
        p*=real<double>();
935 935
      } while (p>=l);
936 936
      return k-1;
937 937
    }
938 938

	
939 939
    ///@}
940 940

	
941
    ///\name Two dimensional distributions
941
    ///\name Two Dimensional Distributions
942 942
    ///
943 943
    ///@{
944 944

	
945 945
    /// Uniform distribution on the full unit circle
946 946

	
947 947
    /// Uniform distribution on the full unit circle.
948 948
    ///
949 949
    dim2::Point<double> disc()
950 950
    {
951 951
      double V1,V2;
952 952
      do {
953 953
        V1=2*real<double>()-1;
954 954
        V2=2*real<double>()-1;
955 955

	
956 956
      } while(V1*V1+V2*V2>=1);
957 957
      return dim2::Point<double>(V1,V2);
958 958
    }
959 959
    /// A kind of two dimensional normal (Gauss) distribution
960 960

	
961 961
    /// This function provides a turning symmetric two-dimensional distribution.
962 962
    /// Both coordinates are of standard normal distribution, but they are not
963 963
    /// independent.
964 964
    ///
965 965
    /// \note The coordinates are the two random variables provided by
966 966
    /// the Box-Muller method.
967 967
    dim2::Point<double> gauss2()
968 968
    {
969 969
      double V1,V2,S;
970 970
      do {
971 971
        V1=2*real<double>()-1;
972 972
        V2=2*real<double>()-1;
973 973
        S=V1*V1+V2*V2;
974 974
      } while(S>=1);
975 975
      double W=std::sqrt(-2*std::log(S)/S);
976 976
      return dim2::Point<double>(W*V1,W*V2);
977 977
    }
978 978
    /// A kind of two dimensional exponential distribution
979 979

	
980 980
    /// This function provides a turning symmetric two-dimensional distribution.
981 981
    /// The x-coordinate is of conditionally exponential distribution
982 982
    /// with the condition that x is positive and y=0. If x is negative and
983 983
    /// y=0 then, -x is of exponential distribution. The same is true for the
984 984
    /// y-coordinate.
985 985
    dim2::Point<double> exponential2()
986 986
    {
987 987
      double V1,V2,S;
988 988
      do {
989 989
        V1=2*real<double>()-1;
990 990
        V2=2*real<double>()-1;
991 991
        S=V1*V1+V2*V2;
992 992
      } while(S>=1);
993 993
      double W=-std::log(S)/S;
994 994
      return dim2::Point<double>(W*V1,W*V2);
995 995
    }
996 996

	
997 997
    ///@}
998 998
  };
999 999

	
1000 1000

	
1001 1001
  extern Random rnd;
1002 1002

	
1003 1003
}
1004 1004

	
1005 1005
#endif
Ignore white space 6 line context
... ...
@@ -35,474 +35,474 @@
35 35
  /// \addtogroup shortest_path
36 36
  /// @{
37 37

	
38 38
  /// \brief Algorithm for finding arc-disjoint paths between two nodes
39 39
  /// having minimum total length.
40 40
  ///
41 41
  /// \ref lemon::Suurballe "Suurballe" implements an algorithm for
42 42
  /// finding arc-disjoint paths having minimum total length (cost)
43 43
  /// from a given source node to a given target node in a digraph.
44 44
  ///
45 45
  /// In fact, this implementation is the specialization of the
46 46
  /// \ref CapacityScaling "successive shortest path" algorithm.
47 47
  ///
48 48
  /// \tparam GR The digraph type the algorithm runs on.
49 49
  /// The default value is \c ListDigraph.
50 50
  /// \tparam LEN The type of the length (cost) map.
51 51
  /// The default value is <tt>Digraph::ArcMap<int></tt>.
52 52
  ///
53 53
  /// \warning Length values should be \e non-negative \e integers.
54 54
  ///
55 55
  /// \note For finding node-disjoint paths this algorithm can be used
56 56
  /// with \ref SplitNodes.
57 57
#ifdef DOXYGEN
58 58
  template <typename GR, typename LEN>
59 59
#else
60 60
  template < typename GR = ListDigraph,
61 61
             typename LEN = typename GR::template ArcMap<int> >
62 62
#endif
63 63
  class Suurballe
64 64
  {
65 65
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
66 66

	
67 67
    typedef ConstMap<Arc, int> ConstArcMap;
68 68
    typedef typename GR::template NodeMap<Arc> PredMap;
69 69

	
70 70
  public:
71 71

	
72 72
    /// The type of the digraph the algorithm runs on.
73 73
    typedef GR Digraph;
74 74
    /// The type of the length map.
75 75
    typedef LEN LengthMap;
76 76
    /// The type of the lengths.
77 77
    typedef typename LengthMap::Value Length;
78 78
    /// The type of the flow map.
79 79
    typedef typename Digraph::template ArcMap<int> FlowMap;
80 80
    /// The type of the potential map.
81 81
    typedef typename Digraph::template NodeMap<Length> PotentialMap;
82 82
    /// The type of the path structures.
83 83
    typedef SimplePath<Digraph> Path;
84 84

	
85 85
  private:
86 86

	
87 87
    /// \brief Special implementation of the Dijkstra algorithm
88 88
    /// for finding shortest paths in the residual network.
89 89
    ///
90 90
    /// \ref ResidualDijkstra is a special implementation of the
91 91
    /// \ref Dijkstra algorithm for finding shortest paths in the
92 92
    /// residual network of the digraph with respect to the reduced arc
93 93
    /// lengths and modifying the node potentials according to the
94 94
    /// distance of the nodes.
95 95
    class ResidualDijkstra
96 96
    {
97 97
      typedef typename Digraph::template NodeMap<int> HeapCrossRef;
98 98
      typedef BinHeap<Length, HeapCrossRef> Heap;
99 99

	
100 100
    private:
101 101

	
102 102
      // The digraph the algorithm runs on
103 103
      const Digraph &_graph;
104 104

	
105 105
      // The main maps
106 106
      const FlowMap &_flow;
107 107
      const LengthMap &_length;
108 108
      PotentialMap &_potential;
109 109

	
110 110
      // The distance map
111 111
      PotentialMap _dist;
112 112
      // The pred arc map
113 113
      PredMap &_pred;
114 114
      // The processed (i.e. permanently labeled) nodes
115 115
      std::vector<Node> _proc_nodes;
116 116

	
117 117
      Node _s;
118 118
      Node _t;
119 119

	
120 120
    public:
121 121

	
122 122
      /// Constructor.
123 123
      ResidualDijkstra( const Digraph &digraph,
124 124
                        const FlowMap &flow,
125 125
                        const LengthMap &length,
126 126
                        PotentialMap &potential,
127 127
                        PredMap &pred,
128 128
                        Node s, Node t ) :
129 129
        _graph(digraph), _flow(flow), _length(length), _potential(potential),
130 130
        _dist(digraph), _pred(pred), _s(s), _t(t) {}
131 131

	
132 132
      /// \brief Run the algorithm. It returns \c true if a path is found
133 133
      /// from the source node to the target node.
134 134
      bool run() {
135 135
        HeapCrossRef heap_cross_ref(_graph, Heap::PRE_HEAP);
136 136
        Heap heap(heap_cross_ref);
137 137
        heap.push(_s, 0);
138 138
        _pred[_s] = INVALID;
139 139
        _proc_nodes.clear();
140 140

	
141 141
        // Process nodes
142 142
        while (!heap.empty() && heap.top() != _t) {
143 143
          Node u = heap.top(), v;
144 144
          Length d = heap.prio() + _potential[u], nd;
145 145
          _dist[u] = heap.prio();
146 146
          heap.pop();
147 147
          _proc_nodes.push_back(u);
148 148

	
149 149
          // Traverse outgoing arcs
150 150
          for (OutArcIt e(_graph, u); e != INVALID; ++e) {
151 151
            if (_flow[e] == 0) {
152 152
              v = _graph.target(e);
153 153
              switch(heap.state(v)) {
154 154
              case Heap::PRE_HEAP:
155 155
                heap.push(v, d + _length[e] - _potential[v]);
156 156
                _pred[v] = e;
157 157
                break;
158 158
              case Heap::IN_HEAP:
159 159
                nd = d + _length[e] - _potential[v];
160 160
                if (nd < heap[v]) {
161 161
                  heap.decrease(v, nd);
162 162
                  _pred[v] = e;
163 163
                }
164 164
                break;
165 165
              case Heap::POST_HEAP:
166 166
                break;
167 167
              }
168 168
            }
169 169
          }
170 170

	
171 171
          // Traverse incoming arcs
172 172
          for (InArcIt e(_graph, u); e != INVALID; ++e) {
173 173
            if (_flow[e] == 1) {
174 174
              v = _graph.source(e);
175 175
              switch(heap.state(v)) {
176 176
              case Heap::PRE_HEAP:
177 177
                heap.push(v, d - _length[e] - _potential[v]);
178 178
                _pred[v] = e;
179 179
                break;
180 180
              case Heap::IN_HEAP:
181 181
                nd = d - _length[e] - _potential[v];
182 182
                if (nd < heap[v]) {
183 183
                  heap.decrease(v, nd);
184 184
                  _pred[v] = e;
185 185
                }
186 186
                break;
187 187
              case Heap::POST_HEAP:
188 188
                break;
189 189
              }
190 190
            }
191 191
          }
192 192
        }
193 193
        if (heap.empty()) return false;
194 194

	
195 195
        // Update potentials of processed nodes
196 196
        Length t_dist = heap.prio();
197 197
        for (int i = 0; i < int(_proc_nodes.size()); ++i)
198 198
          _potential[_proc_nodes[i]] += _dist[_proc_nodes[i]] - t_dist;
199 199
        return true;
200 200
      }
201 201

	
202 202
    }; //class ResidualDijkstra
203 203

	
204 204
  private:
205 205

	
206 206
    // The digraph the algorithm runs on
207 207
    const Digraph &_graph;
208 208
    // The length map
209 209
    const LengthMap &_length;
210 210

	
211 211
    // Arc map of the current flow
212 212
    FlowMap *_flow;
213 213
    bool _local_flow;
214 214
    // Node map of the current potentials
215 215
    PotentialMap *_potential;
216 216
    bool _local_potential;
217 217

	
218 218
    // The source node
219 219
    Node _source;
220 220
    // The target node
221 221
    Node _target;
222 222

	
223 223
    // Container to store the found paths
224 224
    std::vector< SimplePath<Digraph> > paths;
225 225
    int _path_num;
226 226

	
227 227
    // The pred arc map
228 228
    PredMap _pred;
229 229
    // Implementation of the Dijkstra algorithm for finding augmenting
230 230
    // shortest paths in the residual network
231 231
    ResidualDijkstra *_dijkstra;
232 232

	
233 233
  public:
234 234

	
235 235
    /// \brief Constructor.
236 236
    ///
237 237
    /// Constructor.
238 238
    ///
239 239
    /// \param digraph The digraph the algorithm runs on.
240 240
    /// \param length The length (cost) values of the arcs.
241 241
    /// \param s The source node.
242 242
    /// \param t The target node.
243 243
    Suurballe( const Digraph &digraph,
244 244
               const LengthMap &length,
245 245
               Node s, Node t ) :
246 246
      _graph(digraph), _length(length), _flow(0), _local_flow(false),
247 247
      _potential(0), _local_potential(false), _source(s), _target(t),
248 248
      _pred(digraph) {}
249 249

	
250 250
    /// Destructor.
251 251
    ~Suurballe() {
252 252
      if (_local_flow) delete _flow;
253 253
      if (_local_potential) delete _potential;
254 254
      delete _dijkstra;
255 255
    }
256 256

	
257 257
    /// \brief Set the flow map.
258 258
    ///
259 259
    /// This function sets the flow map.
260 260
    ///
261 261
    /// The found flow contains only 0 and 1 values. It is the union of
262 262
    /// the found arc-disjoint paths.
263 263
    ///
264 264
    /// \return <tt>(*this)</tt>
265 265
    Suurballe& flowMap(FlowMap &map) {
266 266
      if (_local_flow) {
267 267
        delete _flow;
268 268
        _local_flow = false;
269 269
      }
270 270
      _flow = &map;
271 271
      return *this;
272 272
    }
273 273

	
274 274
    /// \brief Set the potential map.
275 275
    ///
276 276
    /// This function sets the potential map.
277 277
    ///
278 278
    /// The potentials provide the dual solution of the underlying
279 279
    /// minimum cost flow problem.
280 280
    ///
281 281
    /// \return <tt>(*this)</tt>
282 282
    Suurballe& potentialMap(PotentialMap &map) {
283 283
      if (_local_potential) {
284 284
        delete _potential;
285 285
        _local_potential = false;
286 286
      }
287 287
      _potential = &map;
288 288
      return *this;
289 289
    }
290 290

	
291
    /// \name Execution control
291
    /// \name Execution Control
292 292
    /// The simplest way to execute the algorithm is to call the run()
293 293
    /// function.
294 294
    /// \n
295 295
    /// If you only need the flow that is the union of the found
296 296
    /// arc-disjoint paths, you may call init() and findFlow().
297 297

	
298 298
    /// @{
299 299

	
300 300
    /// \brief Run the algorithm.
301 301
    ///
302 302
    /// This function runs the algorithm.
303 303
    ///
304 304
    /// \param k The number of paths to be found.
305 305
    ///
306 306
    /// \return \c k if there are at least \c k arc-disjoint paths from
307 307
    /// \c s to \c t in the digraph. Otherwise it returns the number of
308 308
    /// arc-disjoint paths found.
309 309
    ///
310 310
    /// \note Apart from the return value, <tt>s.run(k)</tt> is just a
311 311
    /// shortcut of the following code.
312 312
    /// \code
313 313
    ///   s.init();
314 314
    ///   s.findFlow(k);
315 315
    ///   s.findPaths();
316 316
    /// \endcode
317 317
    int run(int k = 2) {
318 318
      init();
319 319
      findFlow(k);
320 320
      findPaths();
321 321
      return _path_num;
322 322
    }
323 323

	
324 324
    /// \brief Initialize the algorithm.
325 325
    ///
326 326
    /// This function initializes the algorithm.
327 327
    void init() {
328 328
      // Initialize maps
329 329
      if (!_flow) {
330 330
        _flow = new FlowMap(_graph);
331 331
        _local_flow = true;
332 332
      }
333 333
      if (!_potential) {
334 334
        _potential = new PotentialMap(_graph);
335 335
        _local_potential = true;
336 336
      }
337 337
      for (ArcIt e(_graph); e != INVALID; ++e) (*_flow)[e] = 0;
338 338
      for (NodeIt n(_graph); n != INVALID; ++n) (*_potential)[n] = 0;
339 339

	
340 340
      _dijkstra = new ResidualDijkstra( _graph, *_flow, _length,
341 341
                                        *_potential, _pred,
342 342
                                        _source, _target );
343 343
    }
344 344

	
345 345
    /// \brief Execute the successive shortest path algorithm to find
346 346
    /// an optimal flow.
347 347
    ///
348 348
    /// This function executes the successive shortest path algorithm to
349 349
    /// find a minimum cost flow, which is the union of \c k or less
350 350
    /// arc-disjoint paths.
351 351
    ///
352 352
    /// \return \c k if there are at least \c k arc-disjoint paths from
353 353
    /// \c s to \c t in the digraph. Otherwise it returns the number of
354 354
    /// arc-disjoint paths found.
355 355
    ///
356 356
    /// \pre \ref init() must be called before using this function.
357 357
    int findFlow(int k = 2) {
358 358
      // Find shortest paths
359 359
      _path_num = 0;
360 360
      while (_path_num < k) {
361 361
        // Run Dijkstra
362 362
        if (!_dijkstra->run()) break;
363 363
        ++_path_num;
364 364

	
365 365
        // Set the flow along the found shortest path
366 366
        Node u = _target;
367 367
        Arc e;
368 368
        while ((e = _pred[u]) != INVALID) {
369 369
          if (u == _graph.target(e)) {
370 370
            (*_flow)[e] = 1;
371 371
            u = _graph.source(e);
372 372
          } else {
373 373
            (*_flow)[e] = 0;
374 374
            u = _graph.target(e);
375 375
          }
376 376
        }
377 377
      }
378 378
      return _path_num;
379 379
    }
380 380

	
381 381
    /// \brief Compute the paths from the flow.
382 382
    ///
383 383
    /// This function computes the paths from the flow.
384 384
    ///
385 385
    /// \pre \ref init() and \ref findFlow() must be called before using
386 386
    /// this function.
387 387
    void findPaths() {
388 388
      // Create the residual flow map (the union of the paths not found
389 389
      // so far)
390 390
      FlowMap res_flow(_graph);
391 391
      for(ArcIt a(_graph); a != INVALID; ++a) res_flow[a] = (*_flow)[a];
392 392

	
393 393
      paths.clear();
394 394
      paths.resize(_path_num);
395 395
      for (int i = 0; i < _path_num; ++i) {
396 396
        Node n = _source;
397 397
        while (n != _target) {
398 398
          OutArcIt e(_graph, n);
399 399
          for ( ; res_flow[e] == 0; ++e) ;
400 400
          n = _graph.target(e);
401 401
          paths[i].addBack(e);
402 402
          res_flow[e] = 0;
403 403
        }
404 404
      }
405 405
    }
406 406

	
407 407
    /// @}
408 408

	
409 409
    /// \name Query Functions
410 410
    /// The results of the algorithm can be obtained using these
411 411
    /// functions.
412 412
    /// \n The algorithm should be executed before using them.
413 413

	
414 414
    /// @{
415 415

	
416 416
    /// \brief Return a const reference to the arc map storing the
417 417
    /// found flow.
418 418
    ///
419 419
    /// This function returns a const reference to the arc map storing
420 420
    /// the flow that is the union of the found arc-disjoint paths.
421 421
    ///
422 422
    /// \pre \ref run() or \ref findFlow() must be called before using
423 423
    /// this function.
424 424
    const FlowMap& flowMap() const {
425 425
      return *_flow;
426 426
    }
427 427

	
428 428
    /// \brief Return a const reference to the node map storing the
429 429
    /// found potentials (the dual solution).
430 430
    ///
431 431
    /// This function returns a const reference to the node map storing
432 432
    /// the found potentials that provide the dual solution of the
433 433
    /// underlying minimum cost flow problem.
434 434
    ///
435 435
    /// \pre \ref run() or \ref findFlow() must be called before using
436 436
    /// this function.
437 437
    const PotentialMap& potentialMap() const {
438 438
      return *_potential;
439 439
    }
440 440

	
441 441
    /// \brief Return the flow on the given arc.
442 442
    ///
443 443
    /// This function returns the flow on the given arc.
444 444
    /// It is \c 1 if the arc is involved in one of the found paths,
445 445
    /// otherwise it is \c 0.
446 446
    ///
447 447
    /// \pre \ref run() or \ref findFlow() must be called before using
448 448
    /// this function.
449 449
    int flow(const Arc& arc) const {
450 450
      return (*_flow)[arc];
451 451
    }
452 452

	
453 453
    /// \brief Return the potential of the given node.
454 454
    ///
455 455
    /// This function returns the potential of the given node.
456 456
    ///
457 457
    /// \pre \ref run() or \ref findFlow() must be called before using
458 458
    /// this function.
459 459
    Length potential(const Node& node) const {
460 460
      return (*_potential)[node];
461 461
    }
462 462

	
463 463
    /// \brief Return the total length (cost) of the found paths (flow).
464 464
    ///
465 465
    /// This function returns the total length (cost) of the found paths
466 466
    /// (flow). The complexity of the function is O(e).
467 467
    ///
468 468
    /// \pre \ref run() or \ref findFlow() must be called before using
469 469
    /// this function.
470 470
    Length totalLength() const {
471 471
      Length c = 0;
472 472
      for (ArcIt e(_graph); e != INVALID; ++e)
473 473
        c += (*_flow)[e] * _length[e];
474 474
      return c;
475 475
    }
476 476

	
477 477
    /// \brief Return the number of the found paths.
478 478
    ///
479 479
    /// This function returns the number of the found paths.
480 480
    ///
481 481
    /// \pre \ref run() or \ref findFlow() must be called before using
482 482
    /// this function.
483 483
    int pathNum() const {
484 484
      return _path_num;
485 485
    }
486 486

	
487 487
    /// \brief Return a const reference to the specified path.
488 488
    ///
489 489
    /// This function returns a const reference to the specified path.
490 490
    ///
491 491
    /// \param i The function returns the \c i-th path.
492 492
    /// \c i must be between \c 0 and <tt>%pathNum()-1</tt>.
493 493
    ///
494 494
    /// \pre \ref run() or \ref findPaths() must be called before using
495 495
    /// this function.
496 496
    Path path(int i) const {
497 497
      return paths[i];
498 498
    }
499 499

	
500 500
    /// @}
501 501

	
502 502
  }; //class Suurballe
503 503

	
504 504
  ///@}
505 505

	
506 506
} //namespace lemon
507 507

	
508 508
#endif //LEMON_SUURBALLE_H
Ignore white space 6 line context
... ...
@@ -34,519 +34,519 @@
34 34
#include <string>
35 35
#include <fstream>
36 36
#include <iostream>
37 37

	
38 38
namespace lemon {
39 39

	
40 40
  /// \addtogroup timecount
41 41
  /// @{
42 42

	
43 43
  /// A class to store (cpu)time instances.
44 44

	
45 45
  /// This class stores five time values.
46 46
  /// - a real time
47 47
  /// - a user cpu time
48 48
  /// - a system cpu time
49 49
  /// - a user cpu time of children
50 50
  /// - a system cpu time of children
51 51
  ///
52 52
  /// TimeStamp's can be added to or substracted from each other and
53 53
  /// they can be pushed to a stream.
54 54
  ///
55 55
  /// In most cases, perhaps the \ref Timer or the \ref TimeReport
56 56
  /// class is what you want to use instead.
57 57

	
58 58
  class TimeStamp
59 59
  {
60 60
    double utime;
61 61
    double stime;
62 62
    double cutime;
63 63
    double cstime;
64 64
    double rtime;
65 65

	
66 66
    void _reset() {
67 67
      utime = stime = cutime = cstime = rtime = 0;
68 68
    }
69 69

	
70 70
  public:
71 71

	
72 72
    ///Read the current time values of the process
73 73
    void stamp()
74 74
    {
75 75
#ifndef WIN32
76 76
      timeval tv;
77 77
      gettimeofday(&tv, 0);
78 78
      rtime=tv.tv_sec+double(tv.tv_usec)/1e6;
79 79

	
80 80
      tms ts;
81 81
      double tck=sysconf(_SC_CLK_TCK);
82 82
      times(&ts);
83 83
      utime=ts.tms_utime/tck;
84 84
      stime=ts.tms_stime/tck;
85 85
      cutime=ts.tms_cutime/tck;
86 86
      cstime=ts.tms_cstime/tck;
87 87
#else
88 88
      bits::getWinProcTimes(rtime, utime, stime, cutime, cstime);
89 89
#endif
90 90
    }
91 91

	
92 92
    /// Constructor initializing with zero
93 93
    TimeStamp()
94 94
    { _reset(); }
95 95
    ///Constructor initializing with the current time values of the process
96 96
    TimeStamp(void *) { stamp();}
97 97

	
98 98
    ///Set every time value to zero
99 99
    TimeStamp &reset() {_reset();return *this;}
100 100

	
101 101
    ///\e
102 102
    TimeStamp &operator+=(const TimeStamp &b)
103 103
    {
104 104
      utime+=b.utime;
105 105
      stime+=b.stime;
106 106
      cutime+=b.cutime;
107 107
      cstime+=b.cstime;
108 108
      rtime+=b.rtime;
109 109
      return *this;
110 110
    }
111 111
    ///\e
112 112
    TimeStamp operator+(const TimeStamp &b) const
113 113
    {
114 114
      TimeStamp t(*this);
115 115
      return t+=b;
116 116
    }
117 117
    ///\e
118 118
    TimeStamp &operator-=(const TimeStamp &b)
119 119
    {
120 120
      utime-=b.utime;
121 121
      stime-=b.stime;
122 122
      cutime-=b.cutime;
123 123
      cstime-=b.cstime;
124 124
      rtime-=b.rtime;
125 125
      return *this;
126 126
    }
127 127
    ///\e
128 128
    TimeStamp operator-(const TimeStamp &b) const
129 129
    {
130 130
      TimeStamp t(*this);
131 131
      return t-=b;
132 132
    }
133 133
    ///\e
134 134
    TimeStamp &operator*=(double b)
135 135
    {
136 136
      utime*=b;
137 137
      stime*=b;
138 138
      cutime*=b;
139 139
      cstime*=b;
140 140
      rtime*=b;
141 141
      return *this;
142 142
    }
143 143
    ///\e
144 144
    TimeStamp operator*(double b) const
145 145
    {
146 146
      TimeStamp t(*this);
147 147
      return t*=b;
148 148
    }
149 149
    friend TimeStamp operator*(double b,const TimeStamp &t);
150 150
    ///\e
151 151
    TimeStamp &operator/=(double b)
152 152
    {
153 153
      utime/=b;
154 154
      stime/=b;
155 155
      cutime/=b;
156 156
      cstime/=b;
157 157
      rtime/=b;
158 158
      return *this;
159 159
    }
160 160
    ///\e
161 161
    TimeStamp operator/(double b) const
162 162
    {
163 163
      TimeStamp t(*this);
164 164
      return t/=b;
165 165
    }
166 166
    ///The time ellapsed since the last call of stamp()
167 167
    TimeStamp ellapsed() const
168 168
    {
169 169
      TimeStamp t(NULL);
170 170
      return t-*this;
171 171
    }
172 172

	
173 173
    friend std::ostream& operator<<(std::ostream& os,const TimeStamp &t);
174 174

	
175 175
    ///Gives back the user time of the process
176 176
    double userTime() const
177 177
    {
178 178
      return utime;
179 179
    }
180 180
    ///Gives back the system time of the process
181 181
    double systemTime() const
182 182
    {
183 183
      return stime;
184 184
    }
185 185
    ///Gives back the user time of the process' children
186 186

	
187 187
    ///\note On <tt>WIN32</tt> platform this value is not calculated.
188 188
    ///
189 189
    double cUserTime() const
190 190
    {
191 191
      return cutime;
192 192
    }
193 193
    ///Gives back the user time of the process' children
194 194

	
195 195
    ///\note On <tt>WIN32</tt> platform this value is not calculated.
196 196
    ///
197 197
    double cSystemTime() const
198 198
    {
199 199
      return cstime;
200 200
    }
201 201
    ///Gives back the real time
202 202
    double realTime() const {return rtime;}
203 203
  };
204 204

	
205 205
  inline TimeStamp operator*(double b,const TimeStamp &t)
206 206
  {
207 207
    return t*b;
208 208
  }
209 209

	
210 210
  ///Prints the time counters
211 211

	
212 212
  ///Prints the time counters in the following form:
213 213
  ///
214 214
  /// <tt>u: XX.XXs s: XX.XXs cu: XX.XXs cs: XX.XXs real: XX.XXs</tt>
215 215
  ///
216 216
  /// where the values are the
217 217
  /// \li \c u: user cpu time,
218 218
  /// \li \c s: system cpu time,
219 219
  /// \li \c cu: user cpu time of children,
220 220
  /// \li \c cs: system cpu time of children,
221 221
  /// \li \c real: real time.
222 222
  /// \relates TimeStamp
223 223
  /// \note On <tt>WIN32</tt> platform the cummulative values are not
224 224
  /// calculated.
225 225
  inline std::ostream& operator<<(std::ostream& os,const TimeStamp &t)
226 226
  {
227 227
    os << "u: " << t.userTime() <<
228 228
      "s, s: " << t.systemTime() <<
229 229
      "s, cu: " << t.cUserTime() <<
230 230
      "s, cs: " << t.cSystemTime() <<
231 231
      "s, real: " << t.realTime() << "s";
232 232
    return os;
233 233
  }
234 234

	
235 235
  ///Class for measuring the cpu time and real time usage of the process
236 236

	
237 237
  ///Class for measuring the cpu time and real time usage of the process.
238 238
  ///It is quite easy-to-use, here is a short example.
239 239
  ///\code
240 240
  /// #include<lemon/time_measure.h>
241 241
  /// #include<iostream>
242 242
  ///
243 243
  /// int main()
244 244
  /// {
245 245
  ///
246 246
  ///   ...
247 247
  ///
248 248
  ///   Timer t;
249 249
  ///   doSomething();
250 250
  ///   std::cout << t << '\n';
251 251
  ///   t.restart();
252 252
  ///   doSomethingElse();
253 253
  ///   std::cout << t << '\n';
254 254
  ///
255 255
  ///   ...
256 256
  ///
257 257
  /// }
258 258
  ///\endcode
259 259
  ///
260 260
  ///The \ref Timer can also be \ref stop() "stopped" and
261 261
  ///\ref start() "started" again, so it is possible to compute collected
262 262
  ///running times.
263 263
  ///
264 264
  ///\warning Depending on the operation system and its actual configuration
265 265
  ///the time counters have a certain (10ms on a typical Linux system)
266 266
  ///granularity.
267 267
  ///Therefore this tool is not appropriate to measure very short times.
268 268
  ///Also, if you start and stop the timer very frequently, it could lead to
269 269
  ///distorted results.
270 270
  ///
271 271
  ///\note If you want to measure the running time of the execution of a certain
272 272
  ///function, consider the usage of \ref TimeReport instead.
273 273
  ///
274 274
  ///\sa TimeReport
275 275
  class Timer
276 276
  {
277 277
    int _running; //Timer is running iff _running>0; (_running>=0 always holds)
278 278
    TimeStamp start_time; //This is the relativ start-time if the timer
279 279
                          //is _running, the collected _running time otherwise.
280 280

	
281 281
    void _reset() {if(_running) start_time.stamp(); else start_time.reset();}
282 282

	
283 283
  public:
284 284
    ///Constructor.
285 285

	
286 286
    ///\param run indicates whether or not the timer starts immediately.
287 287
    ///
288 288
    Timer(bool run=true) :_running(run) {_reset();}
289 289

	
290
    ///\name Control the state of the timer
290
    ///\name Control the State of the Timer
291 291
    ///Basically a Timer can be either running or stopped,
292 292
    ///but it provides a bit finer control on the execution.
293 293
    ///The \ref lemon::Timer "Timer" also counts the number of
294 294
    ///\ref lemon::Timer::start() "start()" executions, and it stops
295 295
    ///only after the same amount (or more) \ref lemon::Timer::stop()
296 296
    ///"stop()"s. This can be useful e.g. to compute the running time
297 297
    ///of recursive functions.
298 298

	
299 299
    ///@{
300 300

	
301 301
    ///Reset and stop the time counters
302 302

	
303 303
    ///This function resets and stops the time counters
304 304
    ///\sa restart()
305 305
    void reset()
306 306
    {
307 307
      _running=0;
308 308
      _reset();
309 309
    }
310 310

	
311 311
    ///Start the time counters
312 312

	
313 313
    ///This function starts the time counters.
314 314
    ///
315 315
    ///If the timer is started more than ones, it will remain running
316 316
    ///until the same amount of \ref stop() is called.
317 317
    ///\sa stop()
318 318
    void start()
319 319
    {
320 320
      if(_running) _running++;
321 321
      else {
322 322
        _running=1;
323 323
        TimeStamp t;
324 324
        t.stamp();
325 325
        start_time=t-start_time;
326 326
      }
327 327
    }
328 328

	
329 329

	
330 330
    ///Stop the time counters
331 331

	
332 332
    ///This function stops the time counters. If start() was executed more than
333 333
    ///once, then the same number of stop() execution is necessary the really
334 334
    ///stop the timer.
335 335
    ///
336 336
    ///\sa halt()
337 337
    ///\sa start()
338 338
    ///\sa restart()
339 339
    ///\sa reset()
340 340

	
341 341
    void stop()
342 342
    {
343 343
      if(_running && !--_running) {
344 344
        TimeStamp t;
345 345
        t.stamp();
346 346
        start_time=t-start_time;
347 347
      }
348 348
    }
349 349

	
350 350
    ///Halt (i.e stop immediately) the time counters
351 351

	
352 352
    ///This function stops immediately the time counters, i.e. <tt>t.halt()</tt>
353 353
    ///is a faster
354 354
    ///equivalent of the following.
355 355
    ///\code
356 356
    ///  while(t.running()) t.stop()
357 357
    ///\endcode
358 358
    ///
359 359
    ///
360 360
    ///\sa stop()
361 361
    ///\sa restart()
362 362
    ///\sa reset()
363 363

	
364 364
    void halt()
365 365
    {
366 366
      if(_running) {
367 367
        _running=0;
368 368
        TimeStamp t;
369 369
        t.stamp();
370 370
        start_time=t-start_time;
371 371
      }
372 372
    }
373 373

	
374 374
    ///Returns the running state of the timer
375 375

	
376 376
    ///This function returns the number of stop() exections that is
377 377
    ///necessary to really stop the timer.
378 378
    ///For example the timer
379 379
    ///is running if and only if the return value is \c true
380 380
    ///(i.e. greater than
381 381
    ///zero).
382 382
    int running()  { return _running; }
383 383

	
384 384

	
385 385
    ///Restart the time counters
386 386

	
387 387
    ///This function is a shorthand for
388 388
    ///a reset() and a start() calls.
389 389
    ///
390 390
    void restart()
391 391
    {
392 392
      reset();
393 393
      start();
394 394
    }
395 395

	
396 396
    ///@}
397 397

	
398
    ///\name Query Functions for the ellapsed time
398
    ///\name Query Functions for the Ellapsed Time
399 399

	
400 400
    ///@{
401 401

	
402 402
    ///Gives back the ellapsed user time of the process
403 403
    double userTime() const
404 404
    {
405 405
      return operator TimeStamp().userTime();
406 406
    }
407 407
    ///Gives back the ellapsed system time of the process
408 408
    double systemTime() const
409 409
    {
410 410
      return operator TimeStamp().systemTime();
411 411
    }
412 412
    ///Gives back the ellapsed user time of the process' children
413 413

	
414 414
    ///\note On <tt>WIN32</tt> platform this value is not calculated.
415 415
    ///
416 416
    double cUserTime() const
417 417
    {
418 418
      return operator TimeStamp().cUserTime();
419 419
    }
420 420
    ///Gives back the ellapsed user time of the process' children
421 421

	
422 422
    ///\note On <tt>WIN32</tt> platform this value is not calculated.
423 423
    ///
424 424
    double cSystemTime() const
425 425
    {
426 426
      return operator TimeStamp().cSystemTime();
427 427
    }
428 428
    ///Gives back the ellapsed real time
429 429
    double realTime() const
430 430
    {
431 431
      return operator TimeStamp().realTime();
432 432
    }
433 433
    ///Computes the ellapsed time
434 434

	
435 435
    ///This conversion computes the ellapsed time, therefore you can print
436 436
    ///the ellapsed time like this.
437 437
    ///\code
438 438
    ///  Timer t;
439 439
    ///  doSomething();
440 440
    ///  std::cout << t << '\n';
441 441
    ///\endcode
442 442
    operator TimeStamp () const
443 443
    {
444 444
      TimeStamp t;
445 445
      t.stamp();
446 446
      return _running?t-start_time:start_time;
447 447
    }
448 448

	
449 449

	
450 450
    ///@}
451 451
  };
452 452

	
453 453
  ///Same as Timer but prints a report on destruction.
454 454

	
455 455
  ///Same as \ref Timer but prints a report on destruction.
456 456
  ///This example shows its usage.
457 457
  ///\code
458 458
  ///  void myAlg(ListGraph &g,int n)
459 459
  ///  {
460 460
  ///    TimeReport tr("Running time of myAlg: ");
461 461
  ///    ... //Here comes the algorithm
462 462
  ///  }
463 463
  ///\endcode
464 464
  ///
465 465
  ///\sa Timer
466 466
  ///\sa NoTimeReport
467 467
  class TimeReport : public Timer
468 468
  {
469 469
    std::string _title;
470 470
    std::ostream &_os;
471 471
  public:
472 472
    ///Constructor
473 473

	
474 474
    ///Constructor.
475 475
    ///\param title This text will be printed before the ellapsed time.
476 476
    ///\param os The stream to print the report to.
477 477
    ///\param run Sets whether the timer should start immediately.
478 478
    TimeReport(std::string title,std::ostream &os=std::cerr,bool run=true)
479 479
      : Timer(run), _title(title), _os(os){}
480 480
    ///Destructor that prints the ellapsed time
481 481
    ~TimeReport()
482 482
    {
483 483
      _os << _title << *this << std::endl;
484 484
    }
485 485
  };
486 486

	
487 487
  ///'Do nothing' version of TimeReport
488 488

	
489 489
  ///\sa TimeReport
490 490
  ///
491 491
  class NoTimeReport
492 492
  {
493 493
  public:
494 494
    ///\e
495 495
    NoTimeReport(std::string,std::ostream &,bool) {}
496 496
    ///\e
497 497
    NoTimeReport(std::string,std::ostream &) {}
498 498
    ///\e
499 499
    NoTimeReport(std::string) {}
500 500
    ///\e Do nothing.
501 501
    ~NoTimeReport() {}
502 502

	
503 503
    operator TimeStamp () const { return TimeStamp(); }
504 504
    void reset() {}
505 505
    void start() {}
506 506
    void stop() {}
507 507
    void halt() {}
508 508
    int running() { return 0; }
509 509
    void restart() {}
510 510
    double userTime() const { return 0; }
511 511
    double systemTime() const { return 0; }
512 512
    double cUserTime() const { return 0; }
513 513
    double cSystemTime() const { return 0; }
514 514
    double realTime() const { return 0; }
515 515
  };
516 516

	
517 517
  ///Tool to measure the running time more exactly.
518 518

	
519 519
  ///This function calls \c f several times and returns the average
520 520
  ///running time. The number of the executions will be choosen in such a way
521 521
  ///that the full real running time will be roughly between \c min_time
522 522
  ///and <tt>2*min_time</tt>.
523 523
  ///\param f the function object to be measured.
524 524
  ///\param min_time the minimum total running time.
525 525
  ///\retval num if it is not \c NULL, then the actual
526 526
  ///        number of execution of \c f will be written into <tt>*num</tt>.
527 527
  ///\retval full_time if it is not \c NULL, then the actual
528 528
  ///        total running time will be written into <tt>*full_time</tt>.
529 529
  ///\return The average running time of \c f.
530 530

	
531 531
  template<class F>
532 532
  TimeStamp runningTimeTest(F f,double min_time=10,unsigned int *num = NULL,
533 533
                            TimeStamp *full_time=NULL)
534 534
  {
535 535
    TimeStamp full;
536 536
    unsigned int total=0;
537 537
    Timer t;
538 538
    for(unsigned int tn=1;tn <= 1U<<31 && full.realTime()<=min_time; tn*=2) {
539 539
      for(;total<tn;total++) f();
540 540
      full=t;
541 541
    }
542 542
    if(num) *num=total;
543 543
    if(full_time) *full_time=full;
544 544
    return full/total;
545 545
  }
546 546

	
547 547
  /// @}
548 548

	
549 549

	
550 550
} //namespace lemon
551 551

	
552 552
#endif //LEMON_TIME_MEASURE_H
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
///\ingroup tools
20 20
///\file
21 21
///\brief DIMACS problem solver.
22 22
///
23 23
/// This program solves various problems given in DIMACS format.
24 24
///
25 25
/// See
26
/// \verbatim
27
///  dimacs-solver --help
28
/// \endverbatim
26
/// \code
27
///   dimacs-solver --help
28
/// \endcode
29 29
/// for more info on usage.
30
///
31 30

	
32 31
#include <iostream>
33 32
#include <fstream>
34 33
#include <cstring>
35 34

	
36 35
#include <lemon/smart_graph.h>
37 36
#include <lemon/dimacs.h>
38 37
#include <lemon/lgf_writer.h>
39 38
#include <lemon/time_measure.h>
40 39

	
41 40
#include <lemon/arg_parser.h>
42 41
#include <lemon/error.h>
43 42

	
44 43
#include <lemon/dijkstra.h>
45 44
#include <lemon/preflow.h>
46 45
#include <lemon/max_matching.h>
47 46

	
48 47
using namespace lemon;
49 48
typedef SmartDigraph Digraph;
50 49
DIGRAPH_TYPEDEFS(Digraph);
51 50
typedef SmartGraph Graph;
52 51

	
53 52
template<class Value>
54 53
void solve_sp(ArgParser &ap, std::istream &is, std::ostream &,
55 54
              DimacsDescriptor &desc)
56 55
{
57 56
  bool report = !ap.given("q");
58 57
  Digraph g;
59 58
  Node s;
60 59
  Digraph::ArcMap<Value> len(g);
61 60
  Timer t;
62 61
  t.restart();
63 62
  readDimacsSp(is, g, len, s, desc);
64 63
  if(report) std::cerr << "Read the file: " << t << '\n';
65 64
  t.restart();
66 65
  Dijkstra<Digraph, Digraph::ArcMap<Value> > dij(g,len);
67 66
  if(report) std::cerr << "Setup Dijkstra class: " << t << '\n';
68 67
  t.restart();
69 68
  dij.run(s);
70 69
  if(report) std::cerr << "Run Dijkstra: " << t << '\n';
71 70
}
72 71

	
73 72
template<class Value>
74 73
void solve_max(ArgParser &ap, std::istream &is, std::ostream &,
75 74
               Value infty, DimacsDescriptor &desc)
76 75
{
77 76
  bool report = !ap.given("q");
78 77
  Digraph g;
79 78
  Node s,t;
80 79
  Digraph::ArcMap<Value> cap(g);
81 80
  Timer ti;
82 81
  ti.restart();
83 82
  readDimacsMax(is, g, cap, s, t, infty, desc);
84 83
  if(report) std::cerr << "Read the file: " << ti << '\n';
85 84
  ti.restart();
86 85
  Preflow<Digraph, Digraph::ArcMap<Value> > pre(g,cap,s,t);
87 86
  if(report) std::cerr << "Setup Preflow class: " << ti << '\n';
88 87
  ti.restart();
89 88
  pre.run();
90 89
  if(report) std::cerr << "Run Preflow: " << ti << '\n';
91 90
  if(report) std::cerr << "\nMax flow value: " << pre.flowValue() << '\n';  
92 91
}
93 92

	
94 93
void solve_mat(ArgParser &ap, std::istream &is, std::ostream &,
95 94
              DimacsDescriptor &desc)
96 95
{
97 96
  bool report = !ap.given("q");
98 97
  Graph g;
99 98
  Timer ti;
100 99
  ti.restart();
101 100
  readDimacsMat(is, g, desc);
102 101
  if(report) std::cerr << "Read the file: " << ti << '\n';
103 102
  ti.restart();
104 103
  MaxMatching<Graph> mat(g);
105 104
  if(report) std::cerr << "Setup MaxMatching class: " << ti << '\n';
106 105
  ti.restart();
107 106
  mat.run();
108 107
  if(report) std::cerr << "Run MaxMatching: " << ti << '\n';
109 108
  if(report) std::cerr << "\nCardinality of max matching: "
110 109
                       << mat.matchingSize() << '\n';  
111 110
}
112 111

	
113 112

	
114 113
template<class Value>
115 114
void solve(ArgParser &ap, std::istream &is, std::ostream &os,
116 115
           DimacsDescriptor &desc)
117 116
{
118 117
  std::stringstream iss(static_cast<std::string>(ap["infcap"]));
119 118
  Value infty;
120 119
  iss >> infty;
121 120
  if(iss.fail())
122 121
    {
123 122
      std::cerr << "Cannot interpret '"
124 123
                << static_cast<std::string>(ap["infcap"]) << "' as infinite"
125 124
                << std::endl;
126 125
      exit(1);
127 126
    }
128 127
  
129 128
  switch(desc.type)
130 129
    {
131 130
    case DimacsDescriptor::MIN:
132 131
      std::cerr <<
133 132
        "\n\n Sorry, the min. cost flow solver is not yet available.\n";
134 133
      break;
135 134
    case DimacsDescriptor::MAX:
136 135
      solve_max<Value>(ap,is,os,infty,desc);
137 136
      break;
138 137
    case DimacsDescriptor::SP:
139 138
      solve_sp<Value>(ap,is,os,desc);
140 139
      break;
141 140
    case DimacsDescriptor::MAT:
142 141
      solve_mat(ap,is,os,desc);
143 142
      break;
144 143
    default:
145 144
      break;
146 145
    }
147 146
}
148 147

	
149 148
int main(int argc, const char *argv[]) {
150 149
  typedef SmartDigraph Digraph;
151 150

	
152 151
  typedef Digraph::Arc Arc;
153 152

	
154 153
  std::string inputName;
155 154
  std::string outputName;
156 155

	
157 156
  ArgParser ap(argc, argv);
158 157
  ap.other("[INFILE [OUTFILE]]",
159 158
           "If either the INFILE or OUTFILE file is missing the standard\n"
160 159
           "     input/output will be used instead.")
161 160
    .boolOption("q", "Do not print any report")
162 161
    .boolOption("int","Use 'int' for capacities, costs etc. (default)")
163 162
    .optionGroup("datatype","int")
164 163
#ifdef HAVE_LONG_LONG
165 164
    .boolOption("long","Use 'long long' for capacities, costs etc.")
166 165
    .optionGroup("datatype","long")
167 166
#endif
168 167
    .boolOption("double","Use 'double' for capacities, costs etc.")
169 168
    .optionGroup("datatype","double")
170 169
    .boolOption("ldouble","Use 'long double' for capacities, costs etc.")
171 170
    .optionGroup("datatype","ldouble")
172 171
    .onlyOneGroup("datatype")
173 172
    .stringOption("infcap","Value used for 'very high' capacities","0")
174 173
    .run();
175 174

	
176 175
  std::ifstream input;
177 176
  std::ofstream output;
178 177

	
179 178
  switch(ap.files().size())
180 179
    {
181 180
    case 2:
182 181
      output.open(ap.files()[1].c_str());
183 182
      if (!output) {
184 183
        throw IoError("Cannot open the file for writing", ap.files()[1]);
185 184
      }
186 185
    case 1:
187 186
      input.open(ap.files()[0].c_str());
188 187
      if (!input) {
189 188
        throw IoError("File cannot be found", ap.files()[0]);
190 189
      }
191 190
    case 0:
192 191
      break;
193 192
    default:
194 193
      std::cerr << ap.commandName() << ": too many arguments\n";
195 194
      return 1;
196 195
    }
197 196
  std::istream& is = (ap.files().size()<1 ? std::cin : input);
198 197
  std::ostream& os = (ap.files().size()<2 ? std::cout : output);
199 198

	
200 199
  DimacsDescriptor desc = dimacsType(is);
201 200
  
202 201
  if(!ap.given("q"))
203 202
    {
204 203
      std::cout << "Problem type: ";
205 204
      switch(desc.type)
206 205
        {
207 206
        case DimacsDescriptor::MIN:
208 207
          std::cout << "min";
209 208
          break;
210 209
        case DimacsDescriptor::MAX:
211 210
          std::cout << "max";
212 211
          break;
213 212
        case DimacsDescriptor::SP:
214 213
          std::cout << "sp";
215 214
        case DimacsDescriptor::MAT:
216 215
          std::cout << "mat";
217 216
          break;
218 217
        default:
219 218
          exit(1);
220 219
          break;
221 220
        }
222 221
      std::cout << "\nNum of nodes: " << desc.nodeNum;
223 222
      std::cout << "\nNum of arcs:  " << desc.edgeNum;
224 223
      std::cout << "\n\n";
225 224
    }
226 225
    
227 226
  if(ap.given("double"))
228 227
    solve<double>(ap,is,os,desc);
229 228
  else if(ap.given("ldouble"))
230 229
    solve<long double>(ap,is,os,desc);
231 230
#ifdef HAVE_LONG_LONG
232 231
  else if(ap.given("long"))
233 232
    solve<long long>(ap,is,os,desc);
234 233
#endif
235 234
  else solve<int>(ap,is,os,desc);
236 235

	
237 236
  return 0;
238 237
}
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
///\ingroup tools
20 20
///\file
21 21
///\brief DIMACS to LGF converter.
22 22
///
23 23
/// This program converts various DIMACS formats to the LEMON Digraph Format
24 24
/// (LGF).
25 25
///
26 26
/// See
27
/// \verbatim
28
///  dimacs-to-lgf --help
29
/// \endverbatim
30
/// for more info on usage.
31
///
27
/// \code
28
///   dimacs-to-lgf --help
29
/// \endcode
30
/// for more info on the usage.
32 31

	
33 32
#include <iostream>
34 33
#include <fstream>
35 34
#include <cstring>
36 35

	
37 36
#include <lemon/smart_graph.h>
38 37
#include <lemon/dimacs.h>
39 38
#include <lemon/lgf_writer.h>
40 39

	
41 40
#include <lemon/arg_parser.h>
42 41
#include <lemon/error.h>
43 42

	
44 43
using namespace std;
45 44
using namespace lemon;
46 45

	
47 46

	
48 47
int main(int argc, const char *argv[]) {
49 48
  typedef SmartDigraph Digraph;
50 49

	
51 50
  typedef Digraph::Arc Arc;
52 51
  typedef Digraph::Node Node;
53 52
  typedef Digraph::ArcIt ArcIt;
54 53
  typedef Digraph::NodeIt NodeIt;
55 54
  typedef Digraph::ArcMap<double> DoubleArcMap;
56 55
  typedef Digraph::NodeMap<double> DoubleNodeMap;
57 56

	
58 57
  std::string inputName;
59 58
  std::string outputName;
60 59

	
61 60
  ArgParser ap(argc, argv);
62 61
  ap.other("[INFILE [OUTFILE]]",
63 62
           "If either the INFILE or OUTFILE file is missing the standard\n"
64 63
           "     input/output will be used instead.")
65 64
    .run();
66 65

	
67 66
  ifstream input;
68 67
  ofstream output;
69 68

	
70 69
  switch(ap.files().size())
71 70
    {
72 71
    case 2:
73 72
      output.open(ap.files()[1].c_str());
74 73
      if (!output) {
75 74
        throw IoError("Cannot open the file for writing", ap.files()[1]);
76 75
      }
77 76
    case 1:
78 77
      input.open(ap.files()[0].c_str());
79 78
      if (!input) {
80 79
        throw IoError("File cannot be found", ap.files()[0]);
81 80
      }
82 81
    case 0:
83 82
      break;
84 83
    default:
85 84
      cerr << ap.commandName() << ": too many arguments\n";
86 85
      return 1;
87 86
  }
88 87
  istream& is = (ap.files().size()<1 ? cin : input);
89 88
  ostream& os = (ap.files().size()<2 ? cout : output);
90 89

	
91 90
  DimacsDescriptor desc = dimacsType(is);
92 91
  switch(desc.type)
93 92
    {
94 93
    case DimacsDescriptor::MIN:
95 94
      {
96 95
        Digraph digraph;
97 96
        DoubleArcMap lower(digraph), capacity(digraph), cost(digraph);
98 97
        DoubleNodeMap supply(digraph);
99 98
        readDimacsMin(is, digraph, lower, capacity, cost, supply, 0, desc);
100 99
        DigraphWriter<Digraph>(digraph, os).
101 100
          nodeMap("supply", supply).
102 101
          arcMap("lower", lower).
103 102
          arcMap("capacity", capacity).
104 103
          arcMap("cost", cost).
105 104
          attribute("problem","min").
106 105
          run();
107 106
      }
108 107
      break;
109 108
    case DimacsDescriptor::MAX:
110 109
      {
111 110
        Digraph digraph;
112 111
        Node s, t;
113 112
        DoubleArcMap capacity(digraph);
114 113
        readDimacsMax(is, digraph, capacity, s, t, 0, desc);
115 114
        DigraphWriter<Digraph>(digraph, os).
116 115
          arcMap("capacity", capacity).
117 116
          node("source", s).
118 117
          node("target", t).
119 118
          attribute("problem","max").
120 119
          run();
121 120
      }
122 121
      break;
123 122
    case DimacsDescriptor::SP:
124 123
      {
125 124
        Digraph digraph;
126 125
        Node s;
127 126
        DoubleArcMap capacity(digraph);
128 127
        readDimacsSp(is, digraph, capacity, s, desc);
129 128
        DigraphWriter<Digraph>(digraph, os).
130 129
          arcMap("capacity", capacity).
131 130
          node("source", s).
132 131
          attribute("problem","sp").
133 132
          run();
134 133
      }
135 134
      break;
136 135
    case DimacsDescriptor::MAT:
137 136
      {
138 137
        Digraph digraph;
139 138
        readDimacsMat(is, digraph,desc);
140 139
        DigraphWriter<Digraph>(digraph, os).
141 140
          attribute("problem","mat").
142 141
          run();
143 142
      }
144 143
      break;
145 144
    default:
146 145
      break;
147 146
    }
148 147
  return 0;
149 148
}
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
/// \ingroup tools
20 20
/// \file
21 21
/// \brief Special plane digraph generator.
22 22
///
23 23
/// Graph generator application for various types of plane graphs.
24 24
///
25 25
/// See
26
/// \verbatim
27
///  lgf-gen --help
28
/// \endverbatim
26
/// \code
27
///   lgf-gen --help
28
/// \endcode
29 29
/// for more info on the usage.
30
///
31

	
32 30

	
33 31
#include <algorithm>
34 32
#include <set>
35 33
#include <ctime>
36 34
#include <lemon/list_graph.h>
37 35
#include <lemon/random.h>
38 36
#include <lemon/dim2.h>
39 37
#include <lemon/bfs.h>
40 38
#include <lemon/counter.h>
41 39
#include <lemon/suurballe.h>
42 40
#include <lemon/graph_to_eps.h>
43 41
#include <lemon/lgf_writer.h>
44 42
#include <lemon/arg_parser.h>
45 43
#include <lemon/euler.h>
46 44
#include <lemon/math.h>
47 45
#include <lemon/kruskal.h>
48 46
#include <lemon/time_measure.h>
49 47

	
50 48
using namespace lemon;
51 49

	
52 50
typedef dim2::Point<double> Point;
53 51

	
54 52
GRAPH_TYPEDEFS(ListGraph);
55 53

	
56 54
bool progress=true;
57 55

	
58 56
int N;
59 57
// int girth;
60 58

	
61 59
ListGraph g;
62 60

	
63 61
std::vector<Node> nodes;
64 62
ListGraph::NodeMap<Point> coords(g);
65 63

	
66 64

	
67 65
double totalLen(){
68 66
  double tlen=0;
69 67
  for(EdgeIt e(g);e!=INVALID;++e)
70 68
    tlen+=sqrt((coords[g.v(e)]-coords[g.u(e)]).normSquare());
71 69
  return tlen;
72 70
}
73 71

	
74 72
int tsp_impr_num=0;
75 73

	
76 74
const double EPSILON=1e-8;
77 75
bool tsp_improve(Node u, Node v)
78 76
{
79 77
  double luv=std::sqrt((coords[v]-coords[u]).normSquare());
80 78
  Node u2=u;
81 79
  Node v2=v;
82 80
  do {
83 81
    Node n;
84 82
    for(IncEdgeIt e(g,v2);(n=g.runningNode(e))==u2;++e) { }
85 83
    u2=v2;
86 84
    v2=n;
87 85
    if(luv+std::sqrt((coords[v2]-coords[u2]).normSquare())-EPSILON>
88 86
       std::sqrt((coords[u]-coords[u2]).normSquare())+
89 87
       std::sqrt((coords[v]-coords[v2]).normSquare()))
90 88
      {
91 89
         g.erase(findEdge(g,u,v));
92 90
         g.erase(findEdge(g,u2,v2));
93 91
        g.addEdge(u2,u);
94 92
        g.addEdge(v,v2);
95 93
        tsp_impr_num++;
96 94
        return true;
97 95
      }
98 96
  } while(v2!=u);
99 97
  return false;
100 98
}
101 99

	
102 100
bool tsp_improve(Node u)
103 101
{
104 102
  for(IncEdgeIt e(g,u);e!=INVALID;++e)
105 103
    if(tsp_improve(u,g.runningNode(e))) return true;
106 104
  return false;
107 105
}
108 106

	
109 107
void tsp_improve()
110 108
{
111 109
  bool b;
112 110
  do {
113 111
    b=false;
114 112
    for(NodeIt n(g);n!=INVALID;++n)
115 113
      if(tsp_improve(n)) b=true;
116 114
  } while(b);
117 115
}
118 116

	
119 117
void tsp()
120 118
{
121 119
  for(int i=0;i<N;i++) g.addEdge(nodes[i],nodes[(i+1)%N]);
122 120
  tsp_improve();
123 121
}
124 122

	
125 123
class Line
126 124
{
127 125
public:
128 126
  Point a;
129 127
  Point b;
130 128
  Line(Point _a,Point _b) :a(_a),b(_b) {}
131 129
  Line(Node _a,Node _b) : a(coords[_a]),b(coords[_b]) {}
132 130
  Line(const Arc &e) : a(coords[g.source(e)]),b(coords[g.target(e)]) {}
133 131
  Line(const Edge &e) : a(coords[g.u(e)]),b(coords[g.v(e)]) {}
134 132
};
135 133

	
136 134
inline std::ostream& operator<<(std::ostream &os, const Line &l)
137 135
{
138 136
  os << l.a << "->" << l.b;
139 137
  return os;
140 138
}
141 139

	
142 140
bool cross(Line a, Line b)
143 141
{
144 142
  Point ao=rot90(a.b-a.a);
145 143
  Point bo=rot90(b.b-b.a);
146 144
  return (ao*(b.a-a.a))*(ao*(b.b-a.a))<0 &&
147 145
    (bo*(a.a-b.a))*(bo*(a.b-b.a))<0;
148 146
}
149 147

	
150 148
struct Parc
151 149
{
152 150
  Node a;
153 151
  Node b;
154 152
  double len;
155 153
};
156 154

	
157 155
bool pedgeLess(Parc a,Parc b)
158 156
{
159 157
  return a.len<b.len;
160 158
}
161 159

	
162 160
std::vector<Edge> arcs;
163 161

	
164 162
namespace _delaunay_bits {
165 163

	
166 164
  struct Part {
167 165
    int prev, curr, next;
168 166

	
169 167
    Part(int p, int c, int n) : prev(p), curr(c), next(n) {}
170 168
  };
171 169

	
172 170
  inline std::ostream& operator<<(std::ostream& os, const Part& part) {
173 171
    os << '(' << part.prev << ',' << part.curr << ',' << part.next << ')';
174 172
    return os;
175 173
  }
176 174

	
177 175
  inline double circle_point(const Point& p, const Point& q, const Point& r) {
178 176
    double a = p.x * (q.y - r.y) + q.x * (r.y - p.y) + r.x * (p.y - q.y);
179 177
    if (a == 0) return std::numeric_limits<double>::quiet_NaN();
180 178

	
181 179
    double d = (p.x * p.x + p.y * p.y) * (q.y - r.y) +
182 180
      (q.x * q.x + q.y * q.y) * (r.y - p.y) +
183 181
      (r.x * r.x + r.y * r.y) * (p.y - q.y);
184 182

	
185 183
    double e = (p.x * p.x + p.y * p.y) * (q.x - r.x) +
186 184
      (q.x * q.x + q.y * q.y) * (r.x - p.x) +
187 185
      (r.x * r.x + r.y * r.y) * (p.x - q.x);
188 186

	
189 187
    double f = (p.x * p.x + p.y * p.y) * (q.x * r.y - r.x * q.y) +
190 188
      (q.x * q.x + q.y * q.y) * (r.x * p.y - p.x * r.y) +
191 189
      (r.x * r.x + r.y * r.y) * (p.x * q.y - q.x * p.y);
192 190

	
193 191
    return d / (2 * a) + sqrt((d * d + e * e) / (4 * a * a) + f / a);
194 192
  }
195 193

	
196 194
  inline bool circle_form(const Point& p, const Point& q, const Point& r) {
197 195
    return rot90(q - p) * (r - q) < 0.0;
198 196
  }
199 197

	
200 198
  inline double intersection(const Point& p, const Point& q, double sx) {
201 199
    const double epsilon = 1e-8;
202 200

	
203 201
    if (p.x == q.x) return (p.y + q.y) / 2.0;
204 202

	
205 203
    if (sx < p.x + epsilon) return p.y;
206 204
    if (sx < q.x + epsilon) return q.y;
207 205

	
208 206
    double a = q.x - p.x;
209 207
    double b = (q.x - sx) * p.y - (p.x - sx) * q.y;
210 208
    double d = (q.x - sx) * (p.x - sx) * (p - q).normSquare();
211 209
    return (b - sqrt(d)) / a;
212 210
  }
213 211

	
214 212
  struct YLess {
215 213

	
216 214

	
217 215
    YLess(const std::vector<Point>& points, double& sweep)
218 216
      : _points(points), _sweep(sweep) {}
219 217

	
220 218
    bool operator()(const Part& l, const Part& r) const {
221 219
      const double epsilon = 1e-8;
222 220

	
223 221
      //      std::cerr << l << " vs " << r << std::endl;
224 222
      double lbx = l.prev != -1 ?
225 223
        intersection(_points[l.prev], _points[l.curr], _sweep) :
226 224
        - std::numeric_limits<double>::infinity();
227 225
      double rbx = r.prev != -1 ?
228 226
        intersection(_points[r.prev], _points[r.curr], _sweep) :
229 227
        - std::numeric_limits<double>::infinity();
230 228
      double lex = l.next != -1 ?
231 229
        intersection(_points[l.curr], _points[l.next], _sweep) :
232 230
        std::numeric_limits<double>::infinity();
233 231
      double rex = r.next != -1 ?
234 232
        intersection(_points[r.curr], _points[r.next], _sweep) :
235 233
        std::numeric_limits<double>::infinity();
236 234

	
237 235
      if (lbx > lex) std::swap(lbx, lex);
238 236
      if (rbx > rex) std::swap(rbx, rex);
239 237

	
240 238
      if (lex < epsilon + rex && lbx + epsilon < rex) return true;
241 239
      if (rex < epsilon + lex && rbx + epsilon < lex) return false;
242 240
      return lex < rex;
243 241
    }
244 242

	
245 243
    const std::vector<Point>& _points;
246 244
    double& _sweep;
247 245
  };
248 246

	
249 247
  struct BeachIt;
250 248

	
251 249
  typedef std::multimap<double, BeachIt> SpikeHeap;
252 250

	
253 251
  typedef std::multimap<Part, SpikeHeap::iterator, YLess> Beach;
254 252

	
255 253
  struct BeachIt {
256 254
    Beach::iterator it;
257 255

	
258 256
    BeachIt(Beach::iterator iter) : it(iter) {}
259 257
  };
260 258

	
261 259
}
262 260

	
263 261
inline void delaunay() {
264 262
  Counter cnt("Number of arcs added: ");
265 263

	
266 264
  using namespace _delaunay_bits;
267 265

	
268 266
  typedef _delaunay_bits::Part Part;
269 267
  typedef std::vector<std::pair<double, int> > SiteHeap;
270 268

	
271 269

	
272 270
  std::vector<Point> points;
273 271
  std::vector<Node> nodes;
274 272

	
275 273
  for (NodeIt it(g); it != INVALID; ++it) {
276 274
    nodes.push_back(it);
277 275
    points.push_back(coords[it]);
278 276
  }
279 277

	
280 278
  SiteHeap siteheap(points.size());
281 279

	
282 280
  double sweep;
283 281

	
284 282

	
285 283
  for (int i = 0; i < int(siteheap.size()); ++i) {
286 284
    siteheap[i] = std::make_pair(points[i].x, i);
287 285
  }
0 comments (0 inline)