src/work/athos/mincostflow.h
author athos
Tue, 01 Jun 2004 11:00:24 +0000
changeset 671 708df4dc6ab6
parent 662 0155001b6f65
child 672 6c7bd0edd1d7
permissions -rw-r--r--
Compiles now
athos@610
     1
// -*- c++ -*-
athos@633
     2
#ifndef HUGO_MINCOSTFLOW_H
athos@633
     3
#define HUGO_MINCOSTFLOW_H
athos@610
     4
athos@610
     5
///\ingroup galgs
athos@610
     6
///\file
athos@645
     7
///\brief An algorithm for finding the minimum cost flow of given value in an uncapacitated network
athos@611
     8
athos@610
     9
#include <hugo/dijkstra.h>
athos@610
    10
#include <hugo/graph_wrapper.h>
athos@610
    11
#include <hugo/maps.h>
athos@610
    12
#include <vector>
athos@657
    13
#include <list>
athos@662
    14
#include <values.h>
athos@661
    15
#include <hugo/for_each_macros.h>
athos@661
    16
#include <hugo/unionfind.h>
athos@662
    17
#include <hugo/bin_heap.h>
athos@662
    18
#include <bfs_dfs.h>
athos@610
    19
athos@610
    20
namespace hugo {
athos@610
    21
athos@610
    22
/// \addtogroup galgs
athos@610
    23
/// @{
athos@610
    24
athos@661
    25
  ///\brief Implementation of an algorithm for solving the minimum cost general
athos@661
    26
  /// flow problem in an uncapacitated network
athos@610
    27
  /// 
athos@610
    28
  ///
athos@633
    29
  /// The class \ref hugo::MinCostFlow "MinCostFlow" implements
athos@633
    30
  /// an algorithm for solving the following general minimum cost flow problem>
athos@633
    31
  /// 
athos@633
    32
  ///
athos@633
    33
  ///
athos@633
    34
  /// \warning It is assumed here that the problem has a feasible solution
athos@633
    35
  ///
athos@661
    36
  /// The range of the cost (weight) function is nonnegative reals but 
athos@610
    37
  /// the range of capacity function is the set of nonnegative integers. 
athos@610
    38
  /// It is not a polinomial time algorithm for counting the minimum cost
athos@610
    39
  /// maximal flow, since it counts the minimum cost flow for every value 0..M
athos@610
    40
  /// where \c M is the value of the maximal flow.
athos@610
    41
  ///
athos@610
    42
  ///\author Attila Bernath
athos@661
    43
  template <typename Graph, typename CostMap, typename SupplyDemandMap>
athos@633
    44
  class MinCostFlow {
athos@610
    45
athos@661
    46
    typedef typename CostMap::ValueType Cost;
athos@610
    47
athos@633
    48
athos@635
    49
    typedef typename SupplyDemandMap::ValueType SupplyDemand;
athos@610
    50
    
athos@610
    51
    typedef typename Graph::Node Node;
athos@610
    52
    typedef typename Graph::NodeIt NodeIt;
athos@610
    53
    typedef typename Graph::Edge Edge;
athos@610
    54
    typedef typename Graph::OutEdgeIt OutEdgeIt;
athos@661
    55
    typedef typename Graph::template EdgeMap<SupplyDemand> FlowMap;
athos@661
    56
    typedef ConstMap<Edge,SupplyDemand> ConstEdgeMap;
athos@610
    57
athos@610
    58
    //    typedef ConstMap<Edge,int> ConstMap;
athos@610
    59
athos@661
    60
    typedef ResGraphWrapper<const Graph,int,ConstEdgeMap,FlowMap> ResGraph;
athos@661
    61
    typedef typename ResGraph::Edge ResGraphEdge;
athos@610
    62
athos@661
    63
    class ModCostMap {   
athos@661
    64
      //typedef typename ResGraph::template NodeMap<Cost> NodeMap;
athos@661
    65
      typedef typename Graph::template NodeMap<Cost> NodeMap;
athos@661
    66
      const ResGraph& res_graph;
athos@610
    67
      //      const EdgeIntMap& rev;
athos@661
    68
      const CostMap &ol;
athos@610
    69
      const NodeMap &pot;
athos@610
    70
    public :
athos@661
    71
      typedef typename CostMap::KeyType KeyType;
athos@661
    72
      typedef typename CostMap::ValueType ValueType;
athos@610
    73
	
athos@661
    74
      ValueType operator[](typename ResGraph::Edge e) const {     
athos@659
    75
	if (res_graph.forward(e))
athos@659
    76
	  return  ol[e]-(pot[res_graph.head(e)]-pot[res_graph.tail(e)]);   
athos@610
    77
	else
athos@659
    78
	  return -ol[e]-(pot[res_graph.head(e)]-pot[res_graph.tail(e)]);   
athos@610
    79
      }     
athos@610
    80
	
athos@661
    81
      ModCostMap(const ResGraph& _res_graph,
athos@661
    82
		   const CostMap &o,  const NodeMap &p) : 
athos@659
    83
	res_graph(_res_graph), /*rev(_rev),*/ ol(o), pot(p){}; 
athos@661
    84
    };//ModCostMap
athos@610
    85
athos@610
    86
athos@610
    87
  protected:
athos@610
    88
    
athos@610
    89
    //Input
athos@659
    90
    const Graph& graph;
athos@661
    91
    const CostMap& cost;
athos@635
    92
    const SupplyDemandMap& supply_demand;//supply or demand of nodes
athos@610
    93
athos@610
    94
athos@610
    95
    //auxiliary variables
athos@610
    96
athos@610
    97
    //To store the flow
athos@661
    98
    FlowMap flow; 
athos@662
    99
    //To store the potential (dual variables)
athos@662
   100
    typedef typename Graph::template NodeMap<Cost> PotentialMap;
athos@662
   101
    PotentialMap potential;
athos@633
   102
    //To store excess-deficit values
athos@635
   103
    SupplyDemandMap excess_deficit;
athos@610
   104
    
athos@610
   105
athos@661
   106
    Cost total_cost;
athos@610
   107
athos@610
   108
athos@610
   109
  public :
athos@610
   110
athos@610
   111
athos@662
   112
   MinCostFlow(Graph& _graph, CostMap& _cost, SupplyDemandMap& _supply_demand):
athos@662
   113
     graph(_graph), 
athos@662
   114
     cost(_cost), 
athos@662
   115
     supply_demand(_supply_demand), 
athos@662
   116
     flow(_graph), 
athos@662
   117
     potential(_graph),
athos@662
   118
     excess_deficit(_graph){ }
athos@610
   119
athos@610
   120
    
athos@610
   121
    ///Runs the algorithm.
athos@610
   122
athos@610
   123
    ///Runs the algorithm.
athos@635
   124
athos@610
   125
    ///\todo May be it does make sense to be able to start with a nonzero 
athos@610
   126
    /// feasible primal-dual solution pair as well.
athos@659
   127
    void run() {
athos@610
   128
athos@610
   129
      //Resetting variables from previous runs
athos@661
   130
      //total_cost = 0;
athos@635
   131
athos@635
   132
      typedef typename Graph::template NodeMap<int> HeapMap;
athos@662
   133
      typedef BinHeap< Node, SupplyDemand, typename Graph::template NodeMap<int>,
athos@635
   134
	std::greater<SupplyDemand> > 	HeapType;
athos@635
   135
athos@635
   136
      //A heap for the excess nodes
athos@659
   137
      HeapMap excess_nodes_map(graph,-1);
athos@635
   138
      HeapType excess_nodes(excess_nodes_map);
athos@635
   139
athos@635
   140
      //A heap for the deficit nodes
athos@659
   141
      HeapMap deficit_nodes_map(graph,-1);
athos@635
   142
      HeapType deficit_nodes(deficit_nodes_map);
athos@635
   143
athos@657
   144
      //A container to store nonabundant arcs
athos@662
   145
      std::list<Edge> nonabundant_arcs;
athos@659
   146
athos@659
   147
	
athos@659
   148
      FOR_EACH_LOC(typename Graph::EdgeIt, e, graph){
athos@610
   149
	flow.set(e,0);
athos@657
   150
	nonabundant_arcs.push_back(e);
athos@610
   151
      }
athos@633
   152
athos@633
   153
      //Initial value for delta
athos@635
   154
      SupplyDemand delta = 0;
athos@635
   155
athos@657
   156
      typedef UnionFindEnum<Node, Graph::template NodeMap> UFE;
athos@657
   157
athos@657
   158
      //A union-find structure to store the abundant components
athos@662
   159
      typename UFE::MapType abund_comp_map(graph);
athos@657
   160
      UFE abundant_components(abund_comp_map);
athos@657
   161
athos@657
   162
athos@657
   163
athos@659
   164
      FOR_EACH_LOC(typename Graph::NodeIt, n, graph){
athos@635
   165
       	excess_deficit.set(n,supply_demand[n]);
athos@635
   166
	//A supply node
athos@635
   167
	if (excess_deficit[n] > 0){
athos@635
   168
	  excess_nodes.push(n,excess_deficit[n]);
athos@633
   169
	}
athos@635
   170
	//A demand node
athos@635
   171
	if (excess_deficit[n] < 0){
athos@635
   172
	  deficit_nodes.push(n, - excess_deficit[n]);
athos@635
   173
	}
athos@635
   174
	//Finding out starting value of delta
athos@635
   175
	if (delta < abs(excess_deficit[n])){
athos@635
   176
	  delta = abs(excess_deficit[n]);
athos@635
   177
	}
athos@633
   178
	//Initialize the copy of the Dijkstra potential to zero
athos@610
   179
	potential.set(n,0);
athos@657
   180
	//Every single point is an abundant component initially 
athos@657
   181
	abundant_components.insert(n);
athos@610
   182
      }
athos@610
   183
athos@635
   184
      //It'll be allright as an initial value, though this value 
athos@635
   185
      //can be the maximum deficit here
athos@635
   186
      SupplyDemand max_excess = delta;
athos@610
   187
      
athos@661
   188
      ///\bug This is a serious cheat here, before we have an uncapacitated ResGraph
athos@662
   189
      ConstEdgeMap const_inf_map(MAXINT);
athos@661
   190
      
athos@633
   191
      //We need a residual graph which is uncapacitated
athos@661
   192
      ResGraph res_graph(graph, const_inf_map, flow);
athos@659
   193
      
athos@659
   194
      //An EdgeMap to tell which arcs are abundant
athos@662
   195
      typename Graph::template EdgeMap<bool> abundant_arcs(graph);
athos@610
   196
athos@659
   197
      //Let's construct the sugraph consisting only of the abundant edges
athos@659
   198
      typedef ConstMap< typename Graph::Node, bool > ConstNodeMap;
athos@659
   199
      ConstNodeMap const_true_map(true);
athos@662
   200
      typedef SubGraphWrapper< const Graph, ConstNodeMap, 
athos@662
   201
	 typename Graph::template EdgeMap<bool> > 
athos@659
   202
	AbundantGraph;
athos@659
   203
      AbundantGraph abundant_graph(graph, const_true_map, abundant_arcs );
athos@659
   204
      
athos@659
   205
      //Let's construct the residual graph for the abundant graph
athos@662
   206
      typedef ResGraphWrapper<const AbundantGraph,int,ConstEdgeMap,FlowMap> 
athos@659
   207
	ResAbGraph;
athos@659
   208
      //Again uncapacitated
athos@661
   209
      ResAbGraph res_ab_graph(abundant_graph, const_inf_map, flow);
athos@659
   210
      
athos@659
   211
      //We need things for the bfs
athos@662
   212
      typename ResAbGraph::template NodeMap<bool> bfs_reached(res_ab_graph);
athos@662
   213
      typename ResAbGraph::template NodeMap<typename ResAbGraph::Edge> 
athos@659
   214
	bfs_pred(res_ab_graph); 
athos@662
   215
      NullMap<typename ResAbGraph::Node, int> bfs_dist_dummy;
athos@671
   216
      //Teszt celbol:
athos@671
   217
      //BfsIterator<ResAbGraph, typename ResAbGraph::template NodeMap<bool> > 
athos@671
   218
      //izebize(res_ab_graph, bfs_reached);
athos@659
   219
      //We want to run bfs-es (more) on this graph 'res_ab_graph'
athos@671
   220
      Bfs < const ResAbGraph , 
athos@662
   221
	typename ResAbGraph::template NodeMap<bool>, 
athos@662
   222
	typename ResAbGraph::template NodeMap<typename ResAbGraph::Edge>,
athos@659
   223
	NullMap<typename ResAbGraph::Node, int> > 
athos@659
   224
	bfs(res_ab_graph, bfs_reached, bfs_pred, bfs_dist_dummy);
athos@662
   225
      /*This is what Marci wants for a bfs
athos@662
   226
	template <typename Graph, 
athos@662
   227
	    typename ReachedMap=typename Graph::template NodeMap<bool>, 
athos@662
   228
	    typename PredMap
athos@662
   229
	    =typename Graph::template NodeMap<typename Graph::Edge>, 
athos@662
   230
	    typename DistMap=typename Graph::template NodeMap<int> > 
athos@662
   231
	    class Bfs : public BfsIterator<Graph, ReachedMap> {
athos@662
   232
athos@662
   233
       */
athos@610
   234
      
athos@661
   235
      ModCostMap mod_cost(res_graph, cost, potential);
athos@610
   236
athos@661
   237
      Dijkstra<ResGraph, ModCostMap> dijkstra(res_graph, mod_cost);
athos@610
   238
athos@671
   239
      //We will use the number of the nodes of the graph often
athos@671
   240
      int number_of_nodes = graph.nodeNum();
athos@633
   241
athos@635
   242
      while (max_excess > 0){
athos@635
   243
athos@657
   244
	//Reset delta if still too big
athos@657
   245
	if (8*number_of_nodes*max_excess <= delta){
athos@657
   246
	  delta = max_excess;
athos@657
   247
	  
athos@657
   248
	}
athos@657
   249
athos@645
   250
	/*
athos@645
   251
	 * Beginning of the delta scaling phase 
athos@645
   252
	*/
athos@635
   253
	//Merge and stuff
athos@657
   254
	{
athos@657
   255
	  SupplyDemand buf=8*number_of_nodes*delta;
athos@662
   256
	  typename std::list<Edge>::iterator i = nonabundant_arcs.begin();
athos@657
   257
	  while ( i != nonabundant_arcs.end() ){
athos@671
   258
	    if (flow[*i]>=buf){
athos@671
   259
	      Node a = abundant_components.find(res_graph.head(*i));
athos@671
   260
	      Node b = abundant_components.find(res_graph.tail(*i));
athos@657
   261
	      //Merge
athos@657
   262
	      if (a != b){
athos@657
   263
		abundant_components.join(a,b);
athos@659
   264
		//We want to push the smaller
athos@659
   265
		//Which has greater absolut value excess/deficit
athos@659
   266
		Node root=(abs(excess_deficit[a])>abs(excess_deficit[b]))?a:b;
athos@659
   267
		//Which is the other
athos@659
   268
		Node non_root = ( a == root ) ? b : a ;
athos@659
   269
		abundant_components.makeRep(root);
athos@659
   270
		SupplyDemand qty_to_augment = abs(excess_deficit[non_root]); 
athos@659
   271
		//Push the positive value
athos@659
   272
		if (excess_deficit[non_root] < 0)
athos@659
   273
		  swap(root, non_root);
athos@659
   274
		//If the non_root node has excess/deficit at all
athos@659
   275
		if (qty_to_augment>0){
athos@659
   276
		  //Find path and augment
athos@671
   277
		  bfs.run(typename AbundantGraph::Node(non_root));
athos@659
   278
		  //root should be reached
athos@659
   279
		  
athos@659
   280
		  //Augmenting on the found path
athos@659
   281
		  Node n=root;
athos@659
   282
		  ResGraphEdge e;
athos@659
   283
		  while (n!=non_root){
athos@671
   284
		    e = bfs_pred[n];
athos@659
   285
		    n = res_graph.tail(e);
athos@659
   286
		    res_graph.augment(e,qty_to_augment);
athos@659
   287
		  }
athos@659
   288
	  
athos@659
   289
		  //We know that non_root had positive excess
athos@671
   290
		  excess_nodes.set(non_root,
athos@671
   291
				   excess_nodes[non_root] - qty_to_augment);
athos@659
   292
		  //But what about root node
athos@659
   293
		  //It might have been positive and so became larger
athos@659
   294
		  if (excess_deficit[root]>0){
athos@671
   295
		    excess_nodes.set(root, 
athos@671
   296
				     excess_nodes[root] + qty_to_augment);
athos@659
   297
		  }
athos@659
   298
		  else{
athos@659
   299
		    //Or negative but not turned into positive
athos@671
   300
		    deficit_nodes.set(root, 
athos@671
   301
				      deficit_nodes[root] - qty_to_augment);
athos@659
   302
		  }
athos@659
   303
athos@659
   304
		  //Update the excess_deficit map
athos@659
   305
		  excess_deficit[non_root] -= qty_to_augment;
athos@659
   306
		  excess_deficit[root] += qty_to_augment;
athos@659
   307
athos@659
   308
		  
athos@659
   309
		}
athos@657
   310
	      }
athos@657
   311
	      //What happens to i?
athos@659
   312
	      //Marci and Zsolt says I shouldn't do such things
athos@659
   313
	      nonabundant_arcs.erase(i++);
athos@671
   314
	      abundant_arcs[*i] = true;
athos@657
   315
	    }
athos@657
   316
	    else
athos@657
   317
	      ++i;
athos@657
   318
	  }
athos@657
   319
	}
athos@657
   320
athos@635
   321
athos@635
   322
	Node s = excess_nodes.top(); 
athos@635
   323
	SupplyDemand max_excess = excess_nodes[s];
athos@635
   324
	Node t = deficit_nodes.top(); 
athos@659
   325
	if (max_excess < deficit_nodes[t]){
athos@659
   326
	  max_excess = deficit_nodes[t];
athos@635
   327
	}
athos@635
   328
athos@635
   329
athos@662
   330
	while(max_excess > (number_of_nodes-1)*delta/number_of_nodes){
athos@659
   331
	  
athos@635
   332
	  
athos@635
   333
	  //s es t valasztasa
athos@659
   334
	  
athos@635
   335
	  //Dijkstra part	
athos@635
   336
	  dijkstra.run(s);
athos@659
   337
	  
athos@635
   338
	  /*We know from theory that t can be reached
athos@635
   339
	  if (!dijkstra.reached(t)){
athos@635
   340
	    //There are no k paths from s to t
athos@635
   341
	    break;
athos@635
   342
	  };
athos@635
   343
	  */
athos@635
   344
	  
athos@635
   345
	  //We have to change the potential
athos@661
   346
	  FOR_EACH_LOC(typename ResGraph::NodeIt, n, res_graph){
athos@635
   347
	    potential[n] += dijkstra.distMap()[n];
athos@635
   348
	  }
athos@635
   349
athos@635
   350
athos@635
   351
	  //Augmenting on the sortest path
athos@635
   352
	  Node n=t;
athos@635
   353
	  ResGraphEdge e;
athos@635
   354
	  while (n!=s){
athos@635
   355
	    e = dijkstra.pred(n);
athos@635
   356
	    n = dijkstra.predNode(n);
athos@635
   357
	    res_graph.augment(e,delta);
athos@635
   358
	    /*
athos@661
   359
	    //Let's update the total cost
athos@635
   360
	    if (res_graph.forward(e))
athos@661
   361
	      total_cost += cost[e];
athos@635
   362
	    else 
athos@661
   363
	      total_cost -= cost[e];	    
athos@635
   364
	    */
athos@635
   365
	  }
athos@659
   366
	  
athos@659
   367
	  //Update the excess_deficit map
athos@659
   368
	  excess_deficit[s] -= delta;
athos@659
   369
	  excess_deficit[t] += delta;
athos@659
   370
	  
athos@635
   371
athos@635
   372
	  //Update the excess_nodes heap
athos@635
   373
	  if (delta >= excess_nodes[s]){
athos@635
   374
	    if (delta > excess_nodes[s])
athos@635
   375
	      deficit_nodes.push(s,delta - excess_nodes[s]);
athos@635
   376
	    excess_nodes.pop();
athos@635
   377
	    
athos@635
   378
	  } 
athos@635
   379
	  else{
athos@671
   380
	    excess_nodes.set(s, excess_nodes[s] - delta);
athos@635
   381
	  }
athos@635
   382
	  //Update the deficit_nodes heap
athos@635
   383
	  if (delta >= deficit_nodes[t]){
athos@635
   384
	    if (delta > deficit_nodes[t])
athos@635
   385
	      excess_nodes.push(t,delta - deficit_nodes[t]);
athos@635
   386
	    deficit_nodes.pop();
athos@635
   387
	    
athos@635
   388
	  } 
athos@635
   389
	  else{
athos@671
   390
	    deficit_nodes.set(t, deficit_nodes[t] - delta);
athos@635
   391
	  }
athos@635
   392
	  //Dijkstra part ends here
athos@659
   393
	  
athos@659
   394
	  //Choose s and t again
athos@659
   395
	  s = excess_nodes.top(); 
athos@659
   396
	  max_excess = excess_nodes[s];
athos@659
   397
	  t = deficit_nodes.top(); 
athos@659
   398
	  if (max_excess < deficit_nodes[t]){
athos@659
   399
	    max_excess = deficit_nodes[t];
athos@659
   400
	  }
athos@659
   401
athos@633
   402
	}
athos@633
   403
athos@633
   404
	/*
athos@635
   405
	 * End of the delta scaling phase 
athos@635
   406
	*/
athos@633
   407
athos@635
   408
	//Whatever this means
athos@635
   409
	delta = delta / 2;
athos@635
   410
athos@635
   411
	/*This is not necessary here
athos@635
   412
	//Update the max_excess
athos@635
   413
	max_excess = 0;
athos@659
   414
	FOR_EACH_LOC(typename Graph::NodeIt, n, graph){
athos@635
   415
	  if (max_excess < excess_deficit[n]){
athos@635
   416
	    max_excess = excess_deficit[n];
athos@610
   417
	  }
athos@610
   418
	}
athos@633
   419
	*/
athos@657
   420
athos@610
   421
	  
athos@635
   422
      }//while(max_excess > 0)
athos@610
   423
      
athos@610
   424
athos@671
   425
      //return i;
athos@610
   426
    }
athos@610
   427
athos@610
   428
athos@610
   429
athos@610
   430
athos@661
   431
    ///This function gives back the total cost of the found paths.
athos@610
   432
    ///Assumes that \c run() has been run and nothing changed since then.
athos@661
   433
    Cost totalCost(){
athos@661
   434
      return total_cost;
athos@610
   435
    }
athos@610
   436
athos@610
   437
    ///Returns a const reference to the EdgeMap \c flow. \pre \ref run() must
athos@610
   438
    ///be called before using this function.
athos@662
   439
    const FlowMap &getFlow() const { return flow;}
athos@610
   440
athos@610
   441
  ///Returns a const reference to the NodeMap \c potential (the dual solution).
athos@610
   442
    /// \pre \ref run() must be called before using this function.
athos@662
   443
    const PotentialMap &getPotential() const { return potential;}
athos@610
   444
athos@610
   445
    ///This function checks, whether the given solution is optimal
athos@610
   446
    ///Running after a \c run() should return with true
athos@610
   447
    ///In this "state of the art" this only check optimality, doesn't bother with feasibility
athos@610
   448
    ///
athos@610
   449
    ///\todo Is this OK here?
athos@610
   450
    bool checkComplementarySlackness(){
athos@661
   451
      Cost mod_pot;
athos@661
   452
      Cost fl_e;
athos@659
   453
      FOR_EACH_LOC(typename Graph::EdgeIt, e, graph){
athos@610
   454
	//C^{\Pi}_{i,j}
athos@661
   455
	mod_pot = cost[e]-potential[graph.head(e)]+potential[graph.tail(e)];
athos@610
   456
	fl_e = flow[e];
athos@610
   457
	//	std::cout << fl_e << std::endl;
athos@610
   458
	if (0<fl_e && fl_e<capacity[e]){
athos@610
   459
	  if (mod_pot != 0)
athos@610
   460
	    return false;
athos@610
   461
	}
athos@610
   462
	else{
athos@610
   463
	  if (mod_pot > 0 && fl_e != 0)
athos@610
   464
	    return false;
athos@610
   465
	  if (mod_pot < 0 && fl_e != capacity[e])
athos@610
   466
	    return false;
athos@610
   467
	}
athos@610
   468
      }
athos@610
   469
      return true;
athos@610
   470
    }
athos@610
   471
    
athos@610
   472
athos@633
   473
  }; //class MinCostFlow
athos@610
   474
athos@610
   475
  ///@}
athos@610
   476
athos@610
   477
} //namespace hugo
athos@610
   478
athos@610
   479
#endif //HUGO_MINCOSTFLOW_H