src/work/athos/mincostflow.h
author athos
Tue, 25 May 2004 17:01:26 +0000
changeset 662 0155001b6f65
parent 661 d306e777117e
child 671 708df4dc6ab6
permissions -rw-r--r--
Almost compiles.
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@659
   216
      //We want to run bfs-es (more) on this graph 'res_ab_graph'
athos@659
   217
      Bfs < ResAbGraph , 
athos@662
   218
	typename ResAbGraph::template NodeMap<bool>, 
athos@662
   219
	typename ResAbGraph::template NodeMap<typename ResAbGraph::Edge>,
athos@659
   220
	NullMap<typename ResAbGraph::Node, int> > 
athos@659
   221
	bfs(res_ab_graph, bfs_reached, bfs_pred, bfs_dist_dummy);
athos@662
   222
      /*This is what Marci wants for a bfs
athos@662
   223
	template <typename Graph, 
athos@662
   224
	    typename ReachedMap=typename Graph::template NodeMap<bool>, 
athos@662
   225
	    typename PredMap
athos@662
   226
	    =typename Graph::template NodeMap<typename Graph::Edge>, 
athos@662
   227
	    typename DistMap=typename Graph::template NodeMap<int> > 
athos@662
   228
	    class Bfs : public BfsIterator<Graph, ReachedMap> {
athos@662
   229
athos@662
   230
       */
athos@610
   231
      
athos@661
   232
      ModCostMap mod_cost(res_graph, cost, potential);
athos@610
   233
athos@661
   234
      Dijkstra<ResGraph, ModCostMap> dijkstra(res_graph, mod_cost);
athos@610
   235
athos@633
   236
