lemon/cycle_canceling.h
author kpeter
Thu, 13 Nov 2008 16:17:50 +0000
changeset 2630 d239741cfd44
parent 2623 90defb96ee61
permissions -rw-r--r--
Various improvements in NetworkSimplex.

- Faster variant of "Altering Candidate List" pivot rule using make_heap
instead of partial_sort.
- Doc improvements.
- Removing unecessary inline keywords.
     1 /* -*- C++ -*-
     2  *
     3  * This file is a part of LEMON, a generic C++ optimization library
     4  *
     5  * Copyright (C) 2003-2008
     6  * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
     7  * (Egervary Research Group on Combinatorial Optimization, EGRES).
     8  *
     9  * Permission to use, modify and distribute this software is granted
    10  * provided that this copyright notice appears in all copies. For
    11  * precise terms see the accompanying LICENSE file.
    12  *
    13  * This software is provided "AS IS" with no warranty of any kind,
    14  * express or implied, and with no claim as to its suitability for any
    15  * purpose.
    16  *
    17  */
    18 
    19 #ifndef LEMON_CYCLE_CANCELING_H
    20 #define LEMON_CYCLE_CANCELING_H
    21 
    22 /// \ingroup min_cost_flow
    23 ///
    24 /// \file
    25 /// \brief Cycle-canceling algorithm for finding a minimum cost flow.
    26 
    27 #include <vector>
    28 #include <lemon/graph_adaptor.h>
    29 #include <lemon/path.h>
    30 
    31 #include <lemon/circulation.h>
    32 #include <lemon/bellman_ford.h>
    33 #include <lemon/min_mean_cycle.h>
    34 
    35 namespace lemon {
    36 
    37   /// \addtogroup min_cost_flow
    38   /// @{
    39 
    40   /// \brief Implementation of a cycle-canceling algorithm for
    41   /// finding a minimum cost flow.
    42   ///
    43   /// \ref CycleCanceling implements a cycle-canceling algorithm for
    44   /// finding a minimum cost flow.
    45   ///
    46   /// \tparam Graph The directed graph type the algorithm runs on.
    47   /// \tparam LowerMap The type of the lower bound map.
    48   /// \tparam CapacityMap The type of the capacity (upper bound) map.
    49   /// \tparam CostMap The type of the cost (length) map.
    50   /// \tparam SupplyMap The type of the supply map.
    51   ///
    52   /// \warning
    53   /// - Edge capacities and costs should be \e non-negative \e integers.
    54   /// - Supply values should be \e signed \e integers.
    55   /// - The value types of the maps should be convertible to each other.
    56   /// - \c CostMap::Value must be signed type.
    57   ///
    58   /// \note By default the \ref BellmanFord "Bellman-Ford" algorithm is
    59   /// used for negative cycle detection with limited iteration number.
    60   /// However \ref CycleCanceling also provides the "Minimum Mean
    61   /// Cycle-Canceling" algorithm, which is \e strongly \e polynomial,
    62   /// but rather slower in practice.
    63   /// To use this version of the algorithm, call \ref run() with \c true
    64   /// parameter.
    65   ///
    66   /// \author Peter Kovacs
    67   template < typename Graph,
    68              typename LowerMap = typename Graph::template EdgeMap<int>,
    69              typename CapacityMap = typename Graph::template EdgeMap<int>,
    70              typename CostMap = typename Graph::template EdgeMap<int>,
    71              typename SupplyMap = typename Graph::template NodeMap<int> >
    72   class CycleCanceling
    73   {
    74     GRAPH_TYPEDEFS(typename Graph);
    75 
    76     typedef typename CapacityMap::Value Capacity;
    77     typedef typename CostMap::Value Cost;
    78     typedef typename SupplyMap::Value Supply;
    79     typedef typename Graph::template EdgeMap<Capacity> CapacityEdgeMap;
    80     typedef typename Graph::template NodeMap<Supply> SupplyNodeMap;
    81 
    82     typedef ResGraphAdaptor< const Graph, Capacity,
    83                              CapacityEdgeMap, CapacityEdgeMap > ResGraph;
    84     typedef typename ResGraph::Node ResNode;
    85     typedef typename ResGraph::NodeIt ResNodeIt;
    86     typedef typename ResGraph::Edge ResEdge;
    87     typedef typename ResGraph::EdgeIt ResEdgeIt;
    88 
    89   public:
    90 
    91     /// The type of the flow map.
    92     typedef typename Graph::template EdgeMap<Capacity> FlowMap;
    93     /// The type of the potential map.
    94     typedef typename Graph::template NodeMap<Cost> PotentialMap;
    95 
    96   private:
    97 
    98     /// \brief Map adaptor class for handling residual edge costs.
    99     ///
   100     /// Map adaptor class for handling residual edge costs.
   101     class ResidualCostMap : public MapBase<ResEdge, Cost>
   102     {
   103     private:
   104 
   105       const CostMap &_cost_map;
   106 
   107     public:
   108 
   109       ///\e
   110       ResidualCostMap(const CostMap &cost_map) : _cost_map(cost_map) {}
   111 
   112       ///\e
   113       Cost operator[](const ResEdge &e) const {
   114         return ResGraph::forward(e) ? _cost_map[e] : -_cost_map[e];
   115       }
   116 
   117     }; //class ResidualCostMap
   118 
   119   private:
   120 
   121     // The maximum number of iterations for the first execution of the
   122     // Bellman-Ford algorithm. It should be at least 2.
   123     static const int BF_FIRST_LIMIT  = 2;
   124     // The iteration limit for the Bellman-Ford algorithm is multiplied
   125     // by BF_LIMIT_FACTOR/100 in every round.
   126     static const int BF_LIMIT_FACTOR = 150;
   127 
   128   private:
   129 
   130     // The directed graph the algorithm runs on
   131     const Graph &_graph;
   132     // The original lower bound map
   133     const LowerMap *_lower;
   134     // The modified capacity map
   135     CapacityEdgeMap _capacity;
   136     // The original cost map
   137     const CostMap &_cost;
   138     // The modified supply map
   139     SupplyNodeMap _supply;
   140     bool _valid_supply;
   141 
   142     // Edge map of the current flow
   143     FlowMap *_flow;
   144     bool _local_flow;
   145     // Node map of the current potentials
   146     PotentialMap *_potential;
   147     bool _local_potential;
   148 
   149     // The residual graph
   150     ResGraph *_res_graph;
   151     // The residual cost map
   152     ResidualCostMap _res_cost;
   153 
   154   public:
   155 
   156     /// \brief General constructor (with lower bounds).
   157     ///
   158     /// General constructor (with lower bounds).
   159     ///
   160     /// \param graph The directed graph the algorithm runs on.
   161     /// \param lower The lower bounds of the edges.
   162     /// \param capacity The capacities (upper bounds) of the edges.
   163     /// \param cost The cost (length) values of the edges.
   164     /// \param supply The supply values of the nodes (signed).
   165     CycleCanceling( const Graph &graph,
   166                     const LowerMap &lower,
   167                     const CapacityMap &capacity,
   168                     const CostMap &cost,
   169                     const SupplyMap &supply ) :
   170       _graph(graph), _lower(&lower), _capacity(capacity), _cost(cost),
   171       _supply(supply), _flow(NULL), _local_flow(false),
   172       _potential(NULL), _local_potential(false), _res_graph(NULL),
   173       _res_cost(_cost)
   174     {
   175       // Check the sum of supply values
   176       Supply sum = 0;
   177       for (NodeIt n(_graph); n != INVALID; ++n) sum += _supply[n];
   178       _valid_supply = sum == 0;
   179 
   180       // Remove non-zero lower bounds
   181       for (EdgeIt e(_graph); e != INVALID; ++e) {
   182         if (lower[e] != 0) {
   183           _capacity[e] -= lower[e];
   184           _supply[_graph.source(e)] -= lower[e];
   185           _supply[_graph.target(e)] += lower[e];
   186         }
   187       }
   188     }
   189 
   190     /// \brief General constructor (without lower bounds).
   191     ///
   192     /// General constructor (without lower bounds).
   193     ///
   194     /// \param graph The directed graph the algorithm runs on.
   195     /// \param capacity The capacities (upper bounds) of the edges.
   196     /// \param cost The cost (length) values of the edges.
   197     /// \param supply The supply values of the nodes (signed).
   198     CycleCanceling( const Graph &graph,
   199                     const CapacityMap &capacity,
   200                     const CostMap &cost,
   201                     const SupplyMap &supply ) :
   202       _graph(graph), _lower(NULL), _capacity(capacity), _cost(cost),
   203       _supply(supply), _flow(NULL), _local_flow(false),
   204       _potential(NULL), _local_potential(false), _res_graph(NULL),
   205       _res_cost(_cost)
   206     {
   207       // Check the sum of supply values
   208       Supply sum = 0;
   209       for (NodeIt n(_graph); n != INVALID; ++n) sum += _supply[n];
   210       _valid_supply = sum == 0;
   211     }
   212 
   213     /// \brief Simple constructor (with lower bounds).
   214     ///
   215     /// Simple constructor (with lower bounds).
   216     ///
   217     /// \param graph The directed graph the algorithm runs on.
   218     /// \param lower The lower bounds of the edges.
   219     /// \param capacity The capacities (upper bounds) of the edges.
   220     /// \param cost The cost (length) values of the edges.
   221     /// \param s The source node.
   222     /// \param t The target node.
   223     /// \param flow_value The required amount of flow from node \c s
   224     /// to node \c t (i.e. the supply of \c s and the demand of \c t).
   225     CycleCanceling( const Graph &graph,
   226                     const LowerMap &lower,
   227                     const CapacityMap &capacity,
   228                     const CostMap &cost,
   229                     Node s, Node t,
   230                     Supply flow_value ) :
   231       _graph(graph), _lower(&lower), _capacity(capacity), _cost(cost),
   232       _supply(graph, 0), _flow(NULL), _local_flow(false),
   233       _potential(NULL), _local_potential(false), _res_graph(NULL),
   234       _res_cost(_cost)
   235     {
   236       // Remove non-zero lower bounds
   237       _supply[s] =  flow_value;
   238       _supply[t] = -flow_value;
   239       for (EdgeIt e(_graph); e != INVALID; ++e) {
   240         if (lower[e] != 0) {
   241           _capacity[e] -= lower[e];
   242           _supply[_graph.source(e)] -= lower[e];
   243           _supply[_graph.target(e)] += lower[e];
   244         }
   245       }
   246       _valid_supply = true;
   247     }
   248 
   249     /// \brief Simple constructor (without lower bounds).
   250     ///
   251     /// Simple constructor (without lower bounds).
   252     ///
   253     /// \param graph The directed graph the algorithm runs on.
   254     /// \param capacity The capacities (upper bounds) of the edges.
   255     /// \param cost The cost (length) values of the edges.
   256     /// \param s The source node.
   257     /// \param t The target node.
   258     /// \param flow_value The required amount of flow from node \c s
   259     /// to node \c t (i.e. the supply of \c s and the demand of \c t).
   260     CycleCanceling( const Graph &graph,
   261                     const CapacityMap &capacity,
   262                     const CostMap &cost,
   263                     Node s, Node t,
   264                     Supply flow_value ) :
   265       _graph(graph), _lower(NULL), _capacity(capacity), _cost(cost),
   266       _supply(graph, 0), _flow(NULL), _local_flow(false),
   267       _potential(NULL), _local_potential(false), _res_graph(NULL),
   268       _res_cost(_cost)
   269     {
   270       _supply[s] =  flow_value;
   271       _supply[t] = -flow_value;
   272       _valid_supply = true;
   273     }
   274 
   275     /// Destructor.
   276     ~CycleCanceling() {
   277       if (_local_flow) delete _flow;
   278       if (_local_potential) delete _potential;
   279       delete _res_graph;
   280     }
   281 
   282     /// \brief Set the flow map.
   283     ///
   284     /// Set the flow map.
   285     ///
   286     /// \return \c (*this)
   287     CycleCanceling& flowMap(FlowMap &map) {
   288       if (_local_flow) {
   289         delete _flow;
   290         _local_flow = false;
   291       }
   292       _flow = &map;
   293       return *this;
   294     }
   295 
   296     /// \brief Set the potential map.
   297     ///
   298     /// Set the potential map.
   299     ///
   300     /// \return \c (*this)
   301     CycleCanceling& potentialMap(PotentialMap &map) {
   302       if (_local_potential) {
   303         delete _potential;
   304         _local_potential = false;
   305       }
   306       _potential = &map;
   307       return *this;
   308     }
   309 
   310     /// \name Execution control
   311 
   312     /// @{
   313 
   314     /// \brief Run the algorithm.
   315     ///
   316     /// Run the algorithm.
   317     ///
   318     /// \param min_mean_cc Set this parameter to \c true to run the
   319     /// "Minimum Mean Cycle-Canceling" algorithm, which is strongly
   320     /// polynomial, but rather slower in practice.
   321     ///
   322     /// \return \c true if a feasible flow can be found.
   323     bool run(bool min_mean_cc = false) {
   324       return init() && start(min_mean_cc);
   325     }
   326 
   327     /// @}
   328 
   329     /// \name Query Functions
   330     /// The result of the algorithm can be obtained using these
   331     /// functions.\n
   332     /// \ref lemon::CycleCanceling::run() "run()" must be called before
   333     /// using them.
   334 
   335     /// @{
   336 
   337     /// \brief Return a const reference to the edge map storing the
   338     /// found flow.
   339     ///
   340     /// Return a const reference to the edge map storing the found flow.
   341     ///
   342     /// \pre \ref run() must be called before using this function.
   343     const FlowMap& flowMap() const {
   344       return *_flow;
   345     }
   346 
   347     /// \brief Return a const reference to the node map storing the
   348     /// found potentials (the dual solution).
   349     ///
   350     /// Return a const reference to the node map storing the found
   351     /// potentials (the dual solution).
   352     ///
   353     /// \pre \ref run() must be called before using this function.
   354     const PotentialMap& potentialMap() const {
   355       return *_potential;
   356     }
   357 
   358     /// \brief Return the flow on the given edge.
   359     ///
   360     /// Return the flow on the given edge.
   361     ///
   362     /// \pre \ref run() must be called before using this function.
   363     Capacity flow(const Edge& edge) const {
   364       return (*_flow)[edge];
   365     }
   366 
   367     /// \brief Return the potential of the given node.
   368     ///
   369     /// Return the potential of the given node.
   370     ///
   371     /// \pre \ref run() must be called before using this function.
   372     Cost potential(const Node& node) const {
   373       return (*_potential)[node];
   374     }
   375 
   376     /// \brief Return the total cost of the found flow.
   377     ///
   378     /// Return the total cost of the found flow. The complexity of the
   379     /// function is \f$ O(e) \f$.
   380     ///
   381     /// \pre \ref run() must be called before using this function.
   382     Cost totalCost() const {
   383       Cost c = 0;
   384       for (EdgeIt e(_graph); e != INVALID; ++e)
   385         c += (*_flow)[e] * _cost[e];
   386       return c;
   387     }
   388 
   389     /// @}
   390 
   391   private:
   392 
   393     /// Initialize the algorithm.
   394     bool init() {
   395       if (!_valid_supply) return false;
   396 
   397       // Initializing flow and potential maps
   398       if (!_flow) {
   399         _flow = new FlowMap(_graph);
   400         _local_flow = true;
   401       }
   402       if (!_potential) {
   403         _potential = new PotentialMap(_graph);
   404         _local_potential = true;
   405       }
   406 
   407       _res_graph = new ResGraph(_graph, _capacity, *_flow);
   408 
   409       // Finding a feasible flow using Circulation
   410       Circulation< Graph, ConstMap<Edge, Capacity>, CapacityEdgeMap,
   411                    SupplyMap >
   412         circulation( _graph, constMap<Edge>(Capacity(0)), _capacity,
   413                      _supply );
   414       return circulation.flowMap(*_flow).run();
   415     }
   416 
   417     bool start(bool min_mean_cc) {
   418       if (min_mean_cc)
   419         startMinMean();
   420       else
   421         start();
   422 
   423       // Handling non-zero lower bounds
   424       if (_lower) {
   425         for (EdgeIt e(_graph); e != INVALID; ++e)
   426           (*_flow)[e] += (*_lower)[e];
   427       }
   428       return true;
   429     }
   430 
   431     /// \brief Execute the algorithm using \ref BellmanFord.
   432     ///
   433     /// Execute the algorithm using the \ref BellmanFord
   434     /// "Bellman-Ford" algorithm for negative cycle detection with
   435     /// successively larger limit for the number of iterations.
   436     void start() {
   437       typename BellmanFord<ResGraph, ResidualCostMap>::PredMap pred(*_res_graph);
   438       typename ResGraph::template NodeMap<int> visited(*_res_graph);
   439       std::vector<ResEdge> cycle;
   440       int node_num = countNodes(_graph);
   441 
   442       int length_bound = BF_FIRST_LIMIT;
   443       bool optimal = false;
   444       while (!optimal) {
   445         BellmanFord<ResGraph, ResidualCostMap> bf(*_res_graph, _res_cost);
   446         bf.predMap(pred);
   447         bf.init(0);
   448         int iter_num = 0;
   449         bool cycle_found = false;
   450         while (!cycle_found) {
   451           int curr_iter_num = iter_num + length_bound <= node_num ?
   452                               length_bound : node_num - iter_num;
   453           iter_num += curr_iter_num;
   454           int real_iter_num = curr_iter_num;
   455           for (int i = 0; i < curr_iter_num; ++i) {
   456             if (bf.processNextWeakRound()) {
   457               real_iter_num = i;
   458               break;
   459             }
   460           }
   461           if (real_iter_num < curr_iter_num) {
   462             // Optimal flow is found
   463             optimal = true;
   464             // Setting node potentials
   465             for (NodeIt n(_graph); n != INVALID; ++n)
   466               (*_potential)[n] = bf.dist(n);
   467             break;
   468           } else {
   469             // Searching for node disjoint negative cycles
   470             for (ResNodeIt n(*_res_graph); n != INVALID; ++n)
   471               visited[n] = 0;
   472             int id = 0;
   473             for (ResNodeIt n(*_res_graph); n != INVALID; ++n) {
   474               if (visited[n] > 0) continue;
   475               visited[n] = ++id;
   476               ResNode u = pred[n] == INVALID ?
   477                           INVALID : _res_graph->source(pred[n]);
   478               while (u != INVALID && visited[u] == 0) {
   479                 visited[u] = id;
   480                 u = pred[u] == INVALID ?
   481                     INVALID : _res_graph->source(pred[u]);
   482               }
   483               if (u != INVALID && visited[u] == id) {
   484                 // Finding the negative cycle
   485                 cycle_found = true;
   486                 cycle.clear();
   487                 ResEdge e = pred[u];
   488                 cycle.push_back(e);
   489                 Capacity d = _res_graph->rescap(e);
   490                 while (_res_graph->source(e) != u) {
   491                   cycle.push_back(e = pred[_res_graph->source(e)]);
   492                   if (_res_graph->rescap(e) < d)
   493                     d = _res_graph->rescap(e);
   494                 }
   495 
   496                 // Augmenting along the cycle
   497                 for (int i = 0; i < int(cycle.size()); ++i)
   498                   _res_graph->augment(cycle[i], d);
   499               }
   500             }
   501           }
   502 
   503           if (!cycle_found)
   504             length_bound = length_bound * BF_LIMIT_FACTOR / 100;
   505         }
   506       }
   507     }
   508 
   509     /// \brief Execute the algorithm using \ref MinMeanCycle.
   510     ///
   511     /// Execute the algorithm using \ref MinMeanCycle for negative
   512     /// cycle detection.
   513     void startMinMean() {
   514       typedef Path<ResGraph> ResPath;
   515       MinMeanCycle<ResGraph, ResidualCostMap> mmc(*_res_graph, _res_cost);
   516       ResPath cycle;
   517 
   518       mmc.cyclePath(cycle).init();
   519       if (mmc.findMinMean()) {
   520         while (mmc.cycleLength() < 0) {
   521           // Finding the cycle
   522           mmc.findCycle();
   523 
   524           // Finding the largest flow amount that can be augmented
   525           // along the cycle
   526           Capacity delta = 0;
   527           for (typename ResPath::EdgeIt e(cycle); e != INVALID; ++e) {
   528             if (delta == 0 || _res_graph->rescap(e) < delta)
   529               delta = _res_graph->rescap(e);
   530           }
   531 
   532           // Augmenting along the cycle
   533           for (typename ResPath::EdgeIt e(cycle); e != INVALID; ++e)
   534             _res_graph->augment(e, delta);
   535 
   536           // Finding the minimum cycle mean for the modified residual
   537           // graph
   538           mmc.reset();
   539           if (!mmc.findMinMean()) break;
   540         }
   541       }
   542 
   543       // Computing node potentials
   544       BellmanFord<ResGraph, ResidualCostMap> bf(*_res_graph, _res_cost);
   545       bf.init(0); bf.start();
   546       for (NodeIt n(_graph); n != INVALID; ++n)
   547         (*_potential)[n] = bf.dist(n);
   548     }
   549 
   550   }; //class CycleCanceling
   551 
   552   ///@}
   553 
   554 } //namespace lemon
   555 
   556 #endif //LEMON_CYCLE_CANCELING_H