An experimental LPSolverWrapper class which uses glpk. For a short
demo, max flow problems are solved with it. This demo does not
demonstrates, but the main aims of this class are row and column
generation capabilities, i.e. to be a core for easily
implementable branch-and-cut a column generetion algorithms.
2 #ifndef HUGO_MAX_FLOW_H
3 #define HUGO_MAX_FLOW_H
8 #include <hugo/graph_wrapper.h>
9 #include <hugo/invalid.h>
10 #include <hugo/maps.h>
17 /// \addtogroup flowalgs
20 ///Maximum flow algorithms class.
22 ///This class provides various algorithms for finding a flow of
23 ///maximum value in a directed graph. The \e source node, the \e
24 ///target node, the \e capacity of the edges and the \e starting \e
25 ///flow value of the edges should be passed to the algorithm through the
26 ///constructor. It is possible to change these quantities using the
27 ///functions \ref setSource, \ref setTarget, \ref setCap and
28 ///\ref setFlow. Before any subsequent runs of any algorithm of
29 ///the class \ref setFlow should be called.
31 ///After running an algorithm of the class, the actual flow value
32 ///can be obtained by calling \ref flowValue(). The minimum
33 ///value cut can be written into a \c node map of \c bools by
34 ///calling \ref minCut. (\ref minMinCut and \ref maxMinCut writes
35 ///the inclusionwise minimum and maximum of the minimum value
38 ///\param Graph The directed graph type the algorithm runs on.
39 ///\param Num The number type of the capacities and the flow values.
40 ///\param CapMap The capacity map type.
41 ///\param FlowMap The flow map type.
43 ///\author Marton Makai, Jacint Szabo
44 template <typename Graph, typename Num,
45 typename CapMap=typename Graph::template EdgeMap<Num>,
46 typename FlowMap=typename Graph::template EdgeMap<Num> >
49 typedef typename Graph::Node Node;
50 typedef typename Graph::NodeIt NodeIt;
51 typedef typename Graph::EdgeIt EdgeIt;
52 typedef typename Graph::OutEdgeIt OutEdgeIt;
53 typedef typename Graph::InEdgeIt InEdgeIt;
55 typedef typename std::vector<Node> VecFirst;
56 typedef typename Graph::template NodeMap<Node> NNMap;
57 typedef typename std::vector<Node> VecNode;
62 const CapMap* capacity;
64 int n; //the number of nodes of G
65 typedef ResGraphWrapper<const Graph, Num, CapMap, FlowMap> ResGW;
66 //typedef ExpResGraphWrapper<const Graph, Num, CapMap, FlowMap> ResGW;
67 typedef typename ResGW::OutEdgeIt ResGWOutEdgeIt;
68 typedef typename ResGW::Edge ResGWEdge;
69 typedef typename Graph::template NodeMap<int> ReachedMap;
72 //level works as a bool map in augmenting path algorithms and is
73 //used by bfs for storing reached information. In preflow, it
74 //shows the levels of nodes.
77 //excess is needed only in preflow
78 typename Graph::template NodeMap<Num> excess;
80 // constants used for heuristics
81 static const int H0=20;
82 static const int H1=1;
86 ///Indicates the property of the starting flow.
88 ///Indicates the property of the starting flow. The meanings are as follows:
89 ///- \c ZERO_FLOW: constant zero flow
90 ///- \c GEN_FLOW: any flow, i.e. the sum of the in-flows equals to
91 ///the sum of the out-flows in every node except the \e source and
93 ///- \c PRE_FLOW: any preflow, i.e. the sum of the in-flows is at
94 ///least the sum of the out-flows in every node except the \e source.
95 ///- \c NO_FLOW: indicates an unspecified edge map. \ref flow will be
96 ///set to the constant zero flow in the beginning of the algorithm in this case.
107 AFTER_FAST_AUGMENTING,
108 AFTER_PRE_FLOW_PHASE_1,
109 AFTER_PRE_FLOW_PHASE_2
112 /// Do not needle this flag only if necessary.
115 // int number_of_augmentations;
118 // template<typename IntMap>
119 // class TrickyReachedMap {
122 // int* number_of_augmentations;
124 // TrickyReachedMap(IntMap& _map, int& _number_of_augmentations) :
125 // map(&_map), number_of_augmentations(&_number_of_augmentations) { }
126 // void set(const Node& n, bool b) {
128 // map->set(n, *number_of_augmentations);
130 // map->set(n, *number_of_augmentations-1);
132 // bool operator[](const Node& n) const {
133 // return (*map)[n]==*number_of_augmentations;
139 ///\todo Document, please.
141 MaxFlow(const Graph& _G, Node _s, Node _t,
142 const CapMap& _capacity, FlowMap& _flow) :
143 g(&_G), s(_s), t(_t), capacity(&_capacity),
144 flow(&_flow), n(_G.nodeNum()), level(_G), excess(_G,0),
145 status(AFTER_NOTHING) { }
147 ///Runs a maximum flow algorithm.
149 ///Runs a preflow algorithm, which is the fastest maximum flow
150 ///algorithm up-to-date. The default for \c fe is ZERO_FLOW.
151 ///\pre The starting flow must be
152 /// - a constant zero flow if \c fe is \c ZERO_FLOW,
153 /// - an arbitary flow if \c fe is \c GEN_FLOW,
154 /// - an arbitary preflow if \c fe is \c PRE_FLOW,
155 /// - any map if \c fe is NO_FLOW.
156 void run(FlowEnum fe=ZERO_FLOW) {
161 ///Runs a preflow algorithm.
163 ///Runs a preflow algorithm. The preflow algorithms provide the
164 ///fastest way to compute a maximum flow in a directed graph.
165 ///\pre The starting flow must be
166 /// - a constant zero flow if \c fe is \c ZERO_FLOW,
167 /// - an arbitary flow if \c fe is \c GEN_FLOW,
168 /// - an arbitary preflow if \c fe is \c PRE_FLOW,
169 /// - any map if \c fe is NO_FLOW.
171 ///\todo NO_FLOW should be the default flow.
172 void preflow(FlowEnum fe) {
179 // list 'level_list' on the nodes on level i implemented by hand
180 // stack 'active' on the active nodes on level i
181 // runs heuristic 'highest label' for H1*n relabels
182 // runs heuristic 'bound decrease' for H0*n relabels, starts with 'highest label'
183 // Parameters H0 and H1 are initialized to 20 and 1.
185 ///Runs the first phase of the preflow algorithm.
187 ///The preflow algorithm consists of two phases, this method runs the
188 ///first phase. After the first phase the maximum flow value and a
189 ///minimum value cut can already be computed, though a maximum flow
190 ///is not yet obtained. So after calling this method \ref flowValue
191 ///and \ref actMinCut gives proper results.
192 ///\warning: \ref minCut, \ref minMinCut and \ref maxMinCut do not
193 ///give minimum value cuts unless calling \ref preflowPhase2.
194 ///\pre The starting flow must be
195 /// - a constant zero flow if \c fe is \c ZERO_FLOW,
196 /// - an arbitary flow if \c fe is \c GEN_FLOW,
197 /// - an arbitary preflow if \c fe is \c PRE_FLOW,
198 /// - any map if \c fe is NO_FLOW.
199 void preflowPhase1(FlowEnum fe)
202 int heur0=(int)(H0*n); //time while running 'bound decrease'
203 int heur1=(int)(H1*n); //time while running 'highest label'
204 int heur=heur1; //starting time interval (#of relabels)
208 //It is 0 in case 'bound decrease' and 1 in case 'highest label'
211 //Needed for 'bound decrease', true means no active nodes are above bound
214 int k=n-2; //bound on the highest level under n containing a node
215 int b=k; //bound on the highest level under n of an active node
217 VecFirst first(n, INVALID);
218 NNMap next(*g, INVALID); //maybe INVALID is not needed
220 NNMap left(*g, INVALID);
221 NNMap right(*g, INVALID);
222 VecNode level_list(n,INVALID);
223 //List of the nodes in level i<n, set to n.
225 preflowPreproc(fe, next, first, level_list, left, right);
226 //End of preprocessing
228 //Push/relabel on the highest level active nodes.
231 if ( !what_heur && !end && k > 0 ) {
237 if ( !g->valid(first[b]) ) --b;
242 int newlevel=push(w, next, first);
243 if ( excess[w] > 0 ) relabel(w, newlevel, next, first, level_list,
244 left, right, b, k, what_heur);
247 if ( numrelabel >= heur ) {
262 status=AFTER_PRE_FLOW_PHASE_1;
266 ///Runs the second phase of the preflow algorithm.
268 ///The preflow algorithm consists of two phases, this method runs
269 ///the second phase. After calling \ref preflowPhase1 and then
270 ///\ref preflowPhase2 the methods \ref flowValue, \ref minCut,
271 ///\ref minMinCut and \ref maxMinCut give proper results.
272 ///\pre \ref preflowPhase1 must be called before.
276 int k=n-2; //bound on the highest level under n containing a node
277 int b=k; //bound on the highest level under n of an active node
280 VecFirst first(n, INVALID);
281 NNMap next(*g, INVALID); //maybe INVALID is not needed
283 std::queue<Node> bfs_queue;
286 while (!bfs_queue.empty()) {
288 Node v=bfs_queue.front();
293 for(g->first(e,v); g->valid(e); g->next(e)) {
294 if ( (*capacity)[e] <= (*flow)[e] ) continue;
296 if ( level[u] >= n ) {
299 if ( excess[u] > 0 ) {
300 next.set(u,first[l]);
307 for(g->first(f,v); g->valid(f); g->next(f)) {
308 if ( 0 >= (*flow)[f] ) continue;
310 if ( level[u] >= n ) {
313 if ( excess[u] > 0 ) {
314 next.set(u,first[l]);
326 if ( !g->valid(first[b]) ) --b;
331 int newlevel=push(w,next, first/*active*/);
334 if ( excess[w] > 0 ) {
335 level.set(w,++newlevel);
336 next.set(w,first[newlevel]);
343 status=AFTER_PRE_FLOW_PHASE_2;
347 /// Returns the value of the maximum flow.
349 /// Returns the excess of the target node \ref t.
350 /// After running \ref preflowPhase1, this is the value of
351 /// the maximum flow.
352 /// It can be called already after running \ref preflowPhase1.
353 Num flowValue() const {
355 // for(InEdgeIt e(*g,t);g->valid(e);g->next(e)) a+=(*flow)[e];
356 // for(OutEdgeIt e(*g,t);g->valid(e);g->next(e)) a-=(*flow)[e];
359 //marci figyu: excess[t] epp ezt adja preflow 1. fazisa utan
363 ///Returns a minimum value cut after calling \ref preflowPhase1.
365 ///After the first phase of the preflow algorithm the maximum flow
366 ///value and a minimum value cut can already be computed. This
367 ///method can be called after running \ref preflowPhase1 for
368 ///obtaining a minimum value cut.
369 /// \warning Gives proper result only right after calling \ref
371 /// \todo We have to make some status variable which shows the
373 /// of the class. This enables us to determine which methods are valid
374 /// for MinCut computation
375 template<typename _CutMap>
376 void actMinCut(_CutMap& M) const {
379 case AFTER_PRE_FLOW_PHASE_1:
380 for(g->first(v); g->valid(v); g->next(v)) {
388 case AFTER_PRE_FLOW_PHASE_2:
390 case AFTER_AUGMENTING:
391 case AFTER_FAST_AUGMENTING:
397 ///Returns the inclusionwise minimum of the minimum value cuts.
399 ///Sets \c M to the characteristic vector of the minimum value cut
400 ///which is inclusionwise minimum. It is computed by processing
401 ///a bfs from the source node \c s in the residual graph.
402 ///\pre M should be a node map of bools initialized to false.
403 ///\pre \c flow must be a maximum flow.
404 template<typename _CutMap>
405 void minMinCut(_CutMap& M) const {
406 std::queue<Node> queue;
411 while (!queue.empty()) {
412 Node w=queue.front();
416 for(g->first(e,w) ; g->valid(e); g->next(e)) {
418 if (!M[v] && (*flow)[e] < (*capacity)[e] ) {
425 for(g->first(f,w) ; g->valid(f); g->next(f)) {
427 if (!M[v] && (*flow)[f] > 0 ) {
435 ///Returns the inclusionwise maximum of the minimum value cuts.
437 ///Sets \c M to the characteristic vector of the minimum value cut
438 ///which is inclusionwise maximum. It is computed by processing a
439 ///backward bfs from the target node \c t in the residual graph.
440 ///\pre M should be a node map of bools initialized to false.
441 ///\pre \c flow must be a maximum flow.
442 template<typename _CutMap>
443 void maxMinCut(_CutMap& M) const {
446 for(g->first(v) ; g->valid(v); g->next(v)) {
450 std::queue<Node> queue;
455 while (!queue.empty()) {
456 Node w=queue.front();
460 for(g->first(e,w) ; g->valid(e); g->next(e)) {
462 if (M[v] && (*flow)[e] < (*capacity)[e] ) {
469 for(g->first(f,w) ; g->valid(f); g->next(f)) {
471 if (M[v] && (*flow)[f] > 0 ) {
479 ///Returns a minimum value cut.
481 ///Sets \c M to the characteristic vector of a minimum value cut.
482 ///\pre M should be a node map of bools initialized to false.
483 ///\pre \c flow must be a maximum flow.
484 template<typename CutMap>
485 void minCut(CutMap& M) const { minMinCut(M); }
487 ///Sets the source node to \c _s.
489 ///Sets the source node to \c _s.
491 void setSource(Node _s) { s=_s; status=AFTER_NOTHING; }
493 ///Sets the target node to \c _t.
495 ///Sets the target node to \c _t.
497 void setTarget(Node _t) { t=_t; status=AFTER_NOTHING; }
499 /// Sets the edge map of the capacities to _cap.
501 /// Sets the edge map of the capacities to _cap.
503 void setCap(const CapMap& _cap)
504 { capacity=&_cap; status=AFTER_NOTHING; }
506 /// Sets the edge map of the flows to _flow.
508 /// Sets the edge map of the flows to _flow.
510 void setFlow(FlowMap& _flow) { flow=&_flow; status=AFTER_NOTHING; }
515 int push(Node w, NNMap& next, VecFirst& first) {
519 int newlevel=n; //bound on the next level of w
522 for(g->first(e,w); g->valid(e); g->next(e)) {
524 if ( (*flow)[e] >= (*capacity)[e] ) continue;
527 if( lev > level[v] ) { //Push is allowed now
529 if ( excess[v]<=0 && v!=t && v!=s ) {
530 next.set(v,first[level[v]]);
534 Num cap=(*capacity)[e];
538 if ( remcap >= exc ) { //A nonsaturating push.
540 flow->set(e, flo+exc);
541 excess.set(v, excess[v]+exc);
545 } else { //A saturating push.
547 excess.set(v, excess[v]+remcap);
550 } else if ( newlevel > level[v] ) newlevel = level[v];
555 for(g->first(e,w); g->valid(e); g->next(e)) {
557 if( (*flow)[e] <= 0 ) continue;
560 if( lev > level[v] ) { //Push is allowed now
562 if ( excess[v]<=0 && v!=t && v!=s ) {
563 next.set(v,first[level[v]]);
569 if ( flo >= exc ) { //A nonsaturating push.
571 flow->set(e, flo-exc);
572 excess.set(v, excess[v]+exc);
575 } else { //A saturating push.
577 excess.set(v, excess[v]+flo);
581 } else if ( newlevel > level[v] ) newlevel = level[v];
584 } // if w still has excess after the out edge for cycle
593 void preflowPreproc(FlowEnum fe, NNMap& next, VecFirst& first,
594 VecNode& level_list, NNMap& left, NNMap& right)
596 switch (fe) { //setting excess
600 for(g->first(e); g->valid(e); g->next(e)) flow->set(e,0);
603 for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
609 for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
615 for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
619 for(g->first(e,t); g->valid(e); g->next(e)) exc+=(*flow)[e];
621 for(g->first(f,t); g->valid(f); g->next(f)) exc-=(*flow)[f];
629 for(g->first(v); g->valid(v); g->next(v)) level.set(v,n);
630 //setting each node to level n
632 std::queue<Node> bfs_queue;
636 case NO_FLOW: //flow is already set to const zero
639 //Reverse_bfs from t, to find the starting level.
643 while (!bfs_queue.empty()) {
645 Node v=bfs_queue.front();
650 for(g->first(e,v); g->valid(e); g->next(e)) {
652 if ( level[w] == n && w != s ) {
654 Node z=level_list[l];
655 if ( g->valid(z) ) left.set(z,w);
665 for(g->first(e,s); g->valid(e); g->next(e))
667 Num c=(*capacity)[e];
668 if ( c <= 0 ) continue;
670 if ( level[w] < n ) {
671 if ( excess[w] <= 0 && w!=t ) //putting into the stack
673 next.set(w,first[level[w]]);
677 excess.set(w, excess[w]+c);
685 //Reverse_bfs from t in the residual graph,
686 //to find the starting level.
690 while (!bfs_queue.empty()) {
692 Node v=bfs_queue.front();
697 for(g->first(e,v); g->valid(e); g->next(e)) {
698 if ( (*capacity)[e] <= (*flow)[e] ) continue;
700 if ( level[w] == n && w != s ) {
702 Node z=level_list[l];
703 if ( g->valid(z) ) left.set(z,w);
711 for(g->first(f,v); g->valid(f); g->next(f)) {
712 if ( 0 >= (*flow)[f] ) continue;
714 if ( level[w] == n && w != s ) {
716 Node z=level_list[l];
717 if ( g->valid(z) ) left.set(z,w);
727 for(g->first(e,s); g->valid(e); g->next(e))
729 Num rem=(*capacity)[e]-(*flow)[e];
730 if ( rem <= 0 ) continue;
732 if ( level[w] < n ) {
733 if ( excess[w] <= 0 && w!=t ) //putting into the stack
735 next.set(w,first[level[w]]);
738 flow->set(e, (*capacity)[e]);
739 excess.set(w, excess[w]+rem);
744 for(g->first(f,s); g->valid(f); g->next(f))
746 if ( (*flow)[f] <= 0 ) continue;
748 if ( level[w] < n ) {
749 if ( excess[w] <= 0 && w!=t )
751 next.set(w,first[level[w]]);
754 excess.set(w, excess[w]+(*flow)[f]);
763 //Reverse_bfs from t in the residual graph,
764 //to find the starting level.
768 while (!bfs_queue.empty()) {
770 Node v=bfs_queue.front();
775 for(g->first(e,v); g->valid(e); g->next(e)) {
776 if ( (*capacity)[e] <= (*flow)[e] ) continue;
778 if ( level[w] == n && w != s ) {
780 Node z=level_list[l];
781 if ( g->valid(z) ) left.set(z,w);
789 for(g->first(f,v); g->valid(f); g->next(f)) {
790 if ( 0 >= (*flow)[f] ) continue;
792 if ( level[w] == n && w != s ) {
794 Node z=level_list[l];
795 if ( g->valid(z) ) left.set(z,w);
806 for(g->first(e,s); g->valid(e); g->next(e))
808 Num rem=(*capacity)[e]-(*flow)[e];
809 if ( rem <= 0 ) continue;
811 if ( level[w] < n ) {
812 flow->set(e, (*capacity)[e]);
813 excess.set(w, excess[w]+rem);
818 for(g->first(f,s); g->valid(f); g->next(f))
820 if ( (*flow)[f] <= 0 ) continue;
822 if ( level[w] < n ) {
823 excess.set(w, excess[w]+(*flow)[f]);
828 NodeIt w; //computing the excess
829 for(g->first(w); g->valid(w); g->next(w)) {
833 for(g->first(e,w); g->valid(e); g->next(e)) exc+=(*flow)[e];
835 for(g->first(f,w); g->valid(f); g->next(f)) exc-=(*flow)[f];
839 //putting the active nodes into the stack
841 if ( exc > 0 && lev < n && w != t )
843 next.set(w,first[lev]);
853 void relabel(Node w, int newlevel, NNMap& next, VecFirst& first,
854 VecNode& level_list, NNMap& left,
855 NNMap& right, int& b, int& k, bool what_heur )
860 Node right_n=right[w];
864 if ( g->valid(right_n) ) {
865 if ( g->valid(left_n) ) {
866 right.set(left_n, right_n);
867 left.set(right_n, left_n);
869 level_list[lev]=right_n;
870 left.set(right_n, INVALID);
873 if ( g->valid(left_n) ) {
874 right.set(left_n, INVALID);
876 level_list[lev]=INVALID;
881 if ( !g->valid(level_list[lev]) ) {
884 for (int i=lev; i!=k ; ) {
885 Node v=level_list[++i];
886 while ( g->valid(v) ) {
890 level_list[i]=INVALID;
891 if ( !what_heur ) first[i]=INVALID;
901 if ( newlevel == n ) level.set(w,n);
903 level.set(w,++newlevel);
904 next.set(w,first[newlevel]);
906 if ( what_heur ) b=newlevel;
907 if ( k < newlevel ) ++k; //now k=newlevel
908 Node z=level_list[newlevel];
909 if ( g->valid(z) ) left.set(z,w);
912 level_list[newlevel]=w;
917 void printexcess() {////
918 std::cout << "Excesses:" <<std::endl;
921 for(g->first(v); g->valid(v); g->next(v)) {
922 std::cout << 1+(g->id(v)) << ":" << excess[v]<<std::endl;
926 void printlevel() {////
927 std::cout << "Levels:" <<std::endl;
930 for(g->first(v); g->valid(v); g->next(v)) {
931 std::cout << 1+(g->id(v)) << ":" << level[v]<<std::endl;
935 void printactive() {////
936 std::cout << "Levels:" <<std::endl;
939 for(g->first(v); g->valid(v); g->next(v)) {
940 std::cout << 1+(g->id(v)) << ":" << level[v]<<std::endl;
948 #endif //HUGO_MAX_FLOW_H