athos@635
   237
      while (max_excess > 0){
athos@635
   238
athos@657
   239
	//Reset delta if still too big
athos@657
   240
	if (8*number_of_nodes*max_excess <= delta){
athos@657
   241
	  delta = max_excess;
athos@657
   242
	  
athos@657
   243
	}
athos@657
   244
athos@645
   245
	/*
athos@645
   246
	 * Beginning of the delta scaling phase 
athos@645
   247
	*/
athos@635
   248
	//Merge and stuff
athos@657
   249
	{
athos@657
   250
	  SupplyDemand buf=8*number_of_nodes*delta;
athos@662
   251
	  typename std::list<Edge>::iterator i = nonabundant_arcs.begin();
athos@657
   252
	  while ( i != nonabundant_arcs.end() ){
athos@657
   253
	    if (flow[i]>=buf){
athos@657
   254
	      Node a = abundant_components.find(res_graph.head(i));
athos@657
   255
	      Node b = abundant_components.find(res_graph.tail(i));
athos@657
   256
	      //Merge
athos@657
   257
	      if (a != b){
athos@657
   258
		abundant_components.join(a,b);
athos@659
   259
		//We want to push the smaller
athos@659
   260
		//Which has greater absolut value excess/deficit
athos@659
   261
		Node root=(abs(excess_deficit[a])>abs(excess_deficit[b]))?a:b;
athos@659
   262
		//Which is the other
athos@659
   263
		Node non_root = ( a == root ) ? b : a ;
athos@659
   264
		abundant_components.makeRep(root);
athos@659
   265
		SupplyDemand qty_to_augment = abs(excess_deficit[non_root]); 
athos@659
   266
		//Push the positive value
athos@659
   267
		if (excess_deficit[non_root] < 0)
athos@659
   268
		  swap(root, non_root);
athos@659
   269
		//If the non_root node has excess/deficit at all
athos@659
   270
		if (qty_to_augment>0){
athos@659
   271
		  //Find path and augment
athos@659
   272
		  bfs.run(non_root);
athos@659
   273
		  //root should be reached
athos@659
   274
		  
athos@659
   275
		  //Augmenting on the found path
athos@659
   276
		  Node n=root;
athos@659
   277
		  ResGraphEdge e;
athos@659
   278
		  while (n!=non_root){
athos@659
   279
		    e = bfs_pred(n);
athos@659
   280
		    n = res_graph.tail(e);
athos@659
   281
		    res_graph.augment(e,qty_to_augment);
athos@659
   282
		  }
athos@659
   283
	  
athos@659
   284
		  //We know that non_root had positive excess
athos@659
   285
		  excess_nodes[non_root] -= qty_to_augment;
athos@659
   286
		  //But what about root node
athos@659
   287
		  //It might have been positive and so became larger
athos@659
   288
		  if (excess_deficit[root]>0){
athos@659
   289
		    excess_nodes[root] += qty_to_augment;
athos@659
   290
		  }
athos@659
   291
		  else{
athos@659
   292
		    //Or negative but not turned into positive
athos@659
   293
		    deficit_nodes[root] -= qty_to_augment;
athos@659
   294
		  }
athos@659
   295
athos@659
   296
		  //Update the excess_deficit map
athos@659
   297
		  excess_deficit[non_root] -= qty_to_augment;
athos@659
   298
		  excess_deficit[root] += qty_to_augment;
athos@659
   299
athos@659
   300
		  
athos@659
   301
		}
athos@657
   302
	      }
athos@657
   303
	      //What happens to i?
athos@659
   304
	      //Marci and Zsolt says I shouldn't do such things
athos@659
   305
	      nonabundant_arcs.erase(i++);
athos@659
   306
	      abundant_arcs[i] = true;
athos@657
   307
	    }
athos@657
   308
	    else
athos@657
   309
	      ++i;
athos@657
   310
	  }
athos@657
   311
	}
athos@657
   312
athos@635
   313
athos@635
   314
	Node s = excess_nodes.top(); 
athos@635
   315
	SupplyDemand max_excess = excess_nodes[s];
athos@635
   316
	Node t = deficit_nodes.top(); 
athos@659
   317
	if (max_excess < deficit_nodes[t]){
athos@659
   318
	  max_excess = deficit_nodes[t];
athos@635
   319
	}
athos@635
   320
athos@635
   321
athos@662
   322
	while(max_excess > (number_of_nodes-1)*delta/number_of_nodes){
athos@659
   323
	  
athos@635
   324
	  
athos@635
   325
	  //s es t valasztasa
athos@659
   326
	  
athos@635
   327
	  //Dijkstra part	
athos@635
   328
	  dijkstra.run(s);
athos@659
   329
	  
athos@635
   330
	  /*We know from theory that t can be reached
athos@635
   331
	  if (!dijkstra.reached(t)){
athos@635
   332
	    //There are no k paths from s to t
athos@635
   333
	    break;
athos@635
   334
	  };
athos@635
   335
	  */
athos@635
   336
	  
athos@635
   337
	  //We have to change the potential
athos@661
   338
	  FOR_EACH_LOC(typename ResGraph::NodeIt, n, res_graph){
athos@635
   339
	    potential[n] += dijkstra.distMap()[n];
athos@635
   340
	  }
athos@635
   341
athos@635
   342
athos@635
   343
	  //Augmenting on the sortest path
athos@635
   344
	  Node n=t;
athos@635
   345
	  ResGraphEdge e;
athos@635
   346
	  while (n!=s){
athos@635
   347
	    e = dijkstra.pred(n);
athos@635
   348
	    n = dijkstra.predNode(n);
athos@635
   349
	    res_graph.augment(e,delta);
athos@635
   350
	    /*
athos@661
   351
	    //Let's update the total cost
athos@635
   352
	    if (res_graph.forward(e))
athos@661
   353
	      total_cost += cost[e];
athos@635
   354
	    else 
athos@661
   355
	      total_cost -= cost[e];	    
athos@635
   356
	    */
athos@635
   357
	  }
athos@659
   358
	  
athos@659
   359
	  //Update the excess_deficit map
athos@659
   360
	  excess_deficit[s] -= delta;
athos@659
   361
	  excess_deficit[t] += delta;
athos@659
   362
	  
athos@635
   363
athos@635
   364
	  //Update the excess_nodes heap
athos@635
   365
	  if (delta >= excess_nodes[s]){
athos@635
   366
	    if (delta > excess_nodes[s])
athos@635
   367
	      deficit_nodes.push(s,delta - excess_nodes[s]);
athos@635
   368
	    excess_nodes.pop();
athos@635
   369
	    
athos@635
   370
	  } 
athos@635
   371
	  else{
athos@635
   372
	    excess_nodes[s] -= delta;
athos@635
   373
	  }
athos@635
   374
	  //Update the deficit_nodes heap
athos@635
   375
	  if (delta >= deficit_nodes[t]){
athos@635
   376
	    if (delta > deficit_nodes[t])
athos@635
   377
	      excess_nodes.push(t,delta - deficit_nodes[t]);
athos@635
   378
	    deficit_nodes.pop();
athos@635
   379
	    
athos@635
   380
	  } 
athos@635
   381
	  else{
athos@635
   382
	    deficit_nodes[t] -= delta;
athos@635
   383
	  }
athos@635
   384
	  //Dijkstra part ends here
athos@659
   385
	  
athos@659
   386
	  //Choose s and t again
athos@659
   387
	  s = excess_nodes.top(); 
athos@659
   388
	  max_excess = excess_nodes[s];
athos@659
   389
	  t = deficit_nodes.top(); 
athos@659
   390
	  if (max_excess < deficit_nodes[t]){
athos@659
   391
	    max_excess = deficit_nodes[t];
athos@659
   392
	  }
athos@659
   393
athos@633
   394
	}
athos@633
   395
athos@633
   396
	/*
athos@635
   397
	 * End of the delta scaling phase 
athos@635
   398
	*/
athos@633
   399
athos@635
   400
	//Whatever this means
athos@635
   401
	delta = delta / 2;
athos@635
   402
athos@635
   403
	/*This is not necessary here
athos@635
   404
	//Update the max_excess
athos@635
   405
	max_excess = 0;
athos@659
   406
	FOR_EACH_LOC(typename Graph::NodeIt, n, graph){
athos@635
   407
	  if (max_excess < excess_deficit[n]){
athos@635
   408
	    max_excess = excess_deficit[n];
athos@610
   409
	  }
athos@610
   410
	}
athos@633
   411
	*/
athos@657
   412
athos@610
   413
	  
athos@635
   414
      }//while(max_excess > 0)
