Debian Codegraph @

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