COIN-OR::LEMON - Graph Library

Ticket #377: forward_graph.patch

File forward_graph.patch, 15.4 KB (added by Gabriel Gouvine, 4 years ago)

First version of the compact digraph

  • new file lemon/compact_graph.h

    # HG changeset patch
    # User Gabriel Gouvine <gabriel.gouvine.GIT@gmx.com>
    # Date 1489930688 -3600
    #      Sun Mar 19 14:38:08 2017 +0100
    # Branch compact_graph
    # Node ID 0f20be66106f756d3b051b2777077b2641df68a0
    # Parent  f51c01a1b88eead63515a8b22f6f380595245a42
    CompactDigraph implementation
    
    Smaller version of StaticDigraph (n+m) if InArcIt is not needed
    
    diff -r f51c01a1b88e -r 0f20be66106f lemon/compact_graph.h
    - +  
     1/* -*- mode: C++; indent-tabs-mode: nil; -*-
     2 *
     3 * This file is a part of LEMON, a generic C++ optimization library.
     4 *
     5 * Copyright (C) 2017
     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_FORWARD_GRAPH_H
     20#define LEMON_FORWARD_GRAPH_H
     21
     22///\ingroup graphs
     23///\file
     24///\brief CompactDigraph class.
     25
     26#include <lemon/core.h>
     27#include <lemon/bits/graph_extender.h>
     28
     29#include <algorithm>
     30
     31namespace lemon {
     32
     33  class CompactDigraphBase {
     34
     35  public:
     36
     37    CompactDigraphBase()
     38      : built(false), node_num(0), arc_num(0),
     39        node_first_out(NULL),
     40        arc_target(NULL) {}
     41
     42    ~CompactDigraphBase() {
     43      if (built) {
     44        delete[] node_first_out;
     45        delete[] arc_target;
     46      }
     47    }
     48
     49    class Node {
     50      friend class CompactDigraphBase;
     51    protected:
     52      int id;
     53      Node(int _id) : id(_id) {}
     54    public:
     55      Node() {}
     56      Node (Invalid) : id(-1) {}
     57      bool operator==(const Node& node) const { return id == node.id; }
     58      bool operator!=(const Node& node) const { return id != node.id; }
     59      bool operator<(const Node& node) const { return id < node.id; }
     60    };
     61
     62    class Arc {
     63      friend class CompactDigraphBase;
     64    protected:
     65      int id;
     66      int source;
     67      int last;
     68      Arc(int _id, int _source, int _last) : id(_id), source(_source), last(_last) {}
     69    public:
     70      Arc() { }
     71      Arc (Invalid) : id(-1) {}
     72      bool operator==(const Arc& arc) const { return id == arc.id; }
     73      bool operator!=(const Arc& arc) const { return id != arc.id; }
     74      bool operator<(const Arc& arc) const { return id < arc.id; }
     75    };
     76
     77    Node source(const Arc& e) const { return Node(e.source); }
     78    Node target(const Arc& e) const { return Node(arc_target[e.id]); }
     79
     80    void first(Node& n) const { n.id = node_num - 1; }
     81    static void next(Node& n) { --n.id; }
     82
     83  private:
     84
     85    void nextSource(Arc& e) const {
     86      if (e.id == -1) return;
     87      while (e.id == e.last) {
     88        --e.source;
     89        e.last = node_first_out[e.source] - 1;
     90      }
     91    }
     92
     93  public:
     94
     95    void first(Arc& e) const {
     96      e.id = arc_num - 1;
     97      e.source = node_num - 1;
     98      e.last = node_num != 0 ? node_first_out[e.source+1] - 1 : -1;
     99      nextSource(e);
     100    }
     101    void next(Arc& e) const {
     102      --e.id;
     103      nextSource(e);
     104    }
     105
     106    void firstOut(Arc& e, const Node& n) const {
     107      e.source = n.id;
     108      e.id = node_first_out[n.id];
     109      e.last = node_first_out[n.id + 1];
     110      if (e.id == e.last) e.id = -1;
     111    }
     112    void nextOut(Arc& e) const {
     113      ++e.id;
     114      if (e.id == e.last) e.id = -1;
     115    }
     116
     117    void firstIn(Arc& e, const Node& n) const {
     118      first(e);
     119      while(e != INVALID && target(e) != n) {
     120        next(e);
     121      }
     122    }
     123    void nextIn(Arc& e) const {
     124      Node arcTarget = target(e);
     125      do {
     126        next(e);
     127      } while(e != INVALID && target(e) != arcTarget);
     128    }
     129
     130    static int id(const Node& n) { return n.id; }
     131    static Node nodeFromId(int id) { return Node(id); }
     132    int maxNodeId() const { return node_num - 1; }
     133
     134    static int id(const Arc& e) { return e.id; }
     135    Arc arcFromId(int id) const {
     136      int *l = std::upper_bound(node_first_out, node_first_out + node_num, id) - 1;
     137      int src = l - node_first_out;
     138      int last = *(l - 1);
     139      return Arc(id, src, last);
     140    }
     141    int maxArcId() const { return arc_num - 1; }
     142
     143    typedef True NodeNumTag;
     144    typedef True ArcNumTag;
     145
     146    int nodeNum() const { return node_num; }
     147    int arcNum() const { return arc_num; }
     148
     149  private:
     150
     151    template <typename Digraph, typename NodeRefMap>
     152    class ArcLess {
     153    public:
     154      typedef typename Digraph::Arc Arc;
     155
     156      ArcLess(const Digraph &_graph, const NodeRefMap& _nodeRef)
     157        : digraph(_graph), nodeRef(_nodeRef) {}
     158
     159      bool operator()(const Arc& left, const Arc& right) const {
     160        return nodeRef[digraph.target(left)] < nodeRef[digraph.target(right)];
     161      }
     162    private:
     163      const Digraph& digraph;
     164      const NodeRefMap& nodeRef;
     165    };
     166
     167  public:
     168
     169    typedef True BuildTag;
     170
     171    void clear() {
     172      if (built) {
     173        delete[] node_first_out;
     174        delete[] arc_target;
     175      }
     176      built = false;
     177      node_num = 0;
     178      arc_num = 0;
     179    }
     180
     181    template <typename Digraph, typename NodeRefMap, typename ArcRefMap>
     182    void build(const Digraph& digraph, NodeRefMap& nodeRef, ArcRefMap& arcRef) {
     183      typedef typename Digraph::Node GNode;
     184      typedef typename Digraph::Arc GArc;
     185
     186      built = true;
     187
     188      node_num = countNodes(digraph);
     189      arc_num = countArcs(digraph);
     190
     191      node_first_out = new int[node_num + 1];
     192
     193      arc_target = new int[arc_num];
     194
     195      int node_index = 0;
     196      for (typename Digraph::NodeIt n(digraph); n != INVALID; ++n) {
     197        nodeRef[n] = Node(node_index);
     198        ++node_index;
     199      }
     200
     201      ArcLess<Digraph, NodeRefMap> arcLess(digraph, nodeRef);
     202
     203      int arc_index = 0;
     204      for (typename Digraph::NodeIt n(digraph); n != INVALID; ++n) {
     205        int source = nodeRef[n].id;
     206        std::vector<GArc> arcs;
     207        for (typename Digraph::OutArcIt e(digraph, n); e != INVALID; ++e) {
     208          arcs.push_back(e);
     209        }
     210        if (!arcs.empty()) {
     211          node_first_out[source] = arc_index;
     212          std::sort(arcs.begin(), arcs.end(), arcLess);
     213          for (typename std::vector<GArc>::iterator it = arcs.begin();
     214               it != arcs.end(); ++it) {
     215            int target = nodeRef[digraph.target(*it)].id;
     216            arcRef[*it] = Arc(arc_index, source, node_first_out[source]-1);
     217            arc_target[arc_index] = target;
     218            ++arc_index;
     219          }
     220        } else {
     221          node_first_out[source] = arc_index;
     222        }
     223      }
     224      node_first_out[node_num] = arc_num;
     225    }
     226
     227    template <typename ArcListIterator>
     228    void build(int n, ArcListIterator first, ArcListIterator last) {
     229      built = true;
     230
     231      node_num = n;
     232      arc_num = static_cast<int>(std::distance(first, last));
     233
     234      node_first_out = new int[node_num + 1];
     235
     236      arc_target = new int[arc_num];
     237
     238      int arc_index = 0;
     239      for (int i = 0; i != node_num; ++i) {
     240        node_first_out[i] = arc_index;
     241        for ( ; first != last && (*first).first == i; ++first) {
     242          int j = (*first).second;
     243          LEMON_ASSERT(j >= 0 && j < node_num,
     244            "Wrong arc list for CompactDigraph::build()");
     245          arc_target[arc_index] = j;
     246          ++arc_index;
     247        }
     248      }
     249      LEMON_ASSERT(first == last,
     250        "Wrong arc list for CompactDigraph::build()");
     251      node_first_out[node_num] = arc_num;
     252    }
     253
     254  protected:
     255    bool built;
     256    int node_num;
     257    int arc_num;
     258    int *node_first_out;
     259    int *arc_target;
     260  };
     261
     262  typedef DigraphExtender<CompactDigraphBase> ExtendedCompactDigraphBase;
     263
     264
     265  /// \ingroup graphs
     266  ///
     267  /// \brief A static directed graph class.
     268  ///
     269  /// \ref CompactDigraph is a highly efficient digraph implementation
     270  /// similar to \ref StaticDigraph. It is more memory efficient but does
     271  /// not provide efficient iteration over incoming arcs.
     272  ///
     273  /// It stores only one \c int values for each node and one \c int value
     274  /// for each arc. Its \ref InArcIt implementation is inefficient and
     275  /// provided only for compatibility with the \ref concepts::Digraph "Digraph concept".
     276  ///
     277  /// This type fully conforms to the \ref concepts::Digraph "Digraph concept".
     278  /// Most of its member functions and nested classes are documented
     279  /// only in the concept class.
     280  ///
     281  /// \sa concepts::Digraph
     282  class CompactDigraph : public ExtendedCompactDigraphBase {
     283
     284  private:
     285    /// Graphs are \e not copy constructible. Use DigraphCopy instead.
     286    CompactDigraph(const CompactDigraph &) : ExtendedCompactDigraphBase() {};
     287    /// \brief Assignment of a graph to another one is \e not allowed.
     288    /// Use DigraphCopy instead.
     289    void operator=(const CompactDigraph&) {}
     290
     291  public:
     292
     293    typedef ExtendedCompactDigraphBase Parent;
     294
     295  public:
     296
     297    /// \brief Constructor
     298    ///
     299    /// Default constructor.
     300    CompactDigraph() : Parent() {}
     301
     302    /// \brief The node with the given index.
     303    ///
     304    /// This function returns the node with the given index.
     305    /// \sa index()
     306    static Node node(int ix) { return Parent::nodeFromId(ix); }
     307
     308    /// \brief The arc with the given index.
     309    ///
     310    /// This function returns the arc with the given index.
     311    /// \sa index()
     312    Arc arc(int ix) { return arcFromId(ix); }
     313
     314    /// \brief The index of the given node.
     315    ///
     316    /// This function returns the index of the the given node.
     317    /// \sa node()
     318    static int index(Node node) { return Parent::id(node); }
     319
     320    /// \brief The index of the given arc.
     321    ///
     322    /// This function returns the index of the the given arc.
     323    /// \sa arc()
     324    static int index(Arc arc) { return Parent::id(arc); }
     325
     326    /// \brief Number of nodes.
     327    ///
     328    /// This function returns the number of nodes.
     329    int nodeNum() const { return node_num; }
     330
     331    /// \brief Number of arcs.
     332    ///
     333    /// This function returns the number of arcs.
     334    int arcNum() const { return arc_num; }
     335
     336    /// \brief Build the digraph copying another digraph.
     337    ///
     338    /// This function builds the digraph copying another digraph of any
     339    /// kind. It can be called more than once, but in such case, the whole
     340    /// structure and all maps will be cleared and rebuilt.
     341    ///
     342    /// This method also makes possible to copy a digraph to a CompactDigraph
     343    /// structure using \ref DigraphCopy.
     344    ///
     345    /// \param digraph An existing digraph to be copied.
     346    /// \param nodeRef The node references will be copied into this map.
     347    /// Its key type must be \c Digraph::Node and its value type must be
     348    /// \c CompactDigraph::Node.
     349    /// It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap"
     350    /// concept.
     351    /// \param arcRef The arc references will be copied into this map.
     352    /// Its key type must be \c Digraph::Arc and its value type must be
     353    /// \c CompactDigraph::Arc.
     354    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
     355    ///
     356    /// \note If you do not need the arc references, then you could use
     357    /// \ref NullMap for the last parameter. However the node references
     358    /// are required by the function itself, thus they must be readable
     359    /// from the map.
     360    template <typename Digraph, typename NodeRefMap, typename ArcRefMap>
     361    void build(const Digraph& digraph, NodeRefMap& nodeRef, ArcRefMap& arcRef) {
     362      if (built) Parent::clear();
     363      Parent::build(digraph, nodeRef, arcRef);
     364    }
     365
     366    /// \brief Build the digraph from an arc list.
     367    ///
     368    /// This function builds the digraph from the given arc list.
     369    /// It can be called more than once, but in such case, the whole
     370    /// structure and all maps will be cleared and rebuilt.
     371    ///
     372    /// The list of the arcs must be given in the range <tt>[begin, end)</tt>
     373    /// specified by STL compatible itartors whose \c value_type must be
     374    /// <tt>std::pair<int,int></tt>.
     375    /// Each arc must be specified by a pair of integer indices
     376    /// from the range <tt>[0..n-1]</tt>. <i>The pairs must be in a
     377    /// non-decreasing order with respect to their first values.</i>
     378    /// If the k-th pair in the list is <tt>(i,j)</tt>, then
     379    /// <tt>arc(k-1)</tt> will connect <tt>node(i)</tt> to <tt>node(j)</tt>.
     380    ///
     381    /// \param n The number of nodes.
     382    /// \param begin An iterator pointing to the beginning of the arc list.
     383    /// \param end An iterator pointing to the end of the arc list.
     384    ///
     385    /// For example, a simple digraph can be constructed like this.
     386    /// \code
     387    ///   std::vector<std::pair<int,int> > arcs;
     388    ///   arcs.push_back(std::make_pair(0,1));
     389    ///   arcs.push_back(std::make_pair(0,2));
     390    ///   arcs.push_back(std::make_pair(1,3));
     391    ///   arcs.push_back(std::make_pair(1,2));
     392    ///   arcs.push_back(std::make_pair(3,0));
     393    ///   CompactDigraph gr;
     394    ///   gr.build(4, arcs.begin(), arcs.end());
     395    /// \endcode
     396    template <typename ArcListIterator>
     397    void build(int n, ArcListIterator begin, ArcListIterator end) {
     398      if (built) Parent::clear();
     399      CompactDigraphBase::build(n, begin, end);
     400      notifier(Node()).build();
     401      notifier(Arc()).build();
     402    }
     403
     404    /// \brief Clear the digraph.
     405    ///
     406    /// This function erases all nodes and arcs from the digraph.
     407    void clear() {
     408      Parent::clear();
     409    }
     410
     411  public:
     412
     413    Node baseNode(const OutArcIt &arc) const {
     414      return Parent::source(static_cast<const Arc&>(arc));
     415    }
     416
     417    Node runningNode(const OutArcIt &arc) const {
     418      return Parent::target(static_cast<const Arc&>(arc));
     419    }
     420
     421    Node baseNode(const InArcIt &arc) const {
     422      return Parent::target(static_cast<const Arc&>(arc));
     423    }
     424
     425    Node runningNode(const InArcIt &arc) const {
     426      return Parent::source(static_cast<const Arc&>(arc));
     427    }
     428
     429  };
     430
     431}
     432
     433#endif
  • test/digraph_test.cc

    diff -r f51c01a1b88e -r 0f20be66106f test/digraph_test.cc
    a b  
    2020#include <lemon/list_graph.h>
    2121#include <lemon/smart_graph.h>
    2222#include <lemon/static_graph.h>
     23#include <lemon/compact_graph.h>
    2324#include <lemon/full_graph.h>
    2425
    2526#include "test_tools.h"
     
    338339    checkConcept<Digraph, StaticDigraph>();
    339340    checkConcept<ClearableDigraphComponent<>, StaticDigraph>();
    340341  }
     342  { // Checking CompactDigraph
     343    checkConcept<Digraph, CompactDigraph>();
     344    checkConcept<ClearableDigraphComponent<>, CompactDigraph>();
     345  }
    341346  { // Checking FullDigraph
    342347    checkConcept<Digraph, FullDigraph>();
    343348  }
     
    394399  check(!g.valid(g.arcFromId(-1)), "Wrong validity check");
    395400}
    396401
     402template <typename GR>
    397403void checkStaticDigraph() {
    398404  SmartDigraph g;
    399   SmartDigraph::NodeMap<StaticDigraph::Node> nref(g);
    400   SmartDigraph::ArcMap<StaticDigraph::Arc> aref(g);
     405  SmartDigraph::NodeMap<typename GR::Node> nref(g);
     406  SmartDigraph::ArcMap<typename GR::Arc> aref(g);
    401407
    402   StaticDigraph G;
     408  GR G;
    403409
    404410  checkGraphNodeList(G, 0);
    405411  checkGraphArcList(G, 0);
     
    555561    checkDigraphValidity<SmartDigraph>();
    556562  }
    557563  { // Checking StaticDigraph
    558     checkStaticDigraph();
     564    checkStaticDigraph<StaticDigraph>();
     565    checkStaticDigraph<CompactDigraph>();
    559566  }
    560567  { // Checking FullDigraph
    561568    checkFullDigraph(8);