athos@610
   415
      
athos@610
   416
athos@610
   417
      return i;
athos@610
   418
    }
athos@610
   419
athos@610
   420
athos@610
   421
athos@610
   422
athos@661
   423
    ///This function gives back the total cost of the found paths.
athos@610
   424
    ///Assumes that \c run() has been run and nothing changed since then.
athos@661
   425
    Cost totalCost(){
athos@661
   426
      return total_cost;
athos@610
   427
    }
athos@610
   428
athos@610
   429
    ///Returns a const reference to the EdgeMap \c flow. \pre \ref run() must
athos@610
   430
    ///be called before using this function.
athos@662
   431
    const FlowMap &getFlow() const { return flow;}
athos@610
   432
athos@610
   433
  ///Returns a const reference to the NodeMap \c potential (the dual solution).
athos@610
   434
    /// \pre \ref run() must be called before using this function.
athos@662
   435
    const PotentialMap &getPotential() const { return potential;}
athos@610
   436
athos@610
   437
    ///This function checks, whether the given solution is optimal
athos@610
   438
    ///Running after a \c run() should return with true
athos@610
   439
    ///In this "state of the art" this only check optimality, doesn't bother with feasibility
athos@610
   440
    ///
athos@610
   441
    ///\todo Is this OK here?
athos@610
   442
    bool checkComplementarySlackness(){
athos@661
   443
      Cost mod_pot;
athos@661
   444
      Cost fl_e;
athos@659
   445
      FOR_EACH_LOC(typename Graph::EdgeIt, e, graph){
athos@610
   446
	//C^{\Pi}_{i,j}
athos@661
   447
	mod_pot = cost[e]-potential[graph.head(e)]+potential[graph.tail(e)];
athos@610
   448
	fl_e = flow[e];
athos@610
   449
	//	std::cout << fl_e << std::endl;
athos@610
   450
	if (0<fl_e && fl_e<capacity[e]){
athos@610
   451
	  if (mod_pot != 0)
athos@610
   452
	    return false;
athos@610
   453
	}
athos@610
   454
	else{
athos@610
   455
	  if (mod_pot > 0 && fl_e != 0)
athos@610
   456
	    return false;
athos@610
   457
	  if (mod_pot < 0 && fl_e != capacity[e])
athos@610
   458
	    return false;
athos@610
   459
	}
athos@610
   460
      }
athos@610
   461
      return true;
athos@610
   462
    }
athos@610
   463
    
athos@610
   464
athos@633
   465
  }; //class MinCostFlow
athos@610
   466
athos@610
   467
  ///@}
athos@610
   468
athos@610
   469
} //namespace hugo
athos@610
   470
athos@610
   471
#endif //HUGO_MINCOSTFLOW_H