lemon/circulation.h
author Peter Kovacs <kpeter@inf.elte.hu>
Fri, 13 Nov 2009 18:10:06 +0100
changeset 833 e20173729589
parent 762 ece80147fb08
child 891 75e6020b19b1
permissions -rw-r--r--
Small doc fixes in several files (#331)
alpar@414
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
alpar@414
     2
 *
alpar@414
     3
 * This file is a part of LEMON, a generic C++ optimization library.
alpar@414
     4
 *
alpar@463
     5
 * Copyright (C) 2003-2009
alpar@414
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
alpar@414
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
alpar@414
     8
 *
alpar@414
     9
 * Permission to use, modify and distribute this software is granted
alpar@414
    10
 * provided that this copyright notice appears in all copies. For
alpar@414
    11
 * precise terms see the accompanying LICENSE file.
alpar@414
    12
 *
alpar@414
    13
 * This software is provided "AS IS" with no warranty of any kind,
alpar@414
    14
 * express or implied, and with no claim as to its suitability for any
alpar@414
    15
 * purpose.
alpar@414
    16
 *
alpar@414
    17
 */
alpar@414
    18
alpar@414
    19
#ifndef LEMON_CIRCULATION_H
alpar@414
    20
#define LEMON_CIRCULATION_H
alpar@414
    21
alpar@414
    22
#include <lemon/tolerance.h>
alpar@414
    23
#include <lemon/elevator.h>
kpeter@669
    24
#include <limits>
alpar@414
    25
alpar@414
    26
///\ingroup max_flow
alpar@414
    27
///\file
kpeter@417
    28
///\brief Push-relabel algorithm for finding a feasible circulation.
alpar@414
    29
///
alpar@414
    30
namespace lemon {
alpar@414
    31
alpar@414
    32
  /// \brief Default traits class of Circulation class.
alpar@414
    33
  ///
alpar@414
    34
  /// Default traits class of Circulation class.
kpeter@657
    35
  ///
kpeter@657
    36
  /// \tparam GR Type of the digraph the algorithm runs on.
kpeter@657
    37
  /// \tparam LM The type of the lower bound map.
kpeter@657
    38
  /// \tparam UM The type of the upper bound (capacity) map.
kpeter@657
    39
  /// \tparam SM The type of the supply map.
kpeter@525
    40
  template <typename GR, typename LM,
kpeter@657
    41
            typename UM, typename SM>
alpar@414
    42
  struct CirculationDefaultTraits {
alpar@414
    43
kpeter@417
    44
    /// \brief The type of the digraph the algorithm runs on.
kpeter@525
    45
    typedef GR Digraph;
alpar@414
    46
kpeter@657
    47
    /// \brief The type of the lower bound map.
alpar@414
    48
    ///
kpeter@657
    49
    /// The type of the map that stores the lower bounds on the arcs.
kpeter@657
    50
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
kpeter@657
    51
    typedef LM LowerMap;
alpar@414
    52
kpeter@657
    53
    /// \brief The type of the upper bound (capacity) map.
alpar@414
    54
    ///
kpeter@657
    55
    /// The type of the map that stores the upper bounds (capacities)
kpeter@657
    56
    /// on the arcs.
kpeter@657
    57
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
kpeter@657
    58
    typedef UM UpperMap;
alpar@414
    59
kpeter@657
    60
    /// \brief The type of supply map.
alpar@414
    61
    ///
kpeter@657
    62
    /// The type of the map that stores the signed supply values of the 
kpeter@657
    63
    /// nodes. 
kpeter@657
    64
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
kpeter@657
    65
    typedef SM SupplyMap;
alpar@414
    66
kpeter@688
    67
    /// \brief The type of the flow and supply values.
kpeter@688
    68
    typedef typename SupplyMap::Value Value;
alpar@414
    69
kpeter@417
    70
    /// \brief The type of the map that stores the flow values.
alpar@414
    71
    ///
kpeter@417
    72
    /// The type of the map that stores the flow values.
kpeter@657
    73
    /// It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap"
kpeter@657
    74
    /// concept.
kpeter@760
    75
#ifdef DOXYGEN
kpeter@760
    76
    typedef GR::ArcMap<Value> FlowMap;
kpeter@760
    77
#else
kpeter@688
    78
    typedef typename Digraph::template ArcMap<Value> FlowMap;
kpeter@760
    79
#endif
alpar@414
    80
alpar@414
    81
    /// \brief Instantiates a FlowMap.
alpar@414
    82
    ///
alpar@414
    83
    /// This function instantiates a \ref FlowMap.
kpeter@657
    84
    /// \param digraph The digraph for which we would like to define
alpar@414
    85
    /// the flow map.
alpar@414
    86
    static FlowMap* createFlowMap(const Digraph& digraph) {
alpar@414
    87
      return new FlowMap(digraph);
alpar@414
    88
    }
alpar@414
    89
kpeter@417
    90
    /// \brief The elevator type used by the algorithm.
alpar@414
    91
    ///
kpeter@417
    92
    /// The elevator type used by the algorithm.
alpar@414
    93
    ///
kpeter@760
    94
    /// \sa Elevator, LinkedElevator
kpeter@760
    95
#ifdef DOXYGEN
kpeter@760
    96
    typedef lemon::Elevator<GR, GR::Node> Elevator;
kpeter@760
    97
#else
alpar@414
    98
    typedef lemon::Elevator<Digraph, typename Digraph::Node> Elevator;
kpeter@760
    99
#endif
alpar@414
   100
alpar@414
   101
    /// \brief Instantiates an Elevator.
alpar@414
   102
    ///
kpeter@417
   103
    /// This function instantiates an \ref Elevator.
kpeter@657
   104
    /// \param digraph The digraph for which we would like to define
alpar@414
   105
    /// the elevator.
alpar@414
   106
    /// \param max_level The maximum level of the elevator.
alpar@414
   107
    static Elevator* createElevator(const Digraph& digraph, int max_level) {
alpar@414
   108
      return new Elevator(digraph, max_level);
alpar@414
   109
    }
alpar@414
   110
alpar@414
   111
    /// \brief The tolerance used by the algorithm
alpar@414
   112
    ///
alpar@414
   113
    /// The tolerance used by the algorithm to handle inexact computation.
kpeter@688
   114
    typedef lemon::Tolerance<Value> Tolerance;
alpar@414
   115
alpar@414
   116
  };
alpar@414
   117
kpeter@417
   118
  /**
kpeter@417
   119
     \brief Push-relabel algorithm for the network circulation problem.
alpar@414
   120
alpar@414
   121
     \ingroup max_flow
kpeter@657
   122
     This class implements a push-relabel algorithm for the \e network
kpeter@657
   123
     \e circulation problem.
kpeter@417
   124
     It is to find a feasible circulation when lower and upper bounds
kpeter@657
   125
     are given for the flow values on the arcs and lower bounds are
kpeter@657
   126
     given for the difference between the outgoing and incoming flow
kpeter@657
   127
     at the nodes.
kpeter@417
   128
alpar@414
   129
     The exact formulation of this problem is the following.
kpeter@669
   130
     Let \f$G=(V,A)\f$ be a digraph, \f$lower: A\rightarrow\mathbf{R}\f$
kpeter@669
   131
     \f$upper: A\rightarrow\mathbf{R}\cup\{\infty\}\f$ denote the lower and
kpeter@669
   132
     upper bounds on the arcs, for which \f$lower(uv) \leq upper(uv)\f$
kpeter@657
   133
     holds for all \f$uv\in A\f$, and \f$sup: V\rightarrow\mathbf{R}\f$
kpeter@657
   134
     denotes the signed supply values of the nodes.
kpeter@657
   135
     If \f$sup(u)>0\f$, then \f$u\f$ is a supply node with \f$sup(u)\f$
kpeter@657
   136
     supply, if \f$sup(u)<0\f$, then \f$u\f$ is a demand node with
kpeter@657
   137
     \f$-sup(u)\f$ demand.
kpeter@669
   138
     A feasible circulation is an \f$f: A\rightarrow\mathbf{R}\f$
kpeter@657
   139
     solution of the following problem.
kpeter@417
   140
kpeter@657
   141
     \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu)
kpeter@657
   142
     \geq sup(u) \quad \forall u\in V, \f]
kpeter@657
   143
     \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A. \f]
kpeter@657
   144
     
kpeter@657
   145
     The sum of the supply values, i.e. \f$\sum_{u\in V} sup(u)\f$ must be
kpeter@657
   146
     zero or negative in order to have a feasible solution (since the sum
kpeter@657
   147
     of the expressions on the left-hand side of the inequalities is zero).
kpeter@657
   148
     It means that the total demand must be greater or equal to the total
kpeter@657
   149
     supply and all the supplies have to be carried out from the supply nodes,
kpeter@657
   150
     but there could be demands that are not satisfied.
kpeter@657
   151
     If \f$\sum_{u\in V} sup(u)\f$ is zero, then all the supply/demand
kpeter@657
   152
     constraints have to be satisfied with equality, i.e. all demands
kpeter@657
   153
     have to be satisfied and all supplies have to be used.
kpeter@657
   154
     
kpeter@657
   155
     If you need the opposite inequalities in the supply/demand constraints
kpeter@657
   156
     (i.e. the total demand is less than the total supply and all the demands
kpeter@657
   157
     have to be satisfied while there could be supplies that are not used),
kpeter@657
   158
     then you could easily transform the problem to the above form by reversing
kpeter@657
   159
     the direction of the arcs and taking the negative of the supply values
kpeter@657
   160
     (e.g. using \ref ReverseDigraph and \ref NegMap adaptors).
kpeter@657
   161
kpeter@669
   162
     This algorithm either calculates a feasible circulation, or provides
kpeter@669
   163
     a \ref barrier() "barrier", which prooves that a feasible soultion
kpeter@669
   164
     cannot exist.
kpeter@669
   165
kpeter@657
   166
     Note that this algorithm also provides a feasible solution for the
kpeter@657
   167
     \ref min_cost_flow "minimum cost flow problem".
kpeter@417
   168
kpeter@525
   169
     \tparam GR The type of the digraph the algorithm runs on.
kpeter@657
   170
     \tparam LM The type of the lower bound map. The default
kpeter@525
   171
     map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
kpeter@657
   172
     \tparam UM The type of the upper bound (capacity) map.
kpeter@657
   173
     The default map type is \c LM.
kpeter@657
   174
     \tparam SM The type of the supply map. The default map type is
kpeter@525
   175
     \ref concepts::Digraph::NodeMap "GR::NodeMap<UM::Value>".
alpar@414
   176
  */
kpeter@417
   177
#ifdef DOXYGEN
kpeter@525
   178
template< typename GR,
kpeter@525
   179
          typename LM,
kpeter@525
   180
          typename UM,
kpeter@657
   181
          typename SM,
kpeter@525
   182
          typename TR >
kpeter@417
   183
#else
kpeter@525
   184
template< typename GR,
kpeter@525
   185
          typename LM = typename GR::template ArcMap<int>,
kpeter@525
   186
          typename UM = LM,
kpeter@657
   187
          typename SM = typename GR::template NodeMap<typename UM::Value>,
kpeter@657
   188
          typename TR = CirculationDefaultTraits<GR, LM, UM, SM> >
kpeter@417
   189
#endif
alpar@414
   190
  class Circulation {
kpeter@417
   191
  public:
alpar@414
   192
kpeter@417
   193
    ///The \ref CirculationDefaultTraits "traits class" of the algorithm.
kpeter@525
   194
    typedef TR Traits;
kpeter@417
   195
    ///The type of the digraph the algorithm runs on.
alpar@414
   196
    typedef typename Traits::Digraph Digraph;
kpeter@688
   197
    ///The type of the flow and supply values.
kpeter@688
   198
    typedef typename Traits::Value Value;
alpar@414
   199
kpeter@657
   200
    ///The type of the lower bound map.
kpeter@657
   201
    typedef typename Traits::LowerMap LowerMap;
kpeter@657
   202
    ///The type of the upper bound (capacity) map.
kpeter@657
   203
    typedef typename Traits::UpperMap UpperMap;
kpeter@657
   204
    ///The type of the supply map.
kpeter@657
   205
    typedef typename Traits::SupplyMap SupplyMap;
kpeter@417
   206
    ///The type of the flow map.
alpar@414
   207
    typedef typename Traits::FlowMap FlowMap;
kpeter@417
   208
kpeter@417
   209
    ///The type of the elevator.
alpar@414
   210
    typedef typename Traits::Elevator Elevator;
kpeter@417
   211
    ///The type of the tolerance.
alpar@414
   212
    typedef typename Traits::Tolerance Tolerance;
alpar@414
   213
kpeter@417
   214
  private:
kpeter@417
   215
kpeter@417
   216
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
alpar@414
   217
alpar@414
   218
    const Digraph &_g;
alpar@414
   219
    int _node_num;
alpar@414
   220
kpeter@657
   221
    const LowerMap *_lo;
kpeter@657
   222
    const UpperMap *_up;
kpeter@657
   223
    const SupplyMap *_supply;
alpar@414
   224
alpar@414
   225
    FlowMap *_flow;
alpar@414
   226
    bool _local_flow;
alpar@414
   227
alpar@414
   228
    Elevator* _level;
alpar@414
   229
    bool _local_level;
alpar@414
   230
kpeter@688
   231
    typedef typename Digraph::template NodeMap<Value> ExcessMap;
alpar@414
   232
    ExcessMap* _excess;
alpar@414
   233
alpar@414
   234
    Tolerance _tol;
alpar@414
   235
    int _el;
alpar@414
   236
alpar@414
   237
  public:
alpar@414
   238
alpar@414
   239
    typedef Circulation Create;
alpar@414
   240
kpeter@417
   241
    ///\name Named Template Parameters
alpar@414
   242
alpar@414
   243
    ///@{
alpar@414
   244
kpeter@606
   245
    template <typename T>
alpar@416
   246
    struct SetFlowMapTraits : public Traits {
kpeter@606
   247
      typedef T FlowMap;
alpar@414
   248
      static FlowMap *createFlowMap(const Digraph&) {
alpar@414
   249
        LEMON_ASSERT(false, "FlowMap is not initialized");
alpar@414
   250
        return 0; // ignore warnings
alpar@414
   251
      }
alpar@414
   252
    };
alpar@414
   253
alpar@414
   254
    /// \brief \ref named-templ-param "Named parameter" for setting
alpar@414
   255
    /// FlowMap type
alpar@414
   256
    ///
alpar@414
   257
    /// \ref named-templ-param "Named parameter" for setting FlowMap
kpeter@417
   258
    /// type.
kpeter@606
   259
    template <typename T>
alpar@416
   260
    struct SetFlowMap
kpeter@657
   261
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   262
                           SetFlowMapTraits<T> > {
kpeter@657
   263
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   264
                          SetFlowMapTraits<T> > Create;
alpar@414
   265
    };
alpar@414
   266
kpeter@606
   267
    template <typename T>
alpar@416
   268
    struct SetElevatorTraits : public Traits {
kpeter@606
   269
      typedef T Elevator;
alpar@414
   270
      static Elevator *createElevator(const Digraph&, int) {
alpar@414
   271
        LEMON_ASSERT(false, "Elevator is not initialized");
alpar@414
   272
        return 0; // ignore warnings
alpar@414
   273
      }
alpar@414
   274
    };
alpar@414
   275
alpar@414
   276
    /// \brief \ref named-templ-param "Named parameter" for setting
alpar@414
   277
    /// Elevator type
alpar@414
   278
    ///
alpar@414
   279
    /// \ref named-templ-param "Named parameter" for setting Elevator
kpeter@417
   280
    /// type. If this named parameter is used, then an external
kpeter@417
   281
    /// elevator object must be passed to the algorithm using the
kpeter@417
   282
    /// \ref elevator(Elevator&) "elevator()" function before calling
kpeter@417
   283
    /// \ref run() or \ref init().
kpeter@417
   284
    /// \sa SetStandardElevator
kpeter@606
   285
    template <typename T>
alpar@416
   286
    struct SetElevator
kpeter@657
   287
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   288
                           SetElevatorTraits<T> > {
kpeter@657
   289
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   290
                          SetElevatorTraits<T> > Create;
alpar@414
   291
    };
alpar@414
   292
kpeter@606
   293
    template <typename T>
alpar@416
   294
    struct SetStandardElevatorTraits : public Traits {
kpeter@606
   295
      typedef T Elevator;
alpar@414
   296
      static Elevator *createElevator(const Digraph& digraph, int max_level) {
alpar@414
   297
        return new Elevator(digraph, max_level);
alpar@414
   298
      }
alpar@414
   299
    };
alpar@414
   300
alpar@414
   301
    /// \brief \ref named-templ-param "Named parameter" for setting
kpeter@417
   302
    /// Elevator type with automatic allocation
alpar@414
   303
    ///
alpar@414
   304
    /// \ref named-templ-param "Named parameter" for setting Elevator
kpeter@417
   305
    /// type with automatic allocation.
kpeter@417
   306
    /// The Elevator should have standard constructor interface to be
kpeter@417
   307
    /// able to automatically created by the algorithm (i.e. the
kpeter@417
   308
    /// digraph and the maximum level should be passed to it).
kpeter@833
   309
    /// However, an external elevator object could also be passed to the
kpeter@417
   310
    /// algorithm with the \ref elevator(Elevator&) "elevator()" function
kpeter@417
   311
    /// before calling \ref run() or \ref init().
kpeter@417
   312
    /// \sa SetElevator
kpeter@606
   313
    template <typename T>
alpar@416
   314
    struct SetStandardElevator
kpeter@657
   315
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   316
                       SetStandardElevatorTraits<T> > {
kpeter@657
   317
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   318
                      SetStandardElevatorTraits<T> > Create;
alpar@414
   319
    };
alpar@414
   320
alpar@414
   321
    /// @}
alpar@414
   322
alpar@414
   323
  protected:
alpar@414
   324
alpar@414
   325
    Circulation() {}
alpar@414
   326
alpar@414
   327
  public:
alpar@414
   328
kpeter@657
   329
    /// Constructor.
alpar@414
   330
alpar@414
   331
    /// The constructor of the class.
kpeter@657
   332
    ///
kpeter@657
   333
    /// \param graph The digraph the algorithm runs on.
kpeter@657
   334
    /// \param lower The lower bounds for the flow values on the arcs.
kpeter@657
   335
    /// \param upper The upper bounds (capacities) for the flow values 
kpeter@657
   336
    /// on the arcs.
kpeter@657
   337
    /// \param supply The signed supply values of the nodes.
kpeter@657
   338
    Circulation(const Digraph &graph, const LowerMap &lower,
kpeter@657
   339
                const UpperMap &upper, const SupplyMap &supply)
kpeter@657
   340
      : _g(graph), _lo(&lower), _up(&upper), _supply(&supply),
kpeter@657
   341
        _flow(NULL), _local_flow(false), _level(NULL), _local_level(false),
kpeter@657
   342
        _excess(NULL) {}
alpar@414
   343
kpeter@417
   344
    /// Destructor.
alpar@414
   345
    ~Circulation() {
alpar@414
   346
      destroyStructures();
alpar@414
   347
    }
alpar@414
   348
kpeter@417
   349
alpar@414
   350
  private:
alpar@414
   351
kpeter@669
   352
    bool checkBoundMaps() {
kpeter@669
   353
      for (ArcIt e(_g);e!=INVALID;++e) {
kpeter@669
   354
        if (_tol.less((*_up)[e], (*_lo)[e])) return false;
kpeter@669
   355
      }
kpeter@669
   356
      return true;
kpeter@669
   357
    }
kpeter@669
   358
alpar@414
   359
    void createStructures() {
alpar@414
   360
      _node_num = _el = countNodes(_g);
alpar@414
   361
alpar@414
   362
      if (!_flow) {
alpar@414
   363
        _flow = Traits::createFlowMap(_g);
alpar@414
   364
        _local_flow = true;
alpar@414
   365
      }
alpar@414
   366
      if (!_level) {
alpar@414
   367
        _level = Traits::createElevator(_g, _node_num);
alpar@414
   368
        _local_level = true;
alpar@414
   369
      }
alpar@414
   370
      if (!_excess) {
alpar@414
   371
        _excess = new ExcessMap(_g);
alpar@414
   372
      }
alpar@414
   373
    }
alpar@414
   374
alpar@414
   375
    void destroyStructures() {
alpar@414
   376
      if (_local_flow) {
alpar@414
   377
        delete _flow;
alpar@414
   378
      }
alpar@414
   379
      if (_local_level) {
alpar@414
   380
        delete _level;
alpar@414
   381
      }
alpar@414
   382
      if (_excess) {
alpar@414
   383
        delete _excess;
alpar@414
   384
      }
alpar@414
   385
    }
alpar@414
   386
alpar@414
   387
  public:
alpar@414
   388
kpeter@657
   389
    /// Sets the lower bound map.
alpar@414
   390
kpeter@657
   391
    /// Sets the lower bound map.
kpeter@417
   392
    /// \return <tt>(*this)</tt>
kpeter@657
   393
    Circulation& lowerMap(const LowerMap& map) {
alpar@414
   394
      _lo = &map;
alpar@414
   395
      return *this;
alpar@414
   396
    }
alpar@414
   397
kpeter@657
   398
    /// Sets the upper bound (capacity) map.
alpar@414
   399
kpeter@657
   400
    /// Sets the upper bound (capacity) map.
kpeter@417
   401
    /// \return <tt>(*this)</tt>
kpeter@669
   402
    Circulation& upperMap(const UpperMap& map) {
alpar@414
   403
      _up = &map;
alpar@414
   404
      return *this;
alpar@414
   405
    }
alpar@414
   406
kpeter@657
   407
    /// Sets the supply map.
alpar@414
   408
kpeter@657
   409
    /// Sets the supply map.
kpeter@417
   410
    /// \return <tt>(*this)</tt>
kpeter@657
   411
    Circulation& supplyMap(const SupplyMap& map) {
kpeter@657
   412
      _supply = &map;
alpar@414
   413
      return *this;
alpar@414
   414
    }
alpar@414
   415
kpeter@417
   416
    /// \brief Sets the flow map.
kpeter@417
   417
    ///
alpar@414
   418
    /// Sets the flow map.
kpeter@417
   419
    /// If you don't use this function before calling \ref run() or
kpeter@417
   420
    /// \ref init(), an instance will be allocated automatically.
kpeter@417
   421
    /// The destructor deallocates this automatically allocated map,
kpeter@417
   422
    /// of course.
kpeter@417
   423
    /// \return <tt>(*this)</tt>
alpar@414
   424
    Circulation& flowMap(FlowMap& map) {
alpar@414
   425
      if (_local_flow) {
alpar@414
   426
        delete _flow;
alpar@414
   427
        _local_flow = false;
alpar@414
   428
      }
alpar@414
   429
      _flow = &map;
alpar@414
   430
      return *this;
alpar@414
   431
    }
alpar@414
   432
kpeter@417
   433
    /// \brief Sets the elevator used by algorithm.
alpar@414
   434
    ///
kpeter@417
   435
    /// Sets the elevator used by algorithm.
kpeter@417
   436
    /// If you don't use this function before calling \ref run() or
kpeter@417
   437
    /// \ref init(), an instance will be allocated automatically.
kpeter@417
   438
    /// The destructor deallocates this automatically allocated elevator,
kpeter@417
   439
    /// of course.
kpeter@417
   440
    /// \return <tt>(*this)</tt>
alpar@414
   441
    Circulation& elevator(Elevator& elevator) {
alpar@414
   442
      if (_local_level) {
alpar@414
   443
        delete _level;
alpar@414
   444
        _local_level = false;
alpar@414
   445
      }
alpar@414
   446
      _level = &elevator;
alpar@414
   447
      return *this;
alpar@414
   448
    }
alpar@414
   449
kpeter@417
   450
    /// \brief Returns a const reference to the elevator.
alpar@414
   451
    ///
kpeter@417
   452
    /// Returns a const reference to the elevator.
kpeter@417
   453
    ///
kpeter@417
   454
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@417
   455
    /// using this function.
kpeter@437
   456
    const Elevator& elevator() const {
alpar@414
   457
      return *_level;
alpar@414
   458
    }
alpar@414
   459
kpeter@736
   460
    /// \brief Sets the tolerance used by the algorithm.
kpeter@417
   461
    ///
kpeter@736
   462
    /// Sets the tolerance object used by the algorithm.
kpeter@736
   463
    /// \return <tt>(*this)</tt>
kpeter@735
   464
    Circulation& tolerance(const Tolerance& tolerance) {
alpar@414
   465
      _tol = tolerance;
alpar@414
   466
      return *this;
alpar@414
   467
    }
alpar@414
   468
kpeter@417
   469
    /// \brief Returns a const reference to the tolerance.
alpar@414
   470
    ///
kpeter@736
   471
    /// Returns a const reference to the tolerance object used by
kpeter@736
   472
    /// the algorithm.
alpar@414
   473
    const Tolerance& tolerance() const {
kpeter@735
   474
      return _tol;
alpar@414
   475
    }
alpar@414
   476
kpeter@417
   477
    /// \name Execution Control
kpeter@417
   478
    /// The simplest way to execute the algorithm is to call \ref run().\n
kpeter@760
   479
    /// If you need better control on the initial solution or the execution,
kpeter@760
   480
    /// you have to call one of the \ref init() functions first, then
kpeter@417
   481
    /// the \ref start() function.
alpar@414
   482
alpar@414
   483
    ///@{
alpar@414
   484
alpar@414
   485
    /// Initializes the internal data structures.
alpar@414
   486
kpeter@417
   487
    /// Initializes the internal data structures and sets all flow values
kpeter@417
   488
    /// to the lower bound.
alpar@414
   489
    void init()
alpar@414
   490
    {
kpeter@669
   491
      LEMON_DEBUG(checkBoundMaps(),
kpeter@669
   492
        "Upper bounds must be greater or equal to the lower bounds");
kpeter@669
   493
alpar@414
   494
      createStructures();
alpar@414
   495
alpar@414
   496
      for(NodeIt n(_g);n!=INVALID;++n) {
alpar@658
   497
        (*_excess)[n] = (*_supply)[n];
alpar@414
   498
      }
alpar@414
   499
alpar@414
   500
      for (ArcIt e(_g);e!=INVALID;++e) {
alpar@414
   501
        _flow->set(e, (*_lo)[e]);
kpeter@628
   502
        (*_excess)[_g.target(e)] += (*_flow)[e];
kpeter@628
   503
        (*_excess)[_g.source(e)] -= (*_flow)[e];
alpar@414
   504
      }
alpar@414
   505
alpar@414
   506
      // global relabeling tested, but in general case it provides
alpar@414
   507
      // worse performance for random digraphs
alpar@414
   508
      _level->initStart();
alpar@414
   509
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   510
        _level->initAddItem(n);
alpar@414
   511
      _level->initFinish();
alpar@414
   512
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   513
        if(_tol.positive((*_excess)[n]))
alpar@414
   514
          _level->activate(n);
alpar@414
   515
    }
alpar@414
   516
kpeter@417
   517
    /// Initializes the internal data structures using a greedy approach.
alpar@414
   518
kpeter@417
   519
    /// Initializes the internal data structures using a greedy approach
kpeter@417
   520
    /// to construct the initial solution.
alpar@414
   521
    void greedyInit()
alpar@414
   522
    {
kpeter@669
   523
      LEMON_DEBUG(checkBoundMaps(),
kpeter@669
   524
        "Upper bounds must be greater or equal to the lower bounds");
kpeter@669
   525
alpar@414
   526
      createStructures();
alpar@414
   527
alpar@414
   528
      for(NodeIt n(_g);n!=INVALID;++n) {
alpar@658
   529
        (*_excess)[n] = (*_supply)[n];
alpar@414
   530
      }
alpar@414
   531
alpar@414
   532
      for (ArcIt e(_g);e!=INVALID;++e) {
kpeter@669
   533
        if (!_tol.less(-(*_excess)[_g.target(e)], (*_up)[e])) {
alpar@414
   534
          _flow->set(e, (*_up)[e]);
kpeter@628
   535
          (*_excess)[_g.target(e)] += (*_up)[e];
kpeter@628
   536
          (*_excess)[_g.source(e)] -= (*_up)[e];
kpeter@669
   537
        } else if (_tol.less(-(*_excess)[_g.target(e)], (*_lo)[e])) {
alpar@414
   538
          _flow->set(e, (*_lo)[e]);
kpeter@628
   539
          (*_excess)[_g.target(e)] += (*_lo)[e];
kpeter@628
   540
          (*_excess)[_g.source(e)] -= (*_lo)[e];
alpar@414
   541
        } else {
kpeter@688
   542
          Value fc = -(*_excess)[_g.target(e)];
alpar@414
   543
          _flow->set(e, fc);
kpeter@628
   544
          (*_excess)[_g.target(e)] = 0;
kpeter@628
   545
          (*_excess)[_g.source(e)] -= fc;
alpar@414
   546
        }
alpar@414
   547
      }
alpar@414
   548
alpar@414
   549
      _level->initStart();
alpar@414
   550
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   551
        _level->initAddItem(n);
alpar@414
   552
      _level->initFinish();
alpar@414
   553
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   554
        if(_tol.positive((*_excess)[n]))
alpar@414
   555
          _level->activate(n);
alpar@414
   556
    }
alpar@414
   557
kpeter@417
   558
    ///Executes the algorithm
alpar@414
   559
kpeter@417
   560
    ///This function executes the algorithm.
kpeter@417
   561
    ///
kpeter@417
   562
    ///\return \c true if a feasible circulation is found.
alpar@414
   563
    ///
alpar@414
   564
    ///\sa barrier()
kpeter@417
   565
    ///\sa barrierMap()
alpar@414
   566
    bool start()
alpar@414
   567
    {
alpar@414
   568
alpar@414
   569
      Node act;
alpar@414
   570
      Node bact=INVALID;
alpar@414
   571
      Node last_activated=INVALID;
alpar@414
   572
      while((act=_level->highestActive())!=INVALID) {
alpar@414
   573
        int actlevel=(*_level)[act];
alpar@414
   574
        int mlevel=_node_num;
kpeter@688
   575
        Value exc=(*_excess)[act];
alpar@414
   576
alpar@414
   577
        for(OutArcIt e(_g,act);e!=INVALID; ++e) {
alpar@414
   578
          Node v = _g.target(e);
kpeter@688
   579
          Value fc=(*_up)[e]-(*_flow)[e];
alpar@414
   580
          if(!_tol.positive(fc)) continue;
alpar@414
   581
          if((*_level)[v]<actlevel) {
alpar@414
   582
            if(!_tol.less(fc, exc)) {
alpar@414
   583
              _flow->set(e, (*_flow)[e] + exc);
kpeter@628
   584
              (*_excess)[v] += exc;
alpar@414
   585
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
alpar@414
   586
                _level->activate(v);
kpeter@628
   587
              (*_excess)[act] = 0;
alpar@414
   588
              _level->deactivate(act);
alpar@414
   589
              goto next_l;
alpar@414
   590
            }
alpar@414
   591
            else {
alpar@414
   592
              _flow->set(e, (*_up)[e]);
kpeter@628
   593
              (*_excess)[v] += fc;
alpar@414
   594
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
alpar@414
   595
                _level->activate(v);
alpar@414
   596
              exc-=fc;
alpar@414
   597
            }
alpar@414
   598
          }
alpar@414
   599
          else if((*_level)[v]<mlevel) mlevel=(*_level)[v];
alpar@414
   600
        }
alpar@414
   601
        for(InArcIt e(_g,act);e!=INVALID; ++e) {
alpar@414
   602
          Node v = _g.source(e);
kpeter@688
   603
          Value fc=(*_flow)[e]-(*_lo)[e];
alpar@414
   604
          if(!_tol.positive(fc)) continue;
alpar@414
   605
          if((*_level)[v]<actlevel) {
alpar@414
   606
            if(!_tol.less(fc, exc)) {
alpar@414
   607
              _flow->set(e, (*_flow)[e] - exc);
kpeter@628
   608
              (*_excess)[v] += exc;
alpar@414
   609
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
alpar@414
   610
                _level->activate(v);
kpeter@628
   611
              (*_excess)[act] = 0;
alpar@414
   612
              _level->deactivate(act);
alpar@414
   613
              goto next_l;
alpar@414
   614
            }
alpar@414
   615
            else {
alpar@414
   616
              _flow->set(e, (*_lo)[e]);
kpeter@628
   617
              (*_excess)[v] += fc;
alpar@414
   618
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
alpar@414
   619
                _level->activate(v);
alpar@414
   620
              exc-=fc;
alpar@414
   621
            }
alpar@414
   622
          }
alpar@414
   623
          else if((*_level)[v]<mlevel) mlevel=(*_level)[v];
alpar@414
   624
        }
alpar@414
   625
kpeter@628
   626
        (*_excess)[act] = exc;
alpar@414
   627
        if(!_tol.positive(exc)) _level->deactivate(act);
alpar@414
   628
        else if(mlevel==_node_num) {
alpar@414
   629
          _level->liftHighestActiveToTop();
alpar@414
   630
          _el = _node_num;
alpar@414
   631
          return false;
alpar@414
   632
        }
alpar@414
   633
        else {
alpar@414
   634
          _level->liftHighestActive(mlevel+1);
alpar@414
   635
          if(_level->onLevel(actlevel)==0) {
alpar@414
   636
            _el = actlevel;
alpar@414
   637
            return false;
alpar@414
   638
          }
alpar@414
   639
        }
alpar@414
   640
      next_l:
alpar@414
   641
        ;
alpar@414
   642
      }
alpar@414
   643
      return true;
alpar@414
   644
    }
alpar@414
   645
kpeter@417
   646
    /// Runs the algorithm.
alpar@414
   647
kpeter@417
   648
    /// This function runs the algorithm.
kpeter@417
   649
    ///
kpeter@417
   650
    /// \return \c true if a feasible circulation is found.
kpeter@417
   651
    ///
kpeter@417
   652
    /// \note Apart from the return value, c.run() is just a shortcut of
kpeter@417
   653
    /// the following code.
alpar@414
   654
    /// \code
kpeter@417
   655
    ///   c.greedyInit();
kpeter@417
   656
    ///   c.start();
alpar@414
   657
    /// \endcode
alpar@414
   658
    bool run() {
alpar@414
   659
      greedyInit();
alpar@414
   660
      return start();
alpar@414
   661
    }
alpar@414
   662
alpar@414
   663
    /// @}
alpar@414
   664
alpar@414
   665
    /// \name Query Functions
kpeter@417
   666
    /// The results of the circulation algorithm can be obtained using
kpeter@417
   667
    /// these functions.\n
kpeter@417
   668
    /// Either \ref run() or \ref start() should be called before
kpeter@417
   669
    /// using them.
alpar@414
   670
alpar@414
   671
    ///@{
alpar@414
   672
kpeter@688
   673
    /// \brief Returns the flow value on the given arc.
kpeter@417
   674
    ///
kpeter@688
   675
    /// Returns the flow value on the given arc.
kpeter@417
   676
    ///
kpeter@417
   677
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@417
   678
    /// using this function.
kpeter@688
   679
    Value flow(const Arc& arc) const {
kpeter@417
   680
      return (*_flow)[arc];
kpeter@417
   681
    }
kpeter@417
   682
kpeter@417
   683
    /// \brief Returns a const reference to the flow map.
kpeter@417
   684
    ///
kpeter@417
   685
    /// Returns a const reference to the arc map storing the found flow.
kpeter@417
   686
    ///
kpeter@417
   687
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@417
   688
    /// using this function.
kpeter@437
   689
    const FlowMap& flowMap() const {
kpeter@417
   690
      return *_flow;
kpeter@417
   691
    }
kpeter@417
   692
alpar@414
   693
    /**
kpeter@417
   694
       \brief Returns \c true if the given node is in a barrier.
kpeter@417
   695
alpar@414
   696
       Barrier is a set \e B of nodes for which
kpeter@417
   697
kpeter@657
   698
       \f[ \sum_{uv\in A: u\in B} upper(uv) -
kpeter@657
   699
           \sum_{uv\in A: v\in B} lower(uv) < \sum_{v\in B} sup(v) \f]
kpeter@417
   700
kpeter@417
   701
       holds. The existence of a set with this property prooves that a
kpeter@417
   702
       feasible circualtion cannot exist.
kpeter@417
   703
kpeter@417
   704
       This function returns \c true if the given node is in the found
kpeter@417
   705
       barrier. If a feasible circulation is found, the function
kpeter@417
   706
       gives back \c false for every node.
kpeter@417
   707
kpeter@417
   708
       \pre Either \ref run() or \ref init() must be called before
kpeter@417
   709
       using this function.
kpeter@417
   710
kpeter@417
   711
       \sa barrierMap()
alpar@414
   712
       \sa checkBarrier()
alpar@414
   713
    */
kpeter@437
   714
    bool barrier(const Node& node) const
kpeter@417
   715
    {
kpeter@417
   716
      return (*_level)[node] >= _el;
kpeter@417
   717
    }
kpeter@417
   718
kpeter@417
   719
    /// \brief Gives back a barrier.
kpeter@417
   720
    ///
kpeter@417
   721
    /// This function sets \c bar to the characteristic vector of the
kpeter@417
   722
    /// found barrier. \c bar should be a \ref concepts::WriteMap "writable"
kpeter@417
   723
    /// node map with \c bool (or convertible) value type.
kpeter@417
   724
    ///
kpeter@417
   725
    /// If a feasible circulation is found, the function gives back an
kpeter@417
   726
    /// empty set, so \c bar[v] will be \c false for all nodes \c v.
kpeter@417
   727
    ///
kpeter@417
   728
    /// \note This function calls \ref barrier() for each node,
kpeter@606
   729
    /// so it runs in O(n) time.
kpeter@417
   730
    ///
kpeter@417
   731
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@417
   732
    /// using this function.
kpeter@417
   733
    ///
kpeter@417
   734
    /// \sa barrier()
kpeter@417
   735
    /// \sa checkBarrier()
kpeter@417
   736
    template<class BarrierMap>
kpeter@437
   737
    void barrierMap(BarrierMap &bar) const
alpar@414
   738
    {
alpar@414
   739
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   740
        bar.set(n, (*_level)[n] >= _el);
alpar@414
   741
    }
alpar@414
   742
alpar@414
   743
    /// @}
alpar@414
   744
alpar@414
   745
    /// \name Checker Functions
kpeter@417
   746
    /// The feasibility of the results can be checked using
kpeter@417
   747
    /// these functions.\n
kpeter@417
   748
    /// Either \ref run() or \ref start() should be called before
kpeter@417
   749
    /// using them.
alpar@414
   750
alpar@414
   751
    ///@{
alpar@414
   752
kpeter@417
   753
    ///Check if the found flow is a feasible circulation
kpeter@417
   754
kpeter@417
   755
    ///Check if the found flow is a feasible circulation,
kpeter@417
   756
    ///
kpeter@437
   757
    bool checkFlow() const {
alpar@414
   758
      for(ArcIt e(_g);e!=INVALID;++e)
alpar@414
   759
        if((*_flow)[e]<(*_lo)[e]||(*_flow)[e]>(*_up)[e]) return false;
alpar@414
   760
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   761
        {
kpeter@688
   762
          Value dif=-(*_supply)[n];
alpar@414
   763
          for(InArcIt e(_g,n);e!=INVALID;++e) dif-=(*_flow)[e];
alpar@414
   764
          for(OutArcIt e(_g,n);e!=INVALID;++e) dif+=(*_flow)[e];
alpar@414
   765
          if(_tol.negative(dif)) return false;
alpar@414
   766
        }
alpar@414
   767
      return true;
alpar@414
   768
    }
alpar@414
   769
alpar@414
   770
    ///Check whether or not the last execution provides a barrier
alpar@414
   771
kpeter@417
   772
    ///Check whether or not the last execution provides a barrier.
alpar@414
   773
    ///\sa barrier()
kpeter@417
   774
    ///\sa barrierMap()
kpeter@437
   775
    bool checkBarrier() const
alpar@414
   776
    {
kpeter@688
   777
      Value delta=0;
kpeter@688
   778
      Value inf_cap = std::numeric_limits<Value>::has_infinity ?
kpeter@688
   779
        std::numeric_limits<Value>::infinity() :
kpeter@688
   780
        std::numeric_limits<Value>::max();
alpar@414
   781
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   782
        if(barrier(n))
kpeter@657
   783
          delta-=(*_supply)[n];
alpar@414
   784
      for(ArcIt e(_g);e!=INVALID;++e)
alpar@414
   785
        {
alpar@414
   786
          Node s=_g.source(e);
alpar@414
   787
          Node t=_g.target(e);
kpeter@669
   788
          if(barrier(s)&&!barrier(t)) {
kpeter@669
   789
            if (_tol.less(inf_cap - (*_up)[e], delta)) return false;
kpeter@669
   790
            delta+=(*_up)[e];
kpeter@669
   791
          }
alpar@414
   792
          else if(barrier(t)&&!barrier(s)) delta-=(*_lo)[e];
alpar@414
   793
        }
alpar@414
   794
      return _tol.negative(delta);
alpar@414
   795
    }
alpar@414
   796
alpar@414
   797
    /// @}
alpar@414
   798
alpar@414
   799
  };
alpar@414
   800
alpar@414
   801
}
alpar@414
   802
alpar@414
   803
#endif