Debian Codegraph @

ot/lp/network_simplex_simple_omp.h

raw symbols SCIP
1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
2 *
3 *
4 * This file has been adapted by Nicolas Bonneel (2013),
5 * from network_simplex.h from LEMON, a generic C++ optimization library,
6 * to implement a lightweight network simplex for mass transport, more
7 * memory efficient than the original file. A previous version of this file
8 * is used as part of the Displacement Interpolation project,
9 * Web: http://www.cs.ubc.ca/labs/imager/tr/2011/DisplacementInterpolation/
10 *
11 * Revisions:
12 * March 2015: added OpenMP parallelization
13 * March 2017: included Antoine Rolet's trick to make it more robust
14 * April 2018: IMPORTANT bug fix + uses 64bit integers (slightly slower but less risks of overflows), updated to a newer version of the algo by LEMON, sparse flow by default + minor edits.
15 *
16 *
17 **** Original file Copyright Notice :
18 *
19 * Copyright (C) 2003-2010
20 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
21 * (Egervary Research Group on Combinatorial Optimization, EGRES).
22 *
23 * Permission to use, modify and distribute this software is granted
24 * provided that this copyright notice appears in all copies. For
25 * precise terms see the accompanying LICENSE file.
26 *
27 * This software is provided "AS IS" with no warranty of any kind,
28 * express or implied, and with no claim as to its suitability for any
29 * purpose.
30 *
31 */
32
33 #pragma once
34 #undef DEBUG_LVL
35 #define DEBUG_LVL 0
36
37 #if DEBUG_LVL>0
38 #include <iomanip>
39 #endif
40
41 #undef EPSILON
42 #undef _EPSILON
43 #undef MAX_DEBUG_ITER
44 #define EPSILON std::numeric_limits<Cost>::epsilon()
45 #define _EPSILON 1e-14
46 #define MAX_DEBUG_ITER 100000
47
48 /// \ingroup min_cost_flow_algs
49 ///
50 /// \file
51 /// \brief Network Simplex algorithm for finding a minimum cost flow.
52
53 // if your compiler has troubles with unorderedmaps, just comment the following line to use a slower std::map instead
54 #define HASHMAP // now handled with unorderedmaps instead of stdext::hash_map. Should be better supported.
55
56 #define SPARSE_FLOW // a sparse flow vector will be 10-15% slower for small problems but uses less memory and becomes faster for large problems (40k total nodes)
57
58 #include <vector>
59 #include <limits>
60 #include <algorithm>
61 #include <iostream>
62 #ifdef HASHMAP
63 #include <unordered_map>
64 #else
65 #include <map>
66 #endif
67 //#include "core.h"
68 //#include "lmath.h"
69
70 #ifdef _OPENMP
71 #include <omp.h>
72 #endif
73 #include <cmath>
74
75
76 //#include "sparse_array_n.h"
77 #include "full_bipartitegraph_omp.h"
78
79 #undef INVALIDNODE
80 #undef INVALID
81 #define INVALIDNODE -1
82 #define INVALID (-1)
83
84 namespace lemon_omp {
85
86 int64_t max_threads = -1;
87
88 template <typename T>
89 class ProxyObject;
90
91 template<typename T>
92 class SparseValueVector
93 {
94 public:
95 SparseValueVector(size_t n = 0) // parameter n for compatibility with standard vectors
96 {
97 }
98 void resize(size_t n = 0) {};
99 T operator[](const size_t id) const
100 {
101 #ifdef HASHMAP
102 typename std::unordered_map<size_t, T>::const_iterator it = data.find(id);
103 #else
104 typename std::map<size_t, T>::const_iterator it = data.find(id);
105 #endif
106 if (it == data.end())
107 return 0;
108 else
109 return it->second;
110 }
111
112 ProxyObject<T> operator[](const size_t id)
113 {
114 return ProxyObject<T>(this, id);
115 }
116
117 //private:
118 #ifdef HASHMAP
119 std::unordered_map<size_t, T> data;
120 #else
121 std::map<size_t, T> data;
122 #endif
123
124 };
125
126 template <typename T>
127 class ProxyObject {
128 public:
129 ProxyObject(SparseValueVector<T> *v, size_t idx) { _v = v; _idx = idx; };
130 ProxyObject<T> & operator=(const T &v) {
131 // If we get here, we know that operator[] was called to perform a write access,
132 // so we can insert an item in the vector if needed
133 if (v != 0)
134 _v->data[_idx] = v;
135 return *this;
136 }
137
138 operator T() {
139 // If we get here, we know that operator[] was called to perform a read access,
140 // so we can simply return the existing object
141 #ifdef HASHMAP
142 typename std::unordered_map<size_t, T>::iterator it = _v->data.find(_idx);
143 #else
144 typename std::map<size_t, T>::iterator it = _v->data.find(_idx);
145 #endif
146 if (it == _v->data.end())
147 return 0;
148 else
149 return it->second;
150 }
151
152 void operator+=(T val)
153 {
154 if (val == 0) return;
155 #ifdef HASHMAP
156 typename std::unordered_map<size_t, T>::iterator it = _v->data.find(_idx);
157 #else
158 typename std::map<size_t, T>::iterator it = _v->data.find(_idx);
159 #endif
160 if (it == _v->data.end())
161 _v->data[_idx] = val;
162 else
163 {
164 T sum = it->second + val;
165 if (sum == 0)
166 _v->data.erase(it);
167 else
168 it->second = sum;
169 }
170 }
171 void operator-=(T val)
172 {
173 if (val == 0) return;
174 #ifdef HASHMAP
175 typename std::unordered_map<size_t, T>::iterator it = _v->data.find(_idx);
176 #else
177 typename std::map<size_t, T>::iterator it = _v->data.find(_idx);
178 #endif
179 if (it == _v->data.end())
180 _v->data[_idx] = -val;
181 else
182 {
183 T sum = it->second - val;
184 if (sum == 0)
185 _v->data.erase(it);
186 else
187 it->second = sum;
188 }
189 }
190
191 SparseValueVector<T> *_v;
192 size_t _idx;
193 };
194
195
196
197 /// \addtogroup min_cost_flow_algs
198 /// @{
199
200 /// \brief Implementation of the primal Network Simplex algorithm
201 /// for finding a \ref min_cost_flow "minimum cost flow".
202 ///
203 /// \ref NetworkSimplexSimple implements the primal Network Simplex algorithm
204 /// for finding a \ref min_cost_flow "minimum cost flow"
205 /// \ref amo93networkflows, \ref dantzig63linearprog,
206 /// \ref kellyoneill91netsimplex.
207 /// This algorithm is a highly efficient specialized version of the
208 /// linear programming simplex method directly for the minimum cost
209 /// flow problem.
210 ///
211 /// In general, %NetworkSimplexSimple is the fastest implementation available
212 /// in LEMON for this problem.
213 /// Moreover, it supports both directions of the supply/demand inequality
214 /// constraints. For more information, see \ref SupplyType.
215 ///
216 /// Most of the parameters of the problem (except for the digraph)
217 /// can be given using separate functions, and the algorithm can be
218 /// executed using the \ref run() function. If some parameters are not
219 /// specified, then default values will be used.
220 ///
221 /// \tparam GR The digraph type the algorithm runs on.
222 /// \tparam V The number type used for flow amounts, capacity bounds
223 /// and supply values in the algorithm. By default, it is \c int.
224 /// \tparam C The number type used for costs and potentials in the
225 /// algorithm. By default, it is the same as \c V.
226 ///
227 /// \warning Both number types must be signed and all input data must
228 /// be integer.
229 ///
230 /// \note %NetworkSimplexSimple provides five different pivot rule
231 /// implementations, from which the most efficient one is used
232 /// by default. For more information, see \ref PivotRule.
233 template <typename GR, typename V = int, typename C = V, typename ArcsType = int64_t>
234 class NetworkSimplexSimple
235 {
236 public:
237
238 /// \brief Constructor.
239 ///
240 /// The constructor of the class.
241 ///
242 /// \param graph The digraph the algorithm runs on.
243 /// \param arc_mixing Indicate if the arcs have to be stored in a
244 /// mixed order in the internal data structure.
245 /// In special cases, it could lead to better overall performance,
246 /// but it is usually slower. Therefore it is disabled by default.
247 NetworkSimplexSimple(const GR& graph, bool arc_mixing, int nbnodes, ArcsType nb_arcs, uint64_t maxiters = 0, int numThreads=-1) :
248 _graph(graph), //_arc_id(graph),
249 _arc_mixing(arc_mixing), _init_nb_nodes(nbnodes), _init_nb_arcs(nb_arcs),
250 MAX(std::numeric_limits<Value>::max()),
251 INF(std::numeric_limits<Value>::has_infinity ?
252 std::numeric_limits<Value>::infinity() : MAX)
253 {
254 // Reset data structures
255 reset();
256 max_iter = maxiters;
257 #ifdef _OPENMP
258 if (max_threads < 0) {
259 max_threads = omp_get_max_threads();
260 }
261 if (numThreads > 0 && numThreads<=max_threads){
262 num_threads = numThreads;
263 } else if (numThreads == -1 || numThreads>max_threads) {
264 num_threads = max_threads;
265 } else {
266 num_threads = 1;
267 }
268 omp_set_num_threads(num_threads);
269 #else
270 num_threads = 1;
271 #endif
272 }
273
274 /// The type of the flow amounts, capacity bounds and supply values
275 typedef V Value;
276 /// The type of the arc costs
277 typedef C Cost;
278
279 public:
280 /// \brief Problem type constants for the \c run() function.
281 ///
282 /// Enum type containing the problem type constants that can be
283 /// returned by the \ref run() function of the algorithm.
284 enum ProblemType {
285 /// The problem has no feasible solution (flow).
286 INFEASIBLE,
287 /// The problem has optimal solution (i.e. it is feasible and
288 /// bounded), and the algorithm has found optimal flow and node
289 /// potentials (primal and dual solutions).
290 OPTIMAL,
291 /// The objective function of the problem is unbounded, i.e.
292 /// there is a directed cycle having negative total cost and
293 /// infinite upper bound.
294 UNBOUNDED,
295 // The maximum number of iteration has been reached
296 MAX_ITER_REACHED
297 };
298
299 /// \brief Constants for selecting the type of the supply constraints.
300 ///
301 /// Enum type containing constants for selecting the supply type,
302 /// i.e. the direction of the inequalities in the supply/demand
303 /// constraints of the \ref min_cost_flow "minimum cost flow problem".
304 ///
305 /// The default supply type is \c GEQ, the \c LEQ type can be
306 /// selected using \ref supplyType().
307 /// The equality form is a special case of both supply types.
308 enum SupplyType {
309 /// This option means that there are <em>"greater or equal"</em>
310 /// supply/demand constraints in the definition of the problem.
311 GEQ,
312 /// This option means that there are <em>"less or equal"</em>
313 /// supply/demand constraints in the definition of the problem.
314 LEQ
315 };
316
317
318
319 private:
320 uint64_t max_iter;
321 int num_threads;
322 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
323
324 typedef std::vector<int> IntVector;
325 typedef std::vector<ArcsType> ArcVector;
326 typedef std::vector<Value> ValueVector;
327 typedef std::vector<Cost> CostVector;
328 // typedef SparseValueVector<Cost> CostVector;
329 typedef std::vector<char> BoolVector;
330 // Note: vector<char> is used instead of vector<bool> for efficiency reasons
331
332 // State constants for arcs
333 enum ArcState {
334 STATE_UPPER = -1,
335 STATE_TREE = 0,
336 STATE_LOWER = 1
337 };
338
339 typedef std::vector<signed char> StateVector;
340 // Note: vector<signed char> is used instead of vector<ArcState> for
341 // efficiency reasons
342
343 private:
344
345 // Data related to the underlying digraph
346 const GR &_graph;
347 int _node_num;
348 ArcsType _arc_num;
349 ArcsType _all_arc_num;
350 ArcsType _search_arc_num;
351
352 // Parameters of the problem
353 SupplyType _stype;
354 Value _sum_supply;
355
356 inline int _node_id(int n) const { return _node_num - n - 1; };
357
358 //IntArcMap _arc_id;
359 IntVector _source; // keep nodes as integers
360 IntVector _target;
361 bool _arc_mixing;
362
363 // Node and arc data
364 CostVector _cost;
365 ValueVector _supply;
366 #ifdef SPARSE_FLOW
367 SparseValueVector<Value> _flow;
368 #else
369 ValueVector _flow;
370 #endif
371
372 CostVector _pi;
373
374 // Data for storing the spanning tree structure
375 IntVector _parent;
376 ArcVector _pred;
377 IntVector _thread;
378 IntVector _rev_thread;
379 IntVector _succ_num;
380 IntVector _last_succ;
381 IntVector _dirty_revs;
382 BoolVector _forward;
383 StateVector _state;
384 ArcsType _root;
385
386 // Temporary data used in the current pivot iteration
387 ArcsType in_arc, join, u_in, v_in, u_out, v_out;
388 ArcsType first, second, right, last;
389 ArcsType stem, par_stem, new_stem;
390 Value delta;
391
392 const Value MAX;
393
394 ArcsType mixingCoeff;
395
396 public:
397
398 /// \brief Constant for infinite upper bounds (capacities).
399 ///
400 /// Constant for infinite upper bounds (capacities).
401 /// It is \c std::numeric_limits<Value>::infinity() if available,
402 /// \c std::numeric_limits<Value>::max() otherwise.
403 const Value INF;
404
405 private:
406
407 // thank you to DVK and MizardX from StackOverflow for this function!
408 inline ArcsType sequence(ArcsType k) const {
409 ArcsType smallv = (k > num_total_big_subsequence_numbers) & 1;
410
411 k -= num_total_big_subsequence_numbers * smallv;
412 ArcsType subsequence_length2 = subsequence_length - smallv;
413 ArcsType subsequence_num = (k / subsequence_length2) + num_big_subsequences * smallv;
414 ArcsType subsequence_offset = (k % subsequence_length2) * mixingCoeff;
415
416 return subsequence_offset + subsequence_num;
417 }
418 ArcsType subsequence_length;
419 ArcsType num_big_subsequences;
420 ArcsType num_total_big_subsequence_numbers;
421
422 inline ArcsType getArcID(const Arc &arc) const
423 {
424 //int n = _arc_num-arc._id-1;
425 ArcsType n = _arc_num - GR::id(arc) - 1;
426
427 //ArcsType a = mixingCoeff*(n%mixingCoeff) + n/mixingCoeff;
428 //ArcsType b = _arc_id[arc];
429 if (_arc_mixing)
430 return sequence(n);
431 else
432 return n;
433 }
434
435 // finally unused because too slow
436 inline ArcsType getSource(const ArcsType arc) const
437 {
438 //ArcsType a = _source[arc];
439 //return a;
440
441 ArcsType n = _arc_num - arc - 1;
442 if (_arc_mixing)
443 n = mixingCoeff*(n%mixingCoeff) + n / mixingCoeff;
444
445 ArcsType b;
446 if (n >= 0)
447 b = _node_id(_graph.source(GR::arcFromId(n)));
448 else
449 {
450 n = arc + 1 - _arc_num;
451 if (n <= _node_num)
452 b = _node_num;
453 else
454 if (n >= _graph._n1)
455 b = _graph._n1;
456 else
457 b = _graph._n1 - n;
458 }
459
460 return b;
461 }
462
463
464
465 // Implementation of the Block Search pivot rule
466 class BlockSearchPivotRule
467 {
468 private:
469
470 // References to the NetworkSimplexSimple class
471 const IntVector &_source;
472 const IntVector &_target;
473 const CostVector &_cost;
474 const StateVector &_state;
475 const CostVector &_pi;
476 ArcsType &_in_arc;
477 ArcsType _search_arc_num;
478
479 // Pivot rule data
480 ArcsType _block_size;
481 ArcsType _next_arc;
482 NetworkSimplexSimple &_ns;
483
484 public:
485
486 // Constructor
487 BlockSearchPivotRule(NetworkSimplexSimple &ns) :
488 _source(ns._source), _target(ns._target),
489 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
490 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
491 _next_arc(0), _ns(ns)
492 {
493 // The main parameters of the pivot rule
494 const double BLOCK_SIZE_FACTOR = 1;
495 const ArcsType MIN_BLOCK_SIZE = 10;
496
497 _block_size = std::max(ArcsType(BLOCK_SIZE_FACTOR * std::sqrt(double(_search_arc_num))), MIN_BLOCK_SIZE);
498 }
499
500 // Find next entering arc
501 bool findEnteringArc() {
502 Cost min_val = 0;
503
504 ArcsType N = _ns.num_threads;
505
506 std::vector<Cost> minArray(N, 0);
507 std::vector<ArcsType> arcId(N);
508 ArcsType bs = (ArcsType)ceil(_block_size / (double)N);
509
510 for (ArcsType i = 0; i < _search_arc_num; i += _block_size) {
511
512 ArcsType e;
513 int j;
514 #pragma omp parallel
515 {
516 #ifdef _OPENMP
517 int t = omp_get_thread_num();
518 #else
519 int t = 0;
520 #endif
521
522 #pragma omp for schedule(static, bs) lastprivate(e)
523 for (j = 0; j < std::min(i + _block_size, _search_arc_num) - i; j++) {
524 e = (_next_arc + i + j); if (e >= _search_arc_num) e -= _search_arc_num;
525 Cost c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
526 if (c < minArray[t]) {
527 minArray[t] = c;
528 arcId[t] = e;
529 }
530 }
531 }
532 for (int j = 0; j < N; j++) {
533 if (minArray[j] < min_val) {
534 min_val = minArray[j];
535 _in_arc = arcId[j];
536 }
537 }
538 Cost a = std::abs(_pi[_source[_in_arc]]) > std::abs(_pi[_target[_in_arc]]) ? std::abs(_pi[_source[_in_arc]]) : std::abs(_pi[_target[_in_arc]]);
539 a = a > std::abs(_cost[_in_arc]) ? a : std::abs(_cost[_in_arc]);
540 if (min_val < -EPSILON*a) {
541 _next_arc = e;
542 return true;
543 }
544 }
545
546 Cost a = fabs(_pi[_source[_in_arc]]) > fabs(_pi[_target[_in_arc]]) ? fabs(_pi[_source[_in_arc]]) : fabs(_pi[_target[_in_arc]]);
547 a = a > fabs(_cost[_in_arc]) ? a : fabs(_cost[_in_arc]);
548 if (min_val >= -EPSILON*a) return false;
549
550 return true;
551 }
552
553
554 // Find next entering arc
555 /*bool findEnteringArc() {
556 Cost min_val = 0;
557 int N = omp_get_max_threads();
558 std::vector<Cost> minArray(N);
559 std::vector<ArcsType> arcId(N);
560
561 ArcsType bs = (ArcsType)ceil(_block_size / (double)N);
562 for (ArcsType i = 0; i < _search_arc_num; i += _block_size) {
563
564 ArcsType maxJ = std::min(i + _block_size, _search_arc_num) - i;
565 ArcsType j;
566 #pragma omp parallel
567 {
568 int t = omp_get_thread_num();
569 Cost minV = 0;
570 ArcsType arcStart = _next_arc + i;
571 ArcsType arc = -1;
572 #pragma omp for schedule(static, bs)
573 for (j = 0; j < maxJ; j++) {
574 ArcsType e = arcStart + j; if (e >= _search_arc_num) e -= _search_arc_num;
575 Cost c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
576 if (c < minV) {
577 minV = c;
578 arc = e;
579 }
580 }
581
582 minArray[t] = minV;
583 arcId[t] = arc;
584 }
585 for (int j = 0; j < N; j++) {
586 if (minArray[j] < min_val) {
587 min_val = minArray[j];
588 _in_arc = arcId[j];
589 }
590 }
591
592 //FIX by Antoine Rolet to avoid precision issues
593 Cost a = std::max(std::abs(_cost[_in_arc]), std::max(std::abs(_pi[_source[_in_arc]]), std::abs(_pi[_target[_in_arc]])));
594 if (min_val <-std::numeric_limits<Cost>::epsilon()*a) {
595 _next_arc = _next_arc + i + maxJ - 1;
596 if (_next_arc >= _search_arc_num) _next_arc -= _search_arc_num;
597 return true;
598 }
599 }
600
601 if (min_val >= 0) {
602 return false;
603 }
604
605 return true;
606 }*/
607
608
609 /*bool findEnteringArc() {
610 Cost c, min = 0;
611 int cnt = _block_size;
612 int e, min_arc = _next_arc;
613 for (e = _next_arc; e < _search_arc_num; ++e) {
614 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
615 if (c < min) {
616 min = c;
617 min_arc = e;
618
619 }
620 if (--cnt == 0) {
621 if (min < 0) break;
622 cnt = _block_size;
623
624 }
625
626 }
627 if (min == 0 || cnt > 0) {
628 for (e = 0; e < _next_arc; ++e) {
629 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
630 if (c < min) {
631 min = c;
632 min_arc = e;
633
634 }
635 if (--cnt == 0) {
636 if (min < 0) break;
637 cnt = _block_size;
638
639 }
640
641 }
642
643 }
644 if (min >= 0) return false;
645 _in_arc = min_arc;
646 _next_arc = e;
647 return true;
648 }*/
649
650
651
652 }; //class BlockSearchPivotRule
653
654
655
656 public:
657
658
659
660 int _init_nb_nodes;
661 ArcsType _init_nb_arcs;
662
663 /// \name Parameters
664 /// The parameters of the algorithm can be specified using these
665 /// functions.
666
667 /// @{
668
669
670 /// \brief Set the costs of the arcs.
671 ///
672 /// This function sets the costs of the arcs.
673 /// If it is not used before calling \ref run(), the costs
674 /// will be set to \c 1 on all arcs.
675 ///
676 /// \param map An arc map storing the costs.
677 /// Its \c Value type must be convertible to the \c Cost type
678 /// of the algorithm.
679 ///
680 /// \return <tt>(*this)</tt>
681 template<typename CostMap>
682 NetworkSimplexSimple& costMap(const CostMap& map) {
683 Arc a; _graph.first(a);
684 for (; a != INVALID; _graph.next(a)) {
685 _cost[getArcID(a)] = map[a];
686 }
687 return *this;
688 }
689
690
691 /// \brief Set the costs of one arc.
692 ///
693 /// This function sets the costs of one arcs.
694 /// Done for memory reasons
695 ///
696 /// \param arc An arc.
697 /// \param arc A cost
698 ///
699 /// \return <tt>(*this)</tt>
700 template<typename Value>
701 NetworkSimplexSimple& setCost(const Arc& arc, const Value cost) {
702 _cost[getArcID(arc)] = cost;
703 return *this;
704 }
705
706
707 /// \brief Set the supply values of the nodes.
708 ///
709 /// This function sets the supply values of the nodes.
710 /// If neither this function nor \ref stSupply() is used before
711 /// calling \ref run(), the supply of each node will be set to zero.
712 ///
713 /// \param map A node map storing the supply values.
714 /// Its \c Value type must be convertible to the \c Value type
715 /// of the algorithm.
716 ///
717 /// \return <tt>(*this)</tt>
718 template<typename SupplyMap>
719 NetworkSimplexSimple& supplyMap(const SupplyMap& map) {
720 Node n; _graph.first(n);
721 for (; n != INVALIDNODE; _graph.next(n)) {
722 _supply[_node_id(n)] = map[n];
723 }
724 return *this;
725 }
726 template<typename SupplyMap>
727 NetworkSimplexSimple& supplyMap(const SupplyMap* map1, int n1, const SupplyMap* map2, int n2) {
728 Node n; _graph.first(n);
729 for (; n != INVALIDNODE; _graph.next(n)) {
730 if (n<n1)
731 _supply[_node_id(n)] = map1[n];
732 else
733 _supply[_node_id(n)] = map2[n - n1];
734 }
735 return *this;
736 }
737 template<typename SupplyMap>
738 NetworkSimplexSimple& supplyMapAll(SupplyMap val1, int n1, SupplyMap val2, int n2) {
739 Node n; _graph.first(n);
740 for (; n != INVALIDNODE; _graph.next(n)) {
741 if (n<n1)
742 _supply[_node_id(n)] = val1;
743 else
744 _supply[_node_id(n)] = val2;
745 }
746 return *this;
747 }
748
749 /// \brief Set single source and target nodes and a supply value.
750 ///
751 /// This function sets a single source node and a single target node
752 /// and the required flow value.
753 /// If neither this function nor \ref supplyMap() is used before
754 /// calling \ref run(), the supply of each node will be set to zero.
755 ///
756 /// Using this function has the same effect as using \ref supplyMap()
757 /// with such a map in which \c k is assigned to \c s, \c -k is
758 /// assigned to \c t and all other nodes have zero supply value.
759 ///
760 /// \param s The source node.
761 /// \param t The target node.
762 /// \param k The required amount of flow from node \c s to node \c t
763 /// (i.e. the supply of \c s and the demand of \c t).
764 ///
765 /// \return <tt>(*this)</tt>
766 NetworkSimplexSimple& stSupply(const Node& s, const Node& t, Value k) {
767 for (int i = 0; i != _node_num; ++i) {
768 _supply[i] = 0;
769 }
770 _supply[_node_id(s)] = k;
771 _supply[_node_id(t)] = -k;
772 return *this;
773 }
774
775 /// \brief Set the type of the supply constraints.
776 ///
777 /// This function sets the type of the supply/demand constraints.
778 /// If it is not used before calling \ref run(), the \ref GEQ supply
779 /// type will be used.
780 ///
781 /// For more information, see \ref SupplyType.
782 ///
783 /// \return <tt>(*this)</tt>
784 NetworkSimplexSimple& supplyType(SupplyType supply_type) {
785 _stype = supply_type;
786 return *this;
787 }
788
789 /// @}
790
791 /// \name Execution Control
792 /// The algorithm can be executed using \ref run().
793
794 /// @{
795
796 /// \brief Run the algorithm.
797 ///
798 /// This function runs the algorithm.
799 /// The paramters can be specified using functions \ref lowerMap(),
800 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
801 /// \ref supplyType().
802 /// For example,
803 /// \code
804 /// NetworkSimplexSimple<ListDigraph> ns(graph);
805 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
806 /// .supplyMap(sup).run();
807 /// \endcode
808 ///
809 /// This function can be called more than once. All the given parameters
810 /// are kept for the next call, unless \ref resetParams() or \ref reset()
811 /// is used, thus only the modified parameters have to be set again.
812 /// If the underlying digraph was also modified after the construction
813 /// of the class (or the last \ref reset() call), then the \ref reset()
814 /// function must be called.
815 ///
816 /// \param pivot_rule The pivot rule that will be used during the
817 /// algorithm. For more information, see \ref PivotRule.
818 ///
819 /// \return \c INFEASIBLE if no feasible flow exists,
820 /// \n \c OPTIMAL if the problem has optimal solution
821 /// (i.e. it is feasible and bounded), and the algorithm has found
822 /// optimal flow and node potentials (primal and dual solutions),
823 /// \n \c UNBOUNDED if the objective function of the problem is
824 /// unbounded, i.e. there is a directed cycle having negative total
825 /// cost and infinite upper bound.
826 ///
827 /// \see ProblemType, PivotRule
828 /// \see resetParams(), reset()
829 ProblemType run() {
830 #if DEBUG_LVL>0
831 std::cout << "OPTIMAL = " << OPTIMAL << "\nINFEASIBLE = " << INFEASIBLE << "\nUNBOUNDED = " << UNBOUNDED << "\nMAX_ITER_REACHED" << MAX_ITER_REACHED << "\n" ;
832 #endif
833 if (!init()) return INFEASIBLE;
834 #if DEBUG_LVL>0
835 std::cout << "Init done, starting iterations\n";
836 #endif
837
838 return start();
839 }
840
841 /// \brief Reset all the parameters that have been given before.
842 ///
843 /// This function resets all the paramaters that have been given
844 /// before using functions \ref lowerMap(), \ref upperMap(),
845 /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType().
846 ///
847 /// It is useful for multiple \ref run() calls. Basically, all the given
848 /// parameters are kept for the next \ref run() call, unless
849 /// \ref resetParams() or \ref reset() is used.
850 /// If the underlying digraph was also modified after the construction
851 /// of the class or the last \ref reset() call, then the \ref reset()
852 /// function must be used, otherwise \ref resetParams() is sufficient.
853 ///
854 /// For example,
855 /// \code
856 /// NetworkSimplexSimple<ListDigraph> ns(graph);
857 ///
858 /// // First run
859 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
860 /// .supplyMap(sup).run();
861 ///
862 /// // Run again with modified cost map (resetParams() is not called,
863 /// // so only the cost map have to be set again)
864 /// cost[e] += 100;
865 /// ns.costMap(cost).run();
866 ///
867 /// // Run again from scratch using resetParams()
868 /// // (the lower bounds will be set to zero on all arcs)
869 /// ns.resetParams();
870 /// ns.upperMap(capacity).costMap(cost)
871 /// .supplyMap(sup).run();
872 /// \endcode
873 ///
874 /// \return <tt>(*this)</tt>
875 ///
876 /// \see reset(), run()
877 NetworkSimplexSimple& resetParams() {
878 for (int i = 0; i != _node_num; ++i) {
879 _supply[i] = 0;
880 }
881 for (ArcsType i = 0; i != _arc_num; ++i) {
882 _cost[i] = 1;
883 }
884 _stype = GEQ;
885 return *this;
886 }
887
888
889 /// \brief Reset the internal data structures and all the parameters
890 /// that have been given before.
891 ///
892 /// This function resets the internal data structures and all the
893 /// paramaters that have been given before using functions \ref lowerMap(),
894 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
895 /// \ref supplyType().
896 ///
897 /// It is useful for multiple \ref run() calls. Basically, all the given
898 /// parameters are kept for the next \ref run() call, unless
899 /// \ref resetParams() or \ref reset() is used.
900 /// If the underlying digraph was also modified after the construction
901 /// of the class or the last \ref reset() call, then the \ref reset()
902 /// function must be used, otherwise \ref resetParams() is sufficient.
903 ///
904 /// See \ref resetParams() for examples.
905 ///
906 /// \return <tt>(*this)</tt>
907 ///
908 /// \see resetParams(), run()
909 NetworkSimplexSimple& reset() {
910 // Resize vectors
911 _node_num = _init_nb_nodes;
912 _arc_num = _init_nb_arcs;
913 int all_node_num = _node_num + 1;
914 ArcsType max_arc_num = _arc_num + 2 * _node_num;
915
916 _source.resize(max_arc_num);
917 _target.resize(max_arc_num);
918
919 _cost.resize(max_arc_num);
920 _supply.resize(all_node_num);
921 _flow.resize(max_arc_num);
922 _pi.resize(all_node_num);
923
924 _parent.resize(all_node_num);
925 _pred.resize(all_node_num);
926 _forward.resize(all_node_num);
927 _thread.resize(all_node_num);
928 _rev_thread.resize(all_node_num);
929 _succ_num.resize(all_node_num);
930 _last_succ.resize(all_node_num);
931 _state.resize(max_arc_num);
932
933
934 //_arc_mixing=false;
935 if (_arc_mixing && _node_num > 1) {
936 // Store the arcs in a mixed order
937 //ArcsType k = std::max(ArcsType(std::sqrt(double(_arc_num))), ArcsType(10));
938 const ArcsType k = std::max(ArcsType(_arc_num / _node_num), ArcsType(3));
939 mixingCoeff = k;
940 subsequence_length = _arc_num / mixingCoeff + 1;
941 num_big_subsequences = _arc_num % mixingCoeff;
942 num_total_big_subsequence_numbers = subsequence_length * num_big_subsequences;
943
944 #pragma omp parallel for schedule(static)
945 for (Arc a = 0; a <= _graph.maxArcId(); a++) { // --a <=> _graph.next(a) , -1 == INVALID
946 ArcsType i = sequence(_graph.maxArcId()-a);
947 _source[i] = _node_id(_graph.source(a));
948 _target[i] = _node_id(_graph.target(a));
949 }
950 } else {
951 // Store the arcs in the original order
952 ArcsType i = 0;
953 Arc a; _graph.first(a);
954 for (; a != INVALID; _graph.next(a), ++i) {
955 _source[i] = _node_id(_graph.source(a));
956 _target[i] = _node_id(_graph.target(a));
957 //_arc_id[a] = i;
958 }
959 }
960
961 // Reset parameters
962 resetParams();
963 return *this;
964 }
965
966 /// @}
967
968 /// \name Query Functions
969 /// The results of the algorithm can be obtained using these
970 /// functions.\n
971 /// The \ref run() function must be called before using them.
972
973 /// @{
974
975 /// \brief Return the total cost of the found flow.
976 ///
977 /// This function returns the total cost of the found flow.
978 /// Its complexity is O(e).
979 ///
980 /// \note The return type of the function can be specified as a
981 /// template parameter. For example,
982 /// \code
983 /// ns.totalCost<double>();
984 /// \endcode
985 /// It is useful if the total cost cannot be stored in the \c Cost
986 /// type of the algorithm, which is the default return type of the
987 /// function.
988 ///
989 /// \pre \ref run() must be called before using this function.
990 /*template <typename Number>
991 Number totalCost() const {
992 Number c = 0;
993 for (ArcIt a(_graph); a != INVALID; ++a) {
994 int i = getArcID(a);
995 c += Number(_flow[i]) * Number(_cost[i]);
996 }
997 return c;
998 }*/
999
1000 template <typename Number>
1001 Number totalCost() const {
1002 Number c = 0;
1003
1004 #ifdef SPARSE_FLOW
1005 #ifdef HASHMAP
1006 typename std::unordered_map<size_t, Value>::const_iterator it;
1007 #else
1008 typename std::map<size_t, Value>::const_iterator it;
1009 #endif
1010 for (it = _flow.data.begin(); it!=_flow.data.end(); ++it)
1011 c += Number(it->second) * Number(_cost[it->first]);
1012 return c;
1013 #else
1014 for (ArcsType i = 0; i<_flow.size(); i++)
1015 c += _flow[i] * Number(_cost[i]);
1016 return c;
1017 #endif
1018 }
1019
1020 #ifndef DOXYGEN
1021 Cost totalCost() const {
1022 return totalCost<Cost>();
1023 }
1024 #endif
1025
1026 /// \brief Return the flow on the given arc.
1027 ///
1028 /// This function returns the flow on the given arc.
1029 ///
1030 /// \pre \ref run() must be called before using this function.
1031 Value flow(const Arc& a) const {
1032 return _flow[getArcID(a)];
1033 }
1034
1035 /// \brief Return the flow map (the primal solution).
1036 ///
1037 /// This function copies the flow value on each arc into the given
1038 /// map. The \c Value type of the algorithm must be convertible to
1039 /// the \c Value type of the map.
1040 ///
1041 /// \pre \ref run() must be called before using this function.
1042 template <typename FlowMap>
1043 void flowMap(FlowMap &map) const {
1044 Arc a; _graph.first(a);
1045 for (; a != INVALID; _graph.next(a)) {
1046 map.set(a, _flow[getArcID(a)]);
1047 }
1048 }
1049
1050 /// \brief Return the potential (dual value) of the given node.
1051 ///
1052 /// This function returns the potential (dual value) of the
1053 /// given node.
1054 ///
1055 /// \pre \ref run() must be called before using this function.
1056 Cost potential(const Node& n) const {
1057 return _pi[_node_id(n)];
1058 }
1059
1060 /// \brief Return the potential map (the dual solution).
1061 ///
1062 /// This function copies the potential (dual value) of each node
1063 /// into the given map.
1064 /// The \c Cost type of the algorithm must be convertible to the
1065 /// \c Value type of the map.
1066 ///
1067 /// \pre \ref run() must be called before using this function.
1068 template <typename PotentialMap>
1069 void potentialMap(PotentialMap &map) const {
1070 Node n; _graph.first(n);
1071 for (; n != INVALID; _graph.next(n)) {
1072 map.set(n, _pi[_node_id(n)]);
1073 }
1074 }
1075
1076 /// @}
1077
1078 private:
1079
1080 // Initialize internal data structures
1081 bool init() {
1082 if (_node_num == 0) return false;
1083
1084 // Check the sum of supply values
1085 _sum_supply = 0;
1086 for (int i = 0; i != _node_num; ++i) {
1087 _sum_supply += _supply[i];
1088 }
1089 /*if (!((_stype == GEQ && _sum_supply <= 0) ||
1090 (_stype == LEQ && _sum_supply >= 0))) return false;*/
1091
1092
1093 // Initialize artifical cost
1094 Cost ART_COST;
1095 if (std::numeric_limits<Cost>::is_exact) {
1096 ART_COST = std::numeric_limits<Cost>::max() / 2 + 1;
1097 } else {
1098 ART_COST = 0;
1099 for (ArcsType i = 0; i != _arc_num; ++i) {
1100 if (_cost[i] > ART_COST) ART_COST = _cost[i];
1101 }
1102 ART_COST = (ART_COST + 1) * _node_num;
1103 }
1104
1105 // Initialize arc maps
1106 for (ArcsType i = 0; i != _arc_num; ++i) {
1107 #ifndef SPARSE_FLOW
1108 _flow[i] = 0; //by default, the sparse matrix is empty
1109 #endif
1110 _state[i] = STATE_LOWER;
1111 }
1112 #ifdef SPARSE_FLOW
1113 _flow = SparseValueVector<Value>();
1114 #endif
1115
1116 // Set data for the artificial root node
1117 _root = _node_num;
1118 _parent[_root] = -1;
1119 _pred[_root] = -1;
1120 _thread[_root] = 0;
1121 _rev_thread[0] = _root;
1122 _succ_num[_root] = _node_num + 1;
1123 _last_succ[_root] = _root - 1;
1124 _supply[_root] = -_sum_supply;
1125 _pi[_root] = 0;
1126
1127 // Add artificial arcs and initialize the spanning tree data structure
1128 if (_sum_supply == 0) {
1129 // EQ supply constraints
1130 _search_arc_num = _arc_num;
1131 _all_arc_num = _arc_num + _node_num;
1132 for (ArcsType u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1133 _parent[u] = _root;
1134 _pred[u] = e;
1135 _thread[u] = u + 1;
1136 _rev_thread[u + 1] = u;
1137 _succ_num[u] = 1;
1138 _last_succ[u] = u;
1139 _state[e] = STATE_TREE;
1140 if (_supply[u] >= 0) {
1141 _forward[u] = true;
1142 _pi[u] = 0;
1143 _source[e] = u;
1144 _target[e] = _root;
1145 _flow[e] = _supply[u];
1146 _cost[e] = 0;
1147 } else {
1148 _forward[u] = false;
1149 _pi[u] = ART_COST;
1150 _source[e] = _root;
1151 _target[e] = u;
1152 _flow[e] = -_supply[u];
1153 _cost[e] = ART_COST;
1154 }
1155 }
1156 } else if (_sum_supply > 0) {
1157 // LEQ supply constraints
1158 _search_arc_num = _arc_num + _node_num;
1159 ArcsType f = _arc_num + _node_num;
1160 for (ArcsType u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1161 _parent[u] = _root;
1162 _thread[u] = u + 1;
1163 _rev_thread[u + 1] = u;
1164 _succ_num[u] = 1;
1165 _last_succ[u] = u;
1166 if (_supply[u] >= 0) {
1167 _forward[u] = true;
1168 _pi[u] = 0;
1169 _pred[u] = e;
1170 _source[e] = u;
1171 _target[e] = _root;
1172 _flow[e] = _supply[u];
1173 _cost[e] = 0;
1174 _state[e] = STATE_TREE;
1175 } else {
1176 _forward[u] = false;
1177 _pi[u] = ART_COST;
1178 _pred[u] = f;
1179 _source[f] = _root;
1180 _target[f] = u;
1181 _flow[f] = -_supply[u];
1182 _cost[f] = ART_COST;
1183 _state[f] = STATE_TREE;
1184 _source[e] = u;
1185 _target[e] = _root;
1186 //_flow[e] = 0; //by default, the sparse matrix is empty
1187 _cost[e] = 0;
1188 _state[e] = STATE_LOWER;
1189 ++f;
1190 }
1191 }
1192 _all_arc_num = f;
1193 } else {
1194 // GEQ supply constraints
1195 _search_arc_num = _arc_num + _node_num;
1196 ArcsType f = _arc_num + _node_num;
1197 for (ArcsType u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1198 _parent[u] = _root;
1199 _thread[u] = u + 1;
1200 _rev_thread[u + 1] = u;
1201 _succ_num[u] = 1;
1202 _last_succ[u] = u;
1203 if (_supply[u] <= 0) {
1204 _forward[u] = false;
1205 _pi[u] = 0;
1206 _pred[u] = e;
1207 _source[e] = _root;
1208 _target[e] = u;
1209 _flow[e] = -_supply[u];
1210 _cost[e] = 0;
1211 _state[e] = STATE_TREE;
1212 } else {
1213 _forward[u] = true;
1214 _pi[u] = -ART_COST;
1215 _pred[u] = f;
1216 _source[f] = u;
1217 _target[f] = _root;
1218 _flow[f] = _supply[u];
1219 _state[f] = STATE_TREE;
1220 _cost[f] = ART_COST;
1221 _source[e] = _root;
1222 _target[e] = u;
1223 //_flow[e] = 0; //by default, the sparse matrix is empty
1224 _cost[e] = 0;
1225 _state[e] = STATE_LOWER;
1226 ++f;
1227 }
1228 }
1229 _all_arc_num = f;
1230 }
1231
1232 return true;
1233 }
1234
1235 // Find the join node
1236 void findJoinNode() {
1237 int u = _source[in_arc];
1238 int v = _target[in_arc];
1239 while (u != v) {
1240 if (_succ_num[u] < _succ_num[v]) {
1241 u = _parent[u];
1242 } else {
1243 v = _parent[v];
1244 }
1245 }
1246 join = u;
1247 }
1248
1249 // Find the leaving arc of the cycle and returns true if the
1250 // leaving arc is not the same as the entering arc
1251 bool findLeavingArc() {
1252 // Initialize first and second nodes according to the direction
1253 // of the cycle
1254 if (_state[in_arc] == STATE_LOWER) {
1255 first = _source[in_arc];
1256 second = _target[in_arc];
1257 } else {
1258 first = _target[in_arc];
1259 second = _source[in_arc];
1260 }
1261 delta = INF;
1262 char result = 0;
1263 Value d;
1264 ArcsType e;
1265
1266 // Search the cycle along the path form the first node to the root
1267 for (int u = first; u != join; u = _parent[u]) {
1268 e = _pred[u];
1269 d = _forward[u] ? _flow[e] : INF;
1270 if (d < delta) {
1271 delta = d;
1272 u_out = u;
1273 result = 1;
1274 }
1275 }
1276 // Search the cycle along the path form the second node to the root
1277 for (int u = second; u != join; u = _parent[u]) {
1278 e = _pred[u];
1279 d = _forward[u] ? INF : _flow[e];
1280 if (d <= delta) {
1281 delta = d;
1282 u_out = u;
1283 result = 2;
1284 }
1285 }
1286
1287 if (result == 1) {
1288 u_in = first;
1289 v_in = second;
1290 } else {
1291 u_in = second;
1292 v_in = first;
1293 }
1294 return result != 0;
1295 }
1296
1297 // Change _flow and _state vectors
1298 void changeFlow(bool change) {
1299 // Augment along the cycle
1300 if (delta > 0) {
1301 Value val = _state[in_arc] * delta;
1302 _flow[in_arc] += val;
1303 for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1304 _flow[_pred[u]] += _forward[u] ? -val : val;
1305 }
1306 for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1307 _flow[_pred[u]] += _forward[u] ? val : -val;
1308 }
1309 }
1310 // Update the state of the entering and leaving arcs
1311 if (change) {
1312 _state[in_arc] = STATE_TREE;
1313 _state[_pred[u_out]] =
1314 (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1315 } else {
1316 _state[in_arc] = -_state[in_arc];
1317 }
1318 }
1319
1320 // Update the tree structure
1321 void updateTreeStructure() {
1322 int old_rev_thread = _rev_thread[u_out];
1323 int old_succ_num = _succ_num[u_out];
1324 int old_last_succ = _last_succ[u_out];
1325 v_out = _parent[u_out];
1326
1327 // Check if u_in and u_out coincide
1328 if (u_in == u_out) {
1329 // Update _parent, _pred, _pred_dir
1330 _parent[u_in] = v_in;
1331 _pred[u_in] = in_arc;
1332 _forward[u_in] = (u_in == _source[in_arc]);
1333
1334 // Update _thread and _rev_thread
1335 if (_thread[v_in] != u_out) {
1336 ArcsType after = _thread[old_last_succ];
1337 _thread[old_rev_thread] = after;
1338 _rev_thread[after] = old_rev_thread;
1339 after = _thread[v_in];
1340 _thread[v_in] = u_out;
1341 _rev_thread[u_out] = v_in;
1342 _thread[old_last_succ] = after;
1343 _rev_thread[after] = old_last_succ;
1344 }
1345 } else {
1346 // Handle the case when old_rev_thread equals to v_in
1347 // (it also means that join and v_out coincide)
1348 int thread_continue = old_rev_thread == v_in ?
1349 _thread[old_last_succ] : _thread[v_in];
1350
1351 // Update _thread and _parent along the stem nodes (i.e. the nodes
1352 // between u_in and u_out, whose parent have to be changed)
1353 int stem = u_in; // the current stem node
1354 int par_stem = v_in; // the new parent of stem
1355 int next_stem; // the next stem node
1356 int last = _last_succ[u_in]; // the last successor of stem
1357 int before, after = _thread[last];
1358 _thread[v_in] = u_in;
1359 _dirty_revs.clear();
1360 _dirty_revs.push_back(v_in);
1361 while (stem != u_out) {
1362 // Insert the next stem node into the thread list
1363 next_stem = _parent[stem];
1364 _thread[last] = next_stem;
1365 _dirty_revs.push_back(last);
1366
1367 // Remove the subtree of stem from the thread list
1368 before = _rev_thread[stem];
1369 _thread[before] = after;
1370 _rev_thread[after] = before;
1371
1372 // Change the parent node and shift stem nodes
1373 _parent[stem] = par_stem;
1374 par_stem = stem;
1375 stem = next_stem;
1376
1377 // Update last and after
1378 last = _last_succ[stem] == _last_succ[par_stem] ?
1379 _rev_thread[par_stem] : _last_succ[stem];
1380 after = _thread[last];
1381 }
1382 _parent[u_out] = par_stem;
1383 _thread[last] = thread_continue;
1384 _rev_thread[thread_continue] = last;
1385 _last_succ[u_out] = last;
1386
1387 // Remove the subtree of u_out from the thread list except for
1388 // the case when old_rev_thread equals to v_in
1389 if (old_rev_thread != v_in) {
1390 _thread[old_rev_thread] = after;
1391 _rev_thread[after] = old_rev_thread;
1392 }
1393
1394 // Update _rev_thread using the new _thread values
1395 for (int i = 0; i != int(_dirty_revs.size()); ++i) {
1396 int u = _dirty_revs[i];
1397 _rev_thread[_thread[u]] = u;
1398 }
1399
1400 // Update _pred, _pred_dir, _last_succ and _succ_num for the
1401 // stem nodes from u_out to u_in
1402 int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1403 for (int u = u_out, p = _parent[u]; u != u_in; u = p, p = _parent[u]) {
1404 _pred[u] = _pred[p];
1405 _forward[u] = !_forward[p];
1406 tmp_sc += _succ_num[u] - _succ_num[p];
1407 _succ_num[u] = tmp_sc;
1408 _last_succ[p] = tmp_ls;
1409 }
1410 _pred[u_in] = in_arc;
1411 _forward[u_in] = (u_in == _source[in_arc]);
1412 _succ_num[u_in] = old_succ_num;
1413 }
1414
1415 // Update _last_succ from v_in towards the root
1416 int up_limit_out = _last_succ[join] == v_in ? join : -1;
1417 int last_succ_out = _last_succ[u_out];
1418 for (int u = v_in; u != -1 && _last_succ[u] == v_in; u = _parent[u]) {
1419 _last_succ[u] = last_succ_out;
1420 }
1421
1422 // Update _last_succ from v_out towards the root
1423 if (join != old_rev_thread && v_in != old_rev_thread) {
1424 for (int u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1425 u = _parent[u]) {
1426 _last_succ[u] = old_rev_thread;
1427 }
1428 } else if (last_succ_out != old_last_succ) {
1429 for (int u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1430 u = _parent[u]) {
1431 _last_succ[u] = last_succ_out;
1432 }
1433 }
1434
1435 // Update _succ_num from v_in to join
1436 for (int u = v_in; u != join; u = _parent[u]) {
1437 _succ_num[u] += old_succ_num;
1438 }
1439 // Update _succ_num from v_out to join
1440 for (int u = v_out; u != join; u = _parent[u]) {
1441 _succ_num[u] -= old_succ_num;
1442 }
1443 }
1444
1445 void updatePotential() {
1446 Cost sigma = _pi[v_in] - _pi[u_in] -
1447 ((_forward[u_in])?_cost[in_arc]:(-_cost[in_arc]));
1448 int end = _thread[_last_succ[u_in]];
1449 for (int u = u_in; u != end; u = _thread[u]) {
1450 _pi[u] += sigma;
1451 }
1452 }
1453
1454
1455 // Heuristic initial pivots
1456 bool initialPivots() {
1457 Value curr, total = 0;
1458 std::vector<Node> supply_nodes, demand_nodes;
1459 Node u; _graph.first(u);
1460 for (; u != INVALIDNODE; _graph.next(u)) {
1461 curr = _supply[_node_id(u)];
1462 if (curr > 0) {
1463 total += curr;
1464 supply_nodes.push_back(u);
1465 } else if (curr < 0) {
1466 demand_nodes.push_back(u);
1467 }
1468 }
1469 if (_sum_supply > 0) total -= _sum_supply;
1470 if (total <= 0) return true;
1471
1472 ArcVector arc_vector;
1473 if (_sum_supply >= 0) {
1474 if (supply_nodes.size() == 1 && demand_nodes.size() == 1) {
1475 // Perform a reverse graph search from the sink to the source
1476 //typename GR::template NodeMap<bool> reached(_graph, false);
1477 BoolVector reached(_node_num, false);
1478 Node s = supply_nodes[0], t = demand_nodes[0];
1479 std::vector<Node> stack;
1480 reached[t] = true;
1481 stack.push_back(t);
1482 while (!stack.empty()) {
1483 Node u, v = stack.back();
1484 stack.pop_back();
1485 if (v == s) break;
1486 Arc a; _graph.firstIn(a, v);
1487 for (; a != INVALID; _graph.nextIn(a)) {
1488 if (reached[u = _graph.source(a)]) continue;
1489 ArcsType j = getArcID(a);
1490 arc_vector.push_back(j);
1491 reached[u] = true;
1492 stack.push_back(u);
1493 }
1494 }
1495 } else {
1496 arc_vector.resize(demand_nodes.size());
1497 // Find the min. cost incomming arc for each demand node
1498 #pragma omp parallel for
1499 for (int i = 0; i < demand_nodes.size(); ++i) {
1500 Node v = demand_nodes[i];
1501 Cost min_cost = std::numeric_limits<Cost>::max();
1502 Arc min_arc = INVALID;
1503 Arc a; _graph.firstIn(a, v);
1504 for (; a != INVALID; _graph.nextIn(a)) {
1505 Cost c = _cost[getArcID(a)];
1506 if (c < min_cost) {
1507 min_cost = c;
1508 min_arc = a;
1509 }
1510 }
1511 arc_vector[i] = getArcID(min_arc);
1512 }
1513 arc_vector.erase(std::remove(arc_vector.begin(), arc_vector.end(), INVALID), arc_vector.end());
1514 }
1515 } else {
1516 arc_vector.resize(supply_nodes.size());
1517 // Find the min. cost outgoing arc for each supply node
1518 #pragma omp parallel for
1519 for (int i = 0; i < int(supply_nodes.size()); ++i) {
1520 Node u = supply_nodes[i];
1521 Cost min_cost = std::numeric_limits<Cost>::max();
1522 Arc min_arc = INVALID;
1523 Arc a; _graph.firstOut(a, u);
1524 for (; a != INVALID; _graph.nextOut(a)) {
1525 Cost c = _cost[getArcID(a)];
1526 if (c < min_cost) {
1527 min_cost = c;
1528 min_arc = a;
1529 }
1530 }
1531 arc_vector[i] = getArcID(min_arc);
1532 }
1533 arc_vector.erase(std::remove(arc_vector.begin(), arc_vector.end(), INVALID), arc_vector.end());
1534 }
1535
1536 // Perform heuristic initial pivots
1537 for (ArcsType i = 0; i != ArcsType(arc_vector.size()); ++i) {
1538 in_arc = arc_vector[i];
1539 if (_state[in_arc] * (_cost[in_arc] + _pi[_source[in_arc]] -
1540 _pi[_target[in_arc]]) >= 0) continue;
1541 findJoinNode();
1542 bool change = findLeavingArc();
1543 if (delta >= MAX) return false;
1544 changeFlow(change);
1545 if (change) {
1546 updateTreeStructure();
1547 updatePotential();
1548 }
1549 }
1550 return true;
1551 }
1552
1553 // Execute the algorithm
1554 ProblemType start() {
1555 return start<BlockSearchPivotRule>();
1556 }
1557
1558 template <typename PivotRuleImpl>
1559 ProblemType start() {
1560 PivotRuleImpl pivot(*this);
1561 ProblemType retVal = OPTIMAL;
1562
1563 // Perform heuristic initial pivots
1564 if (!initialPivots()) return UNBOUNDED;
1565
1566 uint64_t iter_number = 0;
1567 // Execute the Network Simplex algorithm
1568 while (pivot.findEnteringArc()) {
1569 if ((++iter_number <= max_iter&&max_iter > 0) || max_iter<=0) {
1570 #if DEBUG_LVL>0
1571 if(iter_number>MAX_DEBUG_ITER)
1572 break;
1573 if(iter_number%1000==0||iter_number%1000==1){
1574 Cost curCost=totalCost();
1575 Value sumFlow=0;
1576 Cost a;
1577 a= (fabs(_pi[_source[in_arc]])>=fabs(_pi[_target[in_arc]])) ? fabs(_pi[_source[in_arc]]) : fabs(_pi[_target[in_arc]]);
1578 a=a>=fabs(_cost[in_arc])?a:fabs(_cost[in_arc]);
1579 for (int i=0; i<_flow.size(); i++) {
1580 sumFlow+=_state[i]*_flow[i];
1581 }
1582 std::cout << "Sum of the flow " << std::setprecision(20) << sumFlow << "\n" << iter_number << " iterations, current cost=" << curCost << "\nReduced cost=" << _state[in_arc] * (_cost[in_arc] + _pi[_source[in_arc]] -_pi[_target[in_arc]]) << "\nPrecision = "<< -EPSILON*(a) << "\n";
1583 std::cout << "Arc in = (" << _node_id(_source[in_arc]) << ", " << _node_id(_target[in_arc]) <<")\n";
1584 std::cout << "Supplies = (" << _supply[_source[in_arc]] << ", " << _supply[_target[in_arc]] << ")\n";
1585 std::cout << _cost[in_arc] << "\n";
1586 std::cout << _pi[_source[in_arc]] << "\n";
1587 std::cout << _pi[_target[in_arc]] << "\n";
1588 std::cout << a << "\n";
1589 }
1590 #endif
1591
1592 findJoinNode();
1593 bool change = findLeavingArc();
1594 if (delta >= MAX) return UNBOUNDED;
1595 changeFlow(change);
1596 if (change) {
1597 updateTreeStructure();
1598 updatePotential();
1599 }
1600
1601 #if DEBUG_LVL>0
1602 else{
1603 std::cout << "No change\n";
1604 }
1605 #endif
1606
1607 #if DEBUG_LVL>1
1608 std::cout << "Arc in = (" << _source[in_arc] << ", " << _target[in_arc] << ")\n";
1609 #endif
1610
1611
1612 } else {
1613 // max iters
1614 retVal = MAX_ITER_REACHED;
1615 break;
1616 }
1617
1618 }
1619
1620
1621
1622 #if DEBUG_LVL>0
1623 Cost curCost=totalCost();
1624 Value sumFlow=0;
1625 Cost a;
1626 a= (fabs(_pi[_source[in_arc]])>=fabs(_pi[_target[in_arc]])) ? fabs(_pi[_source[in_arc]]) : fabs(_pi[_target[in_arc]]);
1627 a=a>=fabs(_cost[in_arc])?a:fabs(_cost[in_arc]);
1628 for (int i=0; i<_flow.size(); i++) {
1629 sumFlow+=_state[i]*_flow[i];
1630 }
1631
1632 std::cout << "Sum of the flow " << std::setprecision(20) << sumFlow << "\n" << niter << " iterations, current cost=" << curCost << "\nReduced cost=" << _state[in_arc] * (_cost[in_arc] + _pi[_source[in_arc]] -_pi[_target[in_arc]]) << "\nPrecision = "<< -EPSILON*(a) << "\n";
1633
1634 std::cout << "Arc in = (" << _node_id(_source[in_arc]) << ", " << _node_id(_target[in_arc]) <<")\n";
1635 std::cout << "Supplies = (" << _supply[_source[in_arc]] << ", " << _supply[_target[in_arc]] << ")\n";
1636
1637 #endif
1638
1639
1640
1641 #if DEBUG_LVL>1
1642 sumFlow=0;
1643 for (int i=0; i<_flow.size(); i++) {
1644 sumFlow+=_state[i]*_flow[i];
1645 if (_state[i]==STATE_TREE) {
1646 std::cout << "Non zero value at (" << _node_num+1-_source[i] << ", " << _node_num+1-_target[i] << ")\n";
1647 }
1648 }
1649 std::cout << "Sum of the flow " << sumFlow << "\n"<< niter <<" iterations, current cost=" << totalCost() << "\n";
1650 #endif
1651
1652
1653
1654 //Check feasibility
1655 if(retVal == OPTIMAL){
1656 for (ArcsType e = _search_arc_num; e != _all_arc_num; ++e) {
1657 if (_flow[e] != 0){
1658 if (fabs(_flow[e]) > _EPSILON) // change of the original code following issue #126
1659 return INFEASIBLE;
1660 else
1661 _flow[e]=0;
1662 }
1663 }
1664 }
1665
1666 // Shift potentials to meet the requirements of the GEQ/LEQ type
1667 // optimality conditions
1668 if (_sum_supply == 0) {
1669 if (_stype == GEQ) {
1670 Cost max_pot = -std::numeric_limits<Cost>::max();
1671 for (ArcsType i = 0; i != _node_num; ++i) {
1672 if (_pi[i] > max_pot) max_pot = _pi[i];
1673 }
1674 if (max_pot > 0) {
1675 for (ArcsType i = 0; i != _node_num; ++i)
1676 _pi[i] -= max_pot;
1677 }
1678 } else {
1679 Cost min_pot = std::numeric_limits<Cost>::max();
1680 for (ArcsType i = 0; i != _node_num; ++i) {
1681 if (_pi[i] < min_pot) min_pot = _pi[i];
1682 }
1683 if (min_pot < 0) {
1684 for (ArcsType i = 0; i != _node_num; ++i)
1685 _pi[i] -= min_pot;
1686 }
1687 }
1688 }
1689
1690 return retVal;
1691 }
1692
1693 }; //class NetworkSimplexSimple
1694
1695 ///@}
1696
1697 } //namespace lemon_omp