lemon/lgf_reader.h
author Alpar Juttner <alpar@cs.elte.hu>
Wed, 01 Oct 2008 13:56:40 +0200
changeset 294 cbe3ec2d59d2
parent 293 47fbc814aa31
parent 291 d901321d6555
child 295 7c796c1cf1b0
permissions -rw-r--r--
Merge
     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) 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 ///\ingroup lemon_io
    20 ///\file
    21 ///\brief \ref lgf-format "LEMON Graph Format" reader.
    22 
    23 
    24 #ifndef LEMON_LGF_READER_H
    25 #define LEMON_LGF_READER_H
    26 
    27 #include <iostream>
    28 #include <fstream>
    29 #include <sstream>
    30 
    31 #include <set>
    32 #include <map>
    33 
    34 #include <lemon/assert.h>
    35 #include <lemon/core.h>
    36 
    37 #include <lemon/lgf_writer.h>
    38 
    39 #include <lemon/concept_check.h>
    40 #include <lemon/concepts/maps.h>
    41 
    42 namespace lemon {
    43 
    44   namespace _reader_bits {
    45 
    46     template <typename Value>
    47     struct DefaultConverter {
    48       Value operator()(const std::string& str) {
    49         std::istringstream is(str);
    50         Value value;
    51         if (!(is >> value)) {
    52           throw FormatError("Cannot read token");
    53         }
    54 
    55         char c;
    56         if (is >> std::ws >> c) {
    57           throw FormatError("Remaining characters in token");
    58         }
    59         return value;
    60       }
    61     };
    62 
    63     template <>
    64     struct DefaultConverter<std::string> {
    65       std::string operator()(const std::string& str) {
    66         return str;
    67       }
    68     };
    69 
    70     template <typename _Item>
    71     class MapStorageBase {
    72     public:
    73       typedef _Item Item;
    74 
    75     public:
    76       MapStorageBase() {}
    77       virtual ~MapStorageBase() {}
    78 
    79       virtual void set(const Item& item, const std::string& value) = 0;
    80 
    81     };
    82 
    83     template <typename _Item, typename _Map,
    84               typename _Converter = DefaultConverter<typename _Map::Value> >
    85     class MapStorage : public MapStorageBase<_Item> {
    86     public:
    87       typedef _Map Map;
    88       typedef _Converter Converter;
    89       typedef _Item Item;
    90 
    91     private:
    92       Map& _map;
    93       Converter _converter;
    94 
    95     public:
    96       MapStorage(Map& map, const Converter& converter = Converter())
    97         : _map(map), _converter(converter) {}
    98       virtual ~MapStorage() {}
    99 
   100       virtual void set(const Item& item ,const std::string& value) {
   101         _map.set(item, _converter(value));
   102       }
   103     };
   104 
   105     template <typename _Graph, bool _dir, typename _Map,
   106               typename _Converter = DefaultConverter<typename _Map::Value> >
   107     class GraphArcMapStorage : public MapStorageBase<typename _Graph::Edge> {
   108     public:
   109       typedef _Map Map;
   110       typedef _Converter Converter;
   111       typedef _Graph Graph;
   112       typedef typename Graph::Edge Item;
   113       static const bool dir = _dir;
   114 
   115     private:
   116       const Graph& _graph;
   117       Map& _map;
   118       Converter _converter;
   119 
   120     public:
   121       GraphArcMapStorage(const Graph& graph, Map& map,
   122                          const Converter& converter = Converter())
   123         : _graph(graph), _map(map), _converter(converter) {}
   124       virtual ~GraphArcMapStorage() {}
   125 
   126       virtual void set(const Item& item ,const std::string& value) {
   127         _map.set(_graph.direct(item, dir), _converter(value));
   128       }
   129     };
   130 
   131     class ValueStorageBase {
   132     public:
   133       ValueStorageBase() {}
   134       virtual ~ValueStorageBase() {}
   135 
   136       virtual void set(const std::string&) = 0;
   137     };
   138 
   139     template <typename _Value, typename _Converter = DefaultConverter<_Value> >
   140     class ValueStorage : public ValueStorageBase {
   141     public:
   142       typedef _Value Value;
   143       typedef _Converter Converter;
   144 
   145     private:
   146       Value& _value;
   147       Converter _converter;
   148 
   149     public:
   150       ValueStorage(Value& value, const Converter& converter = Converter())
   151         : _value(value), _converter(converter) {}
   152 
   153       virtual void set(const std::string& value) {
   154         _value = _converter(value);
   155       }
   156     };
   157 
   158     template <typename Value>
   159     struct MapLookUpConverter {
   160       const std::map<std::string, Value>& _map;
   161 
   162       MapLookUpConverter(const std::map<std::string, Value>& map)
   163         : _map(map) {}
   164 
   165       Value operator()(const std::string& str) {
   166         typename std::map<std::string, Value>::const_iterator it =
   167           _map.find(str);
   168         if (it == _map.end()) {
   169           std::ostringstream msg;
   170           msg << "Item not found: " << str;
   171           throw FormatError(msg.str());
   172         }
   173         return it->second;
   174       }
   175     };
   176 
   177     template <typename Graph>
   178     struct GraphArcLookUpConverter {
   179       const Graph& _graph;
   180       const std::map<std::string, typename Graph::Edge>& _map;
   181 
   182       GraphArcLookUpConverter(const Graph& graph,
   183                               const std::map<std::string,
   184                                              typename Graph::Edge>& map)
   185         : _graph(graph), _map(map) {}
   186 
   187       typename Graph::Arc operator()(const std::string& str) {
   188         if (str.empty() || (str[0] != '+' && str[0] != '-')) {
   189           throw FormatError("Item must start with '+' or '-'");
   190         }
   191         typename std::map<std::string, typename Graph::Edge>
   192           ::const_iterator it = _map.find(str.substr(1));
   193         if (it == _map.end()) {
   194           throw FormatError("Item not found");
   195         }
   196         return _graph.direct(it->second, str[0] == '+');
   197       }
   198     };
   199 
   200     inline bool isWhiteSpace(char c) {
   201       return c == ' ' || c == '\t' || c == '\v' ||
   202         c == '\n' || c == '\r' || c == '\f';
   203     }
   204 
   205     inline bool isOct(char c) {
   206       return '0' <= c && c <='7';
   207     }
   208 
   209     inline int valueOct(char c) {
   210       LEMON_ASSERT(isOct(c), "The character is not octal.");
   211       return c - '0';
   212     }
   213 
   214     inline bool isHex(char c) {
   215       return ('0' <= c && c <= '9') ||
   216         ('a' <= c && c <= 'z') ||
   217         ('A' <= c && c <= 'Z');
   218     }
   219 
   220     inline int valueHex(char c) {
   221       LEMON_ASSERT(isHex(c), "The character is not hexadecimal.");
   222       if ('0' <= c && c <= '9') return c - '0';
   223       if ('a' <= c && c <= 'z') return c - 'a' + 10;
   224       return c - 'A' + 10;
   225     }
   226 
   227     inline bool isIdentifierFirstChar(char c) {
   228       return ('a' <= c && c <= 'z') ||
   229         ('A' <= c && c <= 'Z') || c == '_';
   230     }
   231 
   232     inline bool isIdentifierChar(char c) {
   233       return isIdentifierFirstChar(c) ||
   234         ('0' <= c && c <= '9');
   235     }
   236 
   237     inline char readEscape(std::istream& is) {
   238       char c;
   239       if (!is.get(c))
   240         throw FormatError("Escape format error");
   241 
   242       switch (c) {
   243       case '\\':
   244         return '\\';
   245       case '\"':
   246         return '\"';
   247       case '\'':
   248         return '\'';
   249       case '\?':
   250         return '\?';
   251       case 'a':
   252         return '\a';
   253       case 'b':
   254         return '\b';
   255       case 'f':
   256         return '\f';
   257       case 'n':
   258         return '\n';
   259       case 'r':
   260         return '\r';
   261       case 't':
   262         return '\t';
   263       case 'v':
   264         return '\v';
   265       case 'x':
   266         {
   267           int code;
   268           if (!is.get(c) || !isHex(c))
   269             throw FormatError("Escape format error");
   270           else if (code = valueHex(c), !is.get(c) || !isHex(c)) is.putback(c);
   271           else code = code * 16 + valueHex(c);
   272           return code;
   273         }
   274       default:
   275         {
   276           int code;
   277           if (!isOct(c))
   278             throw FormatError("Escape format error");
   279           else if (code = valueOct(c), !is.get(c) || !isOct(c))
   280             is.putback(c);
   281           else if (code = code * 8 + valueOct(c), !is.get(c) || !isOct(c))
   282             is.putback(c);
   283           else code = code * 8 + valueOct(c);
   284           return code;
   285         }
   286       }
   287     }
   288 
   289     inline std::istream& readToken(std::istream& is, std::string& str) {
   290       std::ostringstream os;
   291 
   292       char c;
   293       is >> std::ws;
   294 
   295       if (!is.get(c))
   296         return is;
   297 
   298       if (c == '\"') {
   299         while (is.get(c) && c != '\"') {
   300           if (c == '\\')
   301             c = readEscape(is);
   302           os << c;
   303         }
   304         if (!is)
   305           throw FormatError("Quoted format error");
   306       } else {
   307         is.putback(c);
   308         while (is.get(c) && !isWhiteSpace(c)) {
   309           if (c == '\\')
   310             c = readEscape(is);
   311           os << c;
   312         }
   313         if (!is) {
   314           is.clear();
   315         } else {
   316           is.putback(c);
   317         }
   318       }
   319       str = os.str();
   320       return is;
   321     }
   322 
   323     class Section {
   324     public:
   325       virtual ~Section() {}
   326       virtual void process(std::istream& is, int& line_num) = 0;
   327     };
   328 
   329     template <typename Functor>
   330     class LineSection : public Section {
   331     private:
   332 
   333       Functor _functor;
   334 
   335     public:
   336 
   337       LineSection(const Functor& functor) : _functor(functor) {}
   338       virtual ~LineSection() {}
   339 
   340       virtual void process(std::istream& is, int& line_num) {
   341         char c;
   342         std::string line;
   343         while (is.get(c) && c != '@') {
   344           if (c == '\n') {
   345             ++line_num;
   346           } else if (c == '#') {
   347             getline(is, line);
   348             ++line_num;
   349           } else if (!isWhiteSpace(c)) {
   350             is.putback(c);
   351             getline(is, line);
   352             _functor(line);
   353             ++line_num;
   354           }
   355         }
   356         if (is) is.putback(c);
   357         else if (is.eof()) is.clear();
   358       }
   359     };
   360 
   361     template <typename Functor>
   362     class StreamSection : public Section {
   363     private:
   364 
   365       Functor _functor;
   366 
   367     public:
   368 
   369       StreamSection(const Functor& functor) : _functor(functor) {}
   370       virtual ~StreamSection() {}
   371 
   372       virtual void process(std::istream& is, int& line_num) {
   373         _functor(is, line_num);
   374         char c;
   375         std::string line;
   376         while (is.get(c) && c != '@') {
   377           if (c == '\n') {
   378             ++line_num;
   379           } else if (!isWhiteSpace(c)) {
   380             getline(is, line);
   381             ++line_num;
   382           }
   383         }
   384         if (is) is.putback(c);
   385         else if (is.eof()) is.clear();
   386       }
   387     };
   388 
   389   }
   390 
   391   template <typename Digraph>
   392   class DigraphReader;
   393 
   394   template <typename Digraph>
   395   DigraphReader<Digraph> digraphReader(Digraph& digraph,
   396                                        std::istream& is = std::cin);
   397 
   398   template <typename Digraph>
   399   DigraphReader<Digraph> digraphReader(Digraph& digraph, const std::string& fn);
   400 
   401   template <typename Digraph>
   402   DigraphReader<Digraph> digraphReader(Digraph& digraph, const char *fn);
   403 
   404   /// \ingroup lemon_io
   405   ///
   406   /// \brief \ref lgf-format "LGF" reader for directed graphs
   407   ///
   408   /// This utility reads an \ref lgf-format "LGF" file.
   409   ///
   410   /// The reading method does a batch processing. The user creates a
   411   /// reader object, then various reading rules can be added to the
   412   /// reader, and eventually the reading is executed with the \c run()
   413   /// member function. A map reading rule can be added to the reader
   414   /// with the \c nodeMap() or \c arcMap() members. An optional
   415   /// converter parameter can also be added as a standard functor
   416   /// converting from \c std::string to the value type of the map. If it
   417   /// is set, it will determine how the tokens in the file should be
   418   /// converted to the value type of the map. If the functor is not set,
   419   /// then a default conversion will be used. One map can be read into
   420   /// multiple map objects at the same time. The \c attribute(), \c
   421   /// node() and \c arc() functions are used to add attribute reading
   422   /// rules.
   423   ///
   424   ///\code
   425   /// DigraphReader<Digraph>(digraph, std::cin).
   426   ///   nodeMap("coordinates", coord_map).
   427   ///   arcMap("capacity", cap_map).
   428   ///   node("source", src).
   429   ///   node("target", trg).
   430   ///   attribute("caption", caption).
   431   ///   run();
   432   ///\endcode
   433   ///
   434   /// By default the reader uses the first section in the file of the
   435   /// proper type. If a section has an optional name, then it can be
   436   /// selected for reading by giving an optional name parameter to the
   437   /// \c nodes(), \c arcs() or \c attributes() functions.
   438   ///
   439   /// The \c useNodes() and \c useArcs() functions are used to tell the reader
   440   /// that the nodes or arcs should not be constructed (added to the
   441   /// graph) during the reading, but instead the label map of the items
   442   /// are given as a parameter of these functions. An
   443   /// application of these functions is multipass reading, which is
   444   /// important if two \c \@arcs sections must be read from the
   445   /// file. In this case the first phase would read the node set and one
   446   /// of the arc sets, while the second phase would read the second arc
   447   /// set into an \e ArcSet class (\c SmartArcSet or \c ListArcSet).
   448   /// The previously read label node map should be passed to the \c
   449   /// useNodes() functions. Another application of multipass reading when
   450   /// paths are given as a node map or an arc map.
   451   /// It is impossible to read this in
   452   /// a single pass, because the arcs are not constructed when the node
   453   /// maps are read.
   454   template <typename _Digraph>
   455   class DigraphReader {
   456   public:
   457 
   458     typedef _Digraph Digraph;
   459     TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
   460 
   461   private:
   462 
   463 
   464     std::istream* _is;
   465     bool local_is;
   466     std::string _filename;
   467 
   468     Digraph& _digraph;
   469 
   470     std::string _nodes_caption;
   471     std::string _arcs_caption;
   472     std::string _attributes_caption;
   473 
   474     typedef std::map<std::string, Node> NodeIndex;
   475     NodeIndex _node_index;
   476     typedef std::map<std::string, Arc> ArcIndex;
   477     ArcIndex _arc_index;
   478 
   479     typedef std::vector<std::pair<std::string,
   480       _reader_bits::MapStorageBase<Node>*> > NodeMaps;
   481     NodeMaps _node_maps;
   482 
   483     typedef std::vector<std::pair<std::string,
   484       _reader_bits::MapStorageBase<Arc>*> >ArcMaps;
   485     ArcMaps _arc_maps;
   486 
   487     typedef std::multimap<std::string, _reader_bits::ValueStorageBase*>
   488       Attributes;
   489     Attributes _attributes;
   490 
   491     bool _use_nodes;
   492     bool _use_arcs;
   493 
   494     bool _skip_nodes;
   495     bool _skip_arcs;
   496 
   497     int line_num;
   498     std::istringstream line;
   499 
   500   public:
   501 
   502     /// \brief Constructor
   503     ///
   504     /// Construct a directed graph reader, which reads from the given
   505     /// input stream.
   506     DigraphReader(Digraph& digraph, std::istream& is = std::cin)
   507       : _is(&is), local_is(false), _digraph(digraph),
   508         _use_nodes(false), _use_arcs(false),
   509         _skip_nodes(false), _skip_arcs(false) {}
   510 
   511     /// \brief Constructor
   512     ///
   513     /// Construct a directed graph reader, which reads from the given
   514     /// file.
   515     DigraphReader(Digraph& digraph, const std::string& fn)
   516       : _is(new std::ifstream(fn.c_str())), local_is(true),
   517         _filename(fn), _digraph(digraph),
   518         _use_nodes(false), _use_arcs(false),
   519         _skip_nodes(false), _skip_arcs(false) {
   520       if (!(*_is)) throw IoError("Cannot open file", fn);
   521     }
   522 
   523     /// \brief Constructor
   524     ///
   525     /// Construct a directed graph reader, which reads from the given
   526     /// file.
   527     DigraphReader(Digraph& digraph, const char* fn)
   528       : _is(new std::ifstream(fn)), local_is(true),
   529         _filename(fn), _digraph(digraph),
   530         _use_nodes(false), _use_arcs(false),
   531         _skip_nodes(false), _skip_arcs(false) {
   532       if (!(*_is)) throw IoError("Cannot open file", fn);
   533     }
   534 
   535     /// \brief Destructor
   536     ~DigraphReader() {
   537       for (typename NodeMaps::iterator it = _node_maps.begin();
   538            it != _node_maps.end(); ++it) {
   539         delete it->second;
   540       }
   541 
   542       for (typename ArcMaps::iterator it = _arc_maps.begin();
   543            it != _arc_maps.end(); ++it) {
   544         delete it->second;
   545       }
   546 
   547       for (typename Attributes::iterator it = _attributes.begin();
   548            it != _attributes.end(); ++it) {
   549         delete it->second;
   550       }
   551 
   552       if (local_is) {
   553         delete _is;
   554       }
   555 
   556     }
   557 
   558   private:
   559 
   560     friend DigraphReader<Digraph> digraphReader<>(Digraph& digraph,
   561                                                   std::istream& is);
   562     friend DigraphReader<Digraph> digraphReader<>(Digraph& digraph,
   563                                                   const std::string& fn);
   564     friend DigraphReader<Digraph> digraphReader<>(Digraph& digraph,
   565                                                   const char *fn);
   566 
   567     DigraphReader(DigraphReader& other)
   568       : _is(other._is), local_is(other.local_is), _digraph(other._digraph),
   569         _use_nodes(other._use_nodes), _use_arcs(other._use_arcs),
   570         _skip_nodes(other._skip_nodes), _skip_arcs(other._skip_arcs) {
   571 
   572       other._is = 0;
   573       other.local_is = false;
   574 
   575       _node_index.swap(other._node_index);
   576       _arc_index.swap(other._arc_index);
   577 
   578       _node_maps.swap(other._node_maps);
   579       _arc_maps.swap(other._arc_maps);
   580       _attributes.swap(other._attributes);
   581 
   582       _nodes_caption = other._nodes_caption;
   583       _arcs_caption = other._arcs_caption;
   584       _attributes_caption = other._attributes_caption;
   585 
   586     }
   587 
   588     DigraphReader& operator=(const DigraphReader&);
   589 
   590   public:
   591 
   592     /// \name Reading rules
   593     /// @{
   594 
   595     /// \brief Node map reading rule
   596     ///
   597     /// Add a node map reading rule to the reader.
   598     template <typename Map>
   599     DigraphReader& nodeMap(const std::string& caption, Map& map) {
   600       checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
   601       _reader_bits::MapStorageBase<Node>* storage =
   602         new _reader_bits::MapStorage<Node, Map>(map);
   603       _node_maps.push_back(std::make_pair(caption, storage));
   604       return *this;
   605     }
   606 
   607     /// \brief Node map reading rule
   608     ///
   609     /// Add a node map reading rule with specialized converter to the
   610     /// reader.
   611     template <typename Map, typename Converter>
   612     DigraphReader& nodeMap(const std::string& caption, Map& map,
   613                            const Converter& converter = Converter()) {
   614       checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
   615       _reader_bits::MapStorageBase<Node>* storage =
   616         new _reader_bits::MapStorage<Node, Map, Converter>(map, converter);
   617       _node_maps.push_back(std::make_pair(caption, storage));
   618       return *this;
   619     }
   620 
   621     /// \brief Arc map reading rule
   622     ///
   623     /// Add an arc map reading rule to the reader.
   624     template <typename Map>
   625     DigraphReader& arcMap(const std::string& caption, Map& map) {
   626       checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
   627       _reader_bits::MapStorageBase<Arc>* storage =
   628         new _reader_bits::MapStorage<Arc, Map>(map);
   629       _arc_maps.push_back(std::make_pair(caption, storage));
   630       return *this;
   631     }
   632 
   633     /// \brief Arc map reading rule
   634     ///
   635     /// Add an arc map reading rule with specialized converter to the
   636     /// reader.
   637     template <typename Map, typename Converter>
   638     DigraphReader& arcMap(const std::string& caption, Map& map,
   639                           const Converter& converter = Converter()) {
   640       checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
   641       _reader_bits::MapStorageBase<Arc>* storage =
   642         new _reader_bits::MapStorage<Arc, Map, Converter>(map, converter);
   643       _arc_maps.push_back(std::make_pair(caption, storage));
   644       return *this;
   645     }
   646 
   647     /// \brief Attribute reading rule
   648     ///
   649     /// Add an attribute reading rule to the reader.
   650     template <typename Value>
   651     DigraphReader& attribute(const std::string& caption, Value& value) {
   652       _reader_bits::ValueStorageBase* storage =
   653         new _reader_bits::ValueStorage<Value>(value);
   654       _attributes.insert(std::make_pair(caption, storage));
   655       return *this;
   656     }
   657 
   658     /// \brief Attribute reading rule
   659     ///
   660     /// Add an attribute reading rule with specialized converter to the
   661     /// reader.
   662     template <typename Value, typename Converter>
   663     DigraphReader& attribute(const std::string& caption, Value& value,
   664                              const Converter& converter = Converter()) {
   665       _reader_bits::ValueStorageBase* storage =
   666         new _reader_bits::ValueStorage<Value, Converter>(value, converter);
   667       _attributes.insert(std::make_pair(caption, storage));
   668       return *this;
   669     }
   670 
   671     /// \brief Node reading rule
   672     ///
   673     /// Add a node reading rule to reader.
   674     DigraphReader& node(const std::string& caption, Node& node) {
   675       typedef _reader_bits::MapLookUpConverter<Node> Converter;
   676       Converter converter(_node_index);
   677       _reader_bits::ValueStorageBase* storage =
   678         new _reader_bits::ValueStorage<Node, Converter>(node, converter);
   679       _attributes.insert(std::make_pair(caption, storage));
   680       return *this;
   681     }
   682 
   683     /// \brief Arc reading rule
   684     ///
   685     /// Add an arc reading rule to reader.
   686     DigraphReader& arc(const std::string& caption, Arc& arc) {
   687       typedef _reader_bits::MapLookUpConverter<Arc> Converter;
   688       Converter converter(_arc_index);
   689       _reader_bits::ValueStorageBase* storage =
   690         new _reader_bits::ValueStorage<Arc, Converter>(arc, converter);
   691       _attributes.insert(std::make_pair(caption, storage));
   692       return *this;
   693     }
   694 
   695     /// @}
   696 
   697     /// \name Select section by name
   698     /// @{
   699 
   700     /// \brief Set \c \@nodes section to be read
   701     ///
   702     /// Set \c \@nodes section to be read
   703     DigraphReader& nodes(const std::string& caption) {
   704       _nodes_caption = caption;
   705       return *this;
   706     }
   707 
   708     /// \brief Set \c \@arcs section to be read
   709     ///
   710     /// Set \c \@arcs section to be read
   711     DigraphReader& arcs(const std::string& caption) {
   712       _arcs_caption = caption;
   713       return *this;
   714     }
   715 
   716     /// \brief Set \c \@attributes section to be read
   717     ///
   718     /// Set \c \@attributes section to be read
   719     DigraphReader& attributes(const std::string& caption) {
   720       _attributes_caption = caption;
   721       return *this;
   722     }
   723 
   724     /// @}
   725 
   726     /// \name Using previously constructed node or arc set
   727     /// @{
   728 
   729     /// \brief Use previously constructed node set
   730     ///
   731     /// Use previously constructed node set, and specify the node
   732     /// label map.
   733     template <typename Map>
   734     DigraphReader& useNodes(const Map& map) {
   735       checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
   736       LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
   737       _use_nodes = true;
   738       _writer_bits::DefaultConverter<typename Map::Value> converter;
   739       for (NodeIt n(_digraph); n != INVALID; ++n) {
   740         _node_index.insert(std::make_pair(converter(map[n]), n));
   741       }
   742       return *this;
   743     }
   744 
   745     /// \brief Use previously constructed node set
   746     ///
   747     /// Use previously constructed node set, and specify the node
   748     /// label map and a functor which converts the label map values to
   749     /// \c std::string.
   750     template <typename Map, typename Converter>
   751     DigraphReader& useNodes(const Map& map,
   752                             const Converter& converter = Converter()) {
   753       checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
   754       LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
   755       _use_nodes = true;
   756       for (NodeIt n(_digraph); n != INVALID; ++n) {
   757         _node_index.insert(std::make_pair(converter(map[n]), n));
   758       }
   759       return *this;
   760     }
   761 
   762     /// \brief Use previously constructed arc set
   763     ///
   764     /// Use previously constructed arc set, and specify the arc
   765     /// label map.
   766     template <typename Map>
   767     DigraphReader& useArcs(const Map& map) {
   768       checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
   769       LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member");
   770       _use_arcs = true;
   771       _writer_bits::DefaultConverter<typename Map::Value> converter;
   772       for (ArcIt a(_digraph); a != INVALID; ++a) {
   773         _arc_index.insert(std::make_pair(converter(map[a]), a));
   774       }
   775       return *this;
   776     }
   777 
   778     /// \brief Use previously constructed arc set
   779     ///
   780     /// Use previously constructed arc set, and specify the arc
   781     /// label map and a functor which converts the label map values to
   782     /// \c std::string.
   783     template <typename Map, typename Converter>
   784     DigraphReader& useArcs(const Map& map,
   785                            const Converter& converter = Converter()) {
   786       checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
   787       LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member");
   788       _use_arcs = true;
   789       for (ArcIt a(_digraph); a != INVALID; ++a) {
   790         _arc_index.insert(std::make_pair(converter(map[a]), a));
   791       }
   792       return *this;
   793     }
   794 
   795     /// \brief Skips the reading of node section
   796     ///
   797     /// Omit the reading of the node section. This implies that each node
   798     /// map reading rule will be abandoned, and the nodes of the graph
   799     /// will not be constructed, which usually cause that the arc set
   800     /// could not be read due to lack of node name resolving.
   801     /// Therefore \c skipArcs() function should also be used, or
   802     /// \c useNodes() should be used to specify the label of the nodes.
   803     DigraphReader& skipNodes() {
   804       LEMON_ASSERT(!_skip_nodes, "Skip nodes already set");
   805       _skip_nodes = true;
   806       return *this;
   807     }
   808 
   809     /// \brief Skips the reading of arc section
   810     ///
   811     /// Omit the reading of the arc section. This implies that each arc
   812     /// map reading rule will be abandoned, and the arcs of the graph
   813     /// will not be constructed.
   814     DigraphReader& skipArcs() {
   815       LEMON_ASSERT(!_skip_arcs, "Skip arcs already set");
   816       _skip_arcs = true;
   817       return *this;
   818     }
   819 
   820     /// @}
   821 
   822   private:
   823 
   824     bool readLine() {
   825       std::string str;
   826       while(++line_num, std::getline(*_is, str)) {
   827         line.clear(); line.str(str);
   828         char c;
   829         if (line >> std::ws >> c && c != '#') {
   830           line.putback(c);
   831           return true;
   832         }
   833       }
   834       return false;
   835     }
   836 
   837     bool readSuccess() {
   838       return static_cast<bool>(*_is);
   839     }
   840 
   841     void skipSection() {
   842       char c;
   843       while (readSuccess() && line >> c && c != '@') {
   844         readLine();
   845       }
   846       line.putback(c);
   847     }
   848 
   849     void readNodes() {
   850 
   851       std::vector<int> map_index(_node_maps.size());
   852       int map_num, label_index;
   853 
   854       char c;
   855       if (!readLine() || !(line >> c) || c == '@') {
   856         if (readSuccess() && line) line.putback(c);
   857         if (!_node_maps.empty())
   858           throw FormatError("Cannot find map names");
   859         return;
   860       }
   861       line.putback(c);
   862 
   863       {
   864         std::map<std::string, int> maps;
   865 
   866         std::string map;
   867         int index = 0;
   868         while (_reader_bits::readToken(line, map)) {
   869           if (maps.find(map) != maps.end()) {
   870             std::ostringstream msg;
   871             msg << "Multiple occurence of node map: " << map;
   872             throw FormatError(msg.str());
   873           }
   874           maps.insert(std::make_pair(map, index));
   875           ++index;
   876         }
   877 
   878         for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
   879           std::map<std::string, int>::iterator jt =
   880             maps.find(_node_maps[i].first);
   881           if (jt == maps.end()) {
   882             std::ostringstream msg;
   883             msg << "Map not found: " << _node_maps[i].first;
   884             throw FormatError(msg.str());
   885           }
   886           map_index[i] = jt->second;
   887         }
   888 
   889         {
   890           std::map<std::string, int>::iterator jt = maps.find("label");
   891           if (jt != maps.end()) {
   892             label_index = jt->second;
   893           } else {
   894             label_index = -1;
   895           }
   896         }
   897         map_num = maps.size();
   898       }
   899 
   900       while (readLine() && line >> c && c != '@') {
   901         line.putback(c);
   902 
   903         std::vector<std::string> tokens(map_num);
   904         for (int i = 0; i < map_num; ++i) {
   905           if (!_reader_bits::readToken(line, tokens[i])) {
   906             std::ostringstream msg;
   907             msg << "Column not found (" << i + 1 << ")";
   908             throw FormatError(msg.str());
   909           }
   910         }
   911         if (line >> std::ws >> c)
   912           throw FormatError("Extra character at the end of line");
   913 
   914         Node n;
   915         if (!_use_nodes) {
   916           n = _digraph.addNode();
   917           if (label_index != -1)
   918             _node_index.insert(std::make_pair(tokens[label_index], n));
   919         } else {
   920           if (label_index == -1)
   921             throw FormatError("Label map not found");
   922           typename std::map<std::string, Node>::iterator it =
   923             _node_index.find(tokens[label_index]);
   924           if (it == _node_index.end()) {
   925             std::ostringstream msg;
   926             msg << "Node with label not found: " << tokens[label_index];
   927             throw FormatError(msg.str());
   928           }
   929           n = it->second;
   930         }
   931 
   932         for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
   933           _node_maps[i].second->set(n, tokens[map_index[i]]);
   934         }
   935 
   936       }
   937       if (readSuccess()) {
   938         line.putback(c);
   939       }
   940     }
   941 
   942     void readArcs() {
   943 
   944       std::vector<int> map_index(_arc_maps.size());
   945       int map_num, label_index;
   946 
   947       char c;
   948       if (!readLine() || !(line >> c) || c == '@') {
   949         if (readSuccess() && line) line.putback(c);
   950         if (!_arc_maps.empty())
   951           throw FormatError("Cannot find map names");
   952         return;
   953       }
   954       line.putback(c);
   955 
   956       {
   957         std::map<std::string, int> maps;
   958 
   959         std::string map;
   960         int index = 0;
   961         while (_reader_bits::readToken(line, map)) {
   962           if (maps.find(map) != maps.end()) {
   963             std::ostringstream msg;
   964             msg << "Multiple occurence of arc map: " << map;
   965             throw FormatError(msg.str());
   966           }
   967           maps.insert(std::make_pair(map, index));
   968           ++index;
   969         }
   970 
   971         for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) {
   972           std::map<std::string, int>::iterator jt =
   973             maps.find(_arc_maps[i].first);
   974           if (jt == maps.end()) {
   975             std::ostringstream msg;
   976             msg << "Map not found: " << _arc_maps[i].first;
   977             throw FormatError(msg.str());
   978           }
   979           map_index[i] = jt->second;
   980         }
   981 
   982         {
   983           std::map<std::string, int>::iterator jt = maps.find("label");
   984           if (jt != maps.end()) {
   985             label_index = jt->second;
   986           } else {
   987             label_index = -1;
   988           }
   989         }
   990         map_num = maps.size();
   991       }
   992 
   993       while (readLine() && line >> c && c != '@') {
   994         line.putback(c);
   995 
   996         std::string source_token;
   997         std::string target_token;
   998 
   999         if (!_reader_bits::readToken(line, source_token))
  1000           throw FormatError("Source not found");
  1001 
  1002         if (!_reader_bits::readToken(line, target_token))
  1003           throw FormatError("Target not found");
  1004 
  1005         std::vector<std::string> tokens(map_num);
  1006         for (int i = 0; i < map_num; ++i) {
  1007           if (!_reader_bits::readToken(line, tokens[i])) {
  1008             std::ostringstream msg;
  1009             msg << "Column not found (" << i + 1 << ")";
  1010             throw FormatError(msg.str());
  1011           }
  1012         }
  1013         if (line >> std::ws >> c)
  1014           throw FormatError("Extra character at the end of line");
  1015 
  1016         Arc a;
  1017         if (!_use_arcs) {
  1018 
  1019           typename NodeIndex::iterator it;
  1020 
  1021           it = _node_index.find(source_token);
  1022           if (it == _node_index.end()) {
  1023             std::ostringstream msg;
  1024             msg << "Item not found: " << source_token;
  1025             throw FormatError(msg.str());
  1026           }
  1027           Node source = it->second;
  1028 
  1029           it = _node_index.find(target_token);
  1030           if (it == _node_index.end()) {
  1031             std::ostringstream msg;
  1032             msg << "Item not found: " << target_token;
  1033             throw FormatError(msg.str());
  1034           }
  1035           Node target = it->second;
  1036 
  1037           a = _digraph.addArc(source, target);
  1038           if (label_index != -1)
  1039             _arc_index.insert(std::make_pair(tokens[label_index], a));
  1040         } else {
  1041           if (label_index == -1)
  1042             throw FormatError("Label map not found");
  1043           typename std::map<std::string, Arc>::iterator it =
  1044             _arc_index.find(tokens[label_index]);
  1045           if (it == _arc_index.end()) {
  1046             std::ostringstream msg;
  1047             msg << "Arc with label not found: " << tokens[label_index];
  1048             throw FormatError(msg.str());
  1049           }
  1050           a = it->second;
  1051         }
  1052 
  1053         for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) {
  1054           _arc_maps[i].second->set(a, tokens[map_index[i]]);
  1055         }
  1056 
  1057       }
  1058       if (readSuccess()) {
  1059         line.putback(c);
  1060       }
  1061     }
  1062 
  1063     void readAttributes() {
  1064 
  1065       std::set<std::string> read_attr;
  1066 
  1067       char c;
  1068       while (readLine() && line >> c && c != '@') {
  1069         line.putback(c);
  1070 
  1071         std::string attr, token;
  1072         if (!_reader_bits::readToken(line, attr))
  1073           throw FormatError("Attribute name not found");
  1074         if (!_reader_bits::readToken(line, token))
  1075           throw FormatError("Attribute value not found");
  1076         if (line >> c)
  1077           throw FormatError("Extra character at the end of line");
  1078 
  1079         {
  1080           std::set<std::string>::iterator it = read_attr.find(attr);
  1081           if (it != read_attr.end()) {
  1082             std::ostringstream msg;
  1083             msg << "Multiple occurence of attribute: " << attr;
  1084             throw FormatError(msg.str());
  1085           }
  1086           read_attr.insert(attr);
  1087         }
  1088 
  1089         {
  1090           typename Attributes::iterator it = _attributes.lower_bound(attr);
  1091           while (it != _attributes.end() && it->first == attr) {
  1092             it->second->set(token);
  1093             ++it;
  1094           }
  1095         }
  1096 
  1097       }
  1098       if (readSuccess()) {
  1099         line.putback(c);
  1100       }
  1101       for (typename Attributes::iterator it = _attributes.begin();
  1102            it != _attributes.end(); ++it) {
  1103         if (read_attr.find(it->first) == read_attr.end()) {
  1104           std::ostringstream msg;
  1105           msg << "Attribute not found: " << it->first;
  1106           throw FormatError(msg.str());
  1107         }
  1108       }
  1109     }
  1110 
  1111   public:
  1112 
  1113     /// \name Execution of the reader
  1114     /// @{
  1115 
  1116     /// \brief Start the batch processing
  1117     ///
  1118     /// This function starts the batch processing
  1119     void run() {
  1120       LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
  1121 
  1122       bool nodes_done = _skip_nodes;
  1123       bool arcs_done = _skip_arcs;
  1124       bool attributes_done = false;
  1125 
  1126       line_num = 0;
  1127       readLine();
  1128       skipSection();
  1129 
  1130       while (readSuccess()) {
  1131         try {
  1132           char c;
  1133           std::string section, caption;
  1134           line >> c;
  1135           _reader_bits::readToken(line, section);
  1136           _reader_bits::readToken(line, caption);
  1137 
  1138           if (line >> c)
  1139             throw FormatError("Extra character at the end of line");
  1140 
  1141           if (section == "nodes" && !nodes_done) {
  1142             if (_nodes_caption.empty() || _nodes_caption == caption) {
  1143               readNodes();
  1144               nodes_done = true;
  1145             }
  1146           } else if ((section == "arcs" || section == "edges") &&
  1147                      !arcs_done) {
  1148             if (_arcs_caption.empty() || _arcs_caption == caption) {
  1149               readArcs();
  1150               arcs_done = true;
  1151             }
  1152           } else if (section == "attributes" && !attributes_done) {
  1153             if (_attributes_caption.empty() || _attributes_caption == caption) {
  1154               readAttributes();
  1155               attributes_done = true;
  1156             }
  1157           } else {
  1158             readLine();
  1159             skipSection();
  1160           }
  1161         } catch (FormatError& error) {
  1162           error.line(line_num);
  1163           error.file(_filename);
  1164           throw;
  1165         }
  1166       }
  1167 
  1168       if (!nodes_done) {
  1169         throw FormatError("Section @nodes not found");
  1170       }
  1171 
  1172       if (!arcs_done) {
  1173         throw FormatError("Section @arcs not found");
  1174       }
  1175 
  1176       if (!attributes_done && !_attributes.empty()) {
  1177         throw FormatError("Section @attributes not found");
  1178       }
  1179 
  1180     }
  1181 
  1182     /// @}
  1183 
  1184   };
  1185 
  1186   /// \brief Return a \ref DigraphReader class
  1187   ///
  1188   /// This function just returns a \ref DigraphReader class.
  1189   /// \relates DigraphReader
  1190   template <typename Digraph>
  1191   DigraphReader<Digraph> digraphReader(Digraph& digraph,
  1192                                        std::istream& is = std::cin) {
  1193     DigraphReader<Digraph> tmp(digraph, is);
  1194     return tmp;
  1195   }
  1196 
  1197   /// \brief Return a \ref DigraphReader class
  1198   ///
  1199   /// This function just returns a \ref DigraphReader class.
  1200   /// \relates DigraphReader
  1201   template <typename Digraph>
  1202   DigraphReader<Digraph> digraphReader(Digraph& digraph,
  1203                                        const std::string& fn) {
  1204     DigraphReader<Digraph> tmp(digraph, fn);
  1205     return tmp;
  1206   }
  1207 
  1208   /// \brief Return a \ref DigraphReader class
  1209   ///
  1210   /// This function just returns a \ref DigraphReader class.
  1211   /// \relates DigraphReader
  1212   template <typename Digraph>
  1213   DigraphReader<Digraph> digraphReader(Digraph& digraph, const char* fn) {
  1214     DigraphReader<Digraph> tmp(digraph, fn);
  1215     return tmp;
  1216   }
  1217 
  1218   template <typename Graph>
  1219   class GraphReader;
  1220 
  1221   template <typename Graph>
  1222   GraphReader<Graph> graphReader(Graph& graph,
  1223                                  std::istream& is = std::cin);
  1224 
  1225   template <typename Graph>
  1226   GraphReader<Graph> graphReader(Graph& graph, const std::string& fn);
  1227 
  1228   template <typename Graph>
  1229   GraphReader<Graph> graphReader(Graph& graph, const char *fn);
  1230 
  1231   /// \ingroup lemon_io
  1232   ///
  1233   /// \brief \ref lgf-format "LGF" reader for undirected graphs
  1234   ///
  1235   /// This utility reads an \ref lgf-format "LGF" file.
  1236   ///
  1237   /// It can be used almost the same way as \c DigraphReader.
  1238   /// The only difference is that this class can handle edges and
  1239   /// edge maps as well as arcs and arc maps.
  1240   ///
  1241   /// The columns in the \c \@edges (or \c \@arcs) section are the
  1242   /// edge maps. However, if there are two maps with the same name
  1243   /// prefixed with \c '+' and \c '-', then these can be read into an
  1244   /// arc map.  Similarly, an attribute can be read into an arc, if
  1245   /// it's value is an edge label prefixed with \c '+' or \c '-'.
  1246   template <typename _Graph>
  1247   class GraphReader {
  1248   public:
  1249 
  1250     typedef _Graph Graph;
  1251     TEMPLATE_GRAPH_TYPEDEFS(Graph);
  1252 
  1253   private:
  1254 
  1255     std::istream* _is;
  1256     bool local_is;
  1257     std::string _filename;
  1258 
  1259     Graph& _graph;
  1260 
  1261     std::string _nodes_caption;
  1262     std::string _edges_caption;
  1263     std::string _attributes_caption;
  1264 
  1265     typedef std::map<std::string, Node> NodeIndex;
  1266     NodeIndex _node_index;
  1267     typedef std::map<std::string, Edge> EdgeIndex;
  1268     EdgeIndex _edge_index;
  1269 
  1270     typedef std::vector<std::pair<std::string,
  1271       _reader_bits::MapStorageBase<Node>*> > NodeMaps;
  1272     NodeMaps _node_maps;
  1273 
  1274     typedef std::vector<std::pair<std::string,
  1275       _reader_bits::MapStorageBase<Edge>*> > EdgeMaps;
  1276     EdgeMaps _edge_maps;
  1277 
  1278     typedef std::multimap<std::string, _reader_bits::ValueStorageBase*>
  1279       Attributes;
  1280     Attributes _attributes;
  1281 
  1282     bool _use_nodes;
  1283     bool _use_edges;
  1284 
  1285     bool _skip_nodes;
  1286     bool _skip_edges;
  1287 
  1288     int line_num;
  1289     std::istringstream line;
  1290 
  1291   public:
  1292 
  1293     /// \brief Constructor
  1294     ///
  1295     /// Construct an undirected graph reader, which reads from the given
  1296     /// input stream.
  1297     GraphReader(Graph& graph, std::istream& is = std::cin)
  1298       : _is(&is), local_is(false), _graph(graph),
  1299         _use_nodes(false), _use_edges(false),
  1300         _skip_nodes(false), _skip_edges(false) {}
  1301 
  1302     /// \brief Constructor
  1303     ///
  1304     /// Construct an undirected graph reader, which reads from the given
  1305     /// file.
  1306     GraphReader(Graph& graph, const std::string& fn)
  1307       : _is(new std::ifstream(fn.c_str())), local_is(true),
  1308         _filename(fn), _graph(graph),
  1309         _use_nodes(false), _use_edges(false),
  1310         _skip_nodes(false), _skip_edges(false) {
  1311       if (!(*_is)) throw IoError("Cannot open file", fn);
  1312     }
  1313 
  1314     /// \brief Constructor
  1315     ///
  1316     /// Construct an undirected graph reader, which reads from the given
  1317     /// file.
  1318     GraphReader(Graph& graph, const char* fn)
  1319       : _is(new std::ifstream(fn)), local_is(true),
  1320         _filename(fn), _graph(graph),
  1321         _use_nodes(false), _use_edges(false),
  1322         _skip_nodes(false), _skip_edges(false) {
  1323       if (!(*_is)) throw IoError("Cannot open file", fn);
  1324     }
  1325 
  1326     /// \brief Destructor
  1327     ~GraphReader() {
  1328       for (typename NodeMaps::iterator it = _node_maps.begin();
  1329            it != _node_maps.end(); ++it) {
  1330         delete it->second;
  1331       }
  1332 
  1333       for (typename EdgeMaps::iterator it = _edge_maps.begin();
  1334            it != _edge_maps.end(); ++it) {
  1335         delete it->second;
  1336       }
  1337 
  1338       for (typename Attributes::iterator it = _attributes.begin();
  1339            it != _attributes.end(); ++it) {
  1340         delete it->second;
  1341       }
  1342 
  1343       if (local_is) {
  1344         delete _is;
  1345       }
  1346 
  1347     }
  1348 
  1349   private:
  1350     friend GraphReader<Graph> graphReader<>(Graph& graph, std::istream& is);
  1351     friend GraphReader<Graph> graphReader<>(Graph& graph,
  1352                                             const std::string& fn);
  1353     friend GraphReader<Graph> graphReader<>(Graph& graph, const char *fn);
  1354 
  1355     GraphReader(GraphReader& other)
  1356       : _is(other._is), local_is(other.local_is), _graph(other._graph),
  1357         _use_nodes(other._use_nodes), _use_edges(other._use_edges),
  1358         _skip_nodes(other._skip_nodes), _skip_edges(other._skip_edges) {
  1359 
  1360       other._is = 0;
  1361       other.local_is = false;
  1362 
  1363       _node_index.swap(other._node_index);
  1364       _edge_index.swap(other._edge_index);
  1365 
  1366       _node_maps.swap(other._node_maps);
  1367       _edge_maps.swap(other._edge_maps);
  1368       _attributes.swap(other._attributes);
  1369 
  1370       _nodes_caption = other._nodes_caption;
  1371       _edges_caption = other._edges_caption;
  1372       _attributes_caption = other._attributes_caption;
  1373 
  1374     }
  1375 
  1376     GraphReader& operator=(const GraphReader&);
  1377 
  1378   public:
  1379 
  1380     /// \name Reading rules
  1381     /// @{
  1382 
  1383     /// \brief Node map reading rule
  1384     ///
  1385     /// Add a node map reading rule to the reader.
  1386     template <typename Map>
  1387     GraphReader& nodeMap(const std::string& caption, Map& map) {
  1388       checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
  1389       _reader_bits::MapStorageBase<Node>* storage =
  1390         new _reader_bits::MapStorage<Node, Map>(map);
  1391       _node_maps.push_back(std::make_pair(caption, storage));
  1392       return *this;
  1393     }
  1394 
  1395     /// \brief Node map reading rule
  1396     ///
  1397     /// Add a node map reading rule with specialized converter to the
  1398     /// reader.
  1399     template <typename Map, typename Converter>
  1400     GraphReader& nodeMap(const std::string& caption, Map& map,
  1401                            const Converter& converter = Converter()) {
  1402       checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
  1403       _reader_bits::MapStorageBase<Node>* storage =
  1404         new _reader_bits::MapStorage<Node, Map, Converter>(map, converter);
  1405       _node_maps.push_back(std::make_pair(caption, storage));
  1406       return *this;
  1407     }
  1408 
  1409     /// \brief Edge map reading rule
  1410     ///
  1411     /// Add an edge map reading rule to the reader.
  1412     template <typename Map>
  1413     GraphReader& edgeMap(const std::string& caption, Map& map) {
  1414       checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>();
  1415       _reader_bits::MapStorageBase<Edge>* storage =
  1416         new _reader_bits::MapStorage<Edge, Map>(map);
  1417       _edge_maps.push_back(std::make_pair(caption, storage));
  1418       return *this;
  1419     }
  1420 
  1421     /// \brief Edge map reading rule
  1422     ///
  1423     /// Add an edge map reading rule with specialized converter to the
  1424     /// reader.
  1425     template <typename Map, typename Converter>
  1426     GraphReader& edgeMap(const std::string& caption, Map& map,
  1427                           const Converter& converter = Converter()) {
  1428       checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>();
  1429       _reader_bits::MapStorageBase<Edge>* storage =
  1430         new _reader_bits::MapStorage<Edge, Map, Converter>(map, converter);
  1431       _edge_maps.push_back(std::make_pair(caption, storage));
  1432       return *this;
  1433     }
  1434 
  1435     /// \brief Arc map reading rule
  1436     ///
  1437     /// Add an arc map reading rule to the reader.
  1438     template <typename Map>
  1439     GraphReader& arcMap(const std::string& caption, Map& map) {
  1440       checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
  1441       _reader_bits::MapStorageBase<Edge>* forward_storage =
  1442         new _reader_bits::GraphArcMapStorage<Graph, true, Map>(_graph, map);
  1443       _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
  1444       _reader_bits::MapStorageBase<Edge>* backward_storage =
  1445         new _reader_bits::GraphArcMapStorage<Graph, false, Map>(_graph, map);
  1446       _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
  1447       return *this;
  1448     }
  1449 
  1450     /// \brief Arc map reading rule
  1451     ///
  1452     /// Add an arc map reading rule with specialized converter to the
  1453     /// reader.
  1454     template <typename Map, typename Converter>
  1455     GraphReader& arcMap(const std::string& caption, Map& map,
  1456                           const Converter& converter = Converter()) {
  1457       checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
  1458       _reader_bits::MapStorageBase<Edge>* forward_storage =
  1459         new _reader_bits::GraphArcMapStorage<Graph, true, Map, Converter>
  1460         (_graph, map, converter);
  1461       _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
  1462       _reader_bits::MapStorageBase<Edge>* backward_storage =
  1463         new _reader_bits::GraphArcMapStorage<Graph, false, Map, Converter>
  1464         (_graph, map, converter);
  1465       _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
  1466       return *this;
  1467     }
  1468 
  1469     /// \brief Attribute reading rule
  1470     ///
  1471     /// Add an attribute reading rule to the reader.
  1472     template <typename Value>
  1473     GraphReader& attribute(const std::string& caption, Value& value) {
  1474       _reader_bits::ValueStorageBase* storage =
  1475         new _reader_bits::ValueStorage<Value>(value);
  1476       _attributes.insert(std::make_pair(caption, storage));
  1477       return *this;
  1478     }
  1479 
  1480     /// \brief Attribute reading rule
  1481     ///
  1482     /// Add an attribute reading rule with specialized converter to the
  1483     /// reader.
  1484     template <typename Value, typename Converter>
  1485     GraphReader& attribute(const std::string& caption, Value& value,
  1486                              const Converter& converter = Converter()) {
  1487       _reader_bits::ValueStorageBase* storage =
  1488         new _reader_bits::ValueStorage<Value, Converter>(value, converter);
  1489       _attributes.insert(std::make_pair(caption, storage));
  1490       return *this;
  1491     }
  1492 
  1493     /// \brief Node reading rule
  1494     ///
  1495     /// Add a node reading rule to reader.
  1496     GraphReader& node(const std::string& caption, Node& node) {
  1497       typedef _reader_bits::MapLookUpConverter<Node> Converter;
  1498       Converter converter(_node_index);
  1499       _reader_bits::ValueStorageBase* storage =
  1500         new _reader_bits::ValueStorage<Node, Converter>(node, converter);
  1501       _attributes.insert(std::make_pair(caption, storage));
  1502       return *this;
  1503     }
  1504 
  1505     /// \brief Edge reading rule
  1506     ///
  1507     /// Add an edge reading rule to reader.
  1508     GraphReader& edge(const std::string& caption, Edge& edge) {
  1509       typedef _reader_bits::MapLookUpConverter<Edge> Converter;
  1510       Converter converter(_edge_index);
  1511       _reader_bits::ValueStorageBase* storage =
  1512         new _reader_bits::ValueStorage<Edge, Converter>(edge, converter);
  1513       _attributes.insert(std::make_pair(caption, storage));
  1514       return *this;
  1515     }
  1516 
  1517     /// \brief Arc reading rule
  1518     ///
  1519     /// Add an arc reading rule to reader.
  1520     GraphReader& arc(const std::string& caption, Arc& arc) {
  1521       typedef _reader_bits::GraphArcLookUpConverter<Graph> Converter;
  1522       Converter converter(_graph, _edge_index);
  1523       _reader_bits::ValueStorageBase* storage =
  1524         new _reader_bits::ValueStorage<Arc, Converter>(arc, converter);
  1525       _attributes.insert(std::make_pair(caption, storage));
  1526       return *this;
  1527     }
  1528 
  1529     /// @}
  1530 
  1531     /// \name Select section by name
  1532     /// @{
  1533 
  1534     /// \brief Set \c \@nodes section to be read
  1535     ///
  1536     /// Set \c \@nodes section to be read.
  1537     GraphReader& nodes(const std::string& caption) {
  1538       _nodes_caption = caption;
  1539       return *this;
  1540     }
  1541 
  1542     /// \brief Set \c \@edges section to be read
  1543     ///
  1544     /// Set \c \@edges section to be read.
  1545     GraphReader& edges(const std::string& caption) {
  1546       _edges_caption = caption;
  1547       return *this;
  1548     }
  1549 
  1550     /// \brief Set \c \@attributes section to be read
  1551     ///
  1552     /// Set \c \@attributes section to be read.
  1553     GraphReader& attributes(const std::string& caption) {
  1554       _attributes_caption = caption;
  1555       return *this;
  1556     }
  1557 
  1558     /// @}
  1559 
  1560     /// \name Using previously constructed node or edge set
  1561     /// @{
  1562 
  1563     /// \brief Use previously constructed node set
  1564     ///
  1565     /// Use previously constructed node set, and specify the node
  1566     /// label map.
  1567     template <typename Map>
  1568     GraphReader& useNodes(const Map& map) {
  1569       checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
  1570       LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
  1571       _use_nodes = true;
  1572       _writer_bits::DefaultConverter<typename Map::Value> converter;
  1573       for (NodeIt n(_graph); n != INVALID; ++n) {
  1574         _node_index.insert(std::make_pair(converter(map[n]), n));
  1575       }
  1576       return *this;
  1577     }
  1578 
  1579     /// \brief Use previously constructed node set
  1580     ///
  1581     /// Use previously constructed node set, and specify the node
  1582     /// label map and a functor which converts the label map values to
  1583     /// \c std::string.
  1584     template <typename Map, typename Converter>
  1585     GraphReader& useNodes(const Map& map,
  1586                             const Converter& converter = Converter()) {
  1587       checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
  1588       LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
  1589       _use_nodes = true;
  1590       for (NodeIt n(_graph); n != INVALID; ++n) {
  1591         _node_index.insert(std::make_pair(converter(map[n]), n));
  1592       }
  1593       return *this;
  1594     }
  1595 
  1596     /// \brief Use previously constructed edge set
  1597     ///
  1598     /// Use previously constructed edge set, and specify the edge
  1599     /// label map.
  1600     template <typename Map>
  1601     GraphReader& useEdges(const Map& map) {
  1602       checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
  1603       LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member");
  1604       _use_edges = true;
  1605       _writer_bits::DefaultConverter<typename Map::Value> converter;
  1606       for (EdgeIt a(_graph); a != INVALID; ++a) {
  1607         _edge_index.insert(std::make_pair(converter(map[a]), a));
  1608       }
  1609       return *this;
  1610     }
  1611 
  1612     /// \brief Use previously constructed edge set
  1613     ///
  1614     /// Use previously constructed edge set, and specify the edge
  1615     /// label map and a functor which converts the label map values to
  1616     /// \c std::string.
  1617     template <typename Map, typename Converter>
  1618     GraphReader& useEdges(const Map& map,
  1619                             const Converter& converter = Converter()) {
  1620       checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
  1621       LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member");
  1622       _use_edges = true;
  1623       for (EdgeIt a(_graph); a != INVALID; ++a) {
  1624         _edge_index.insert(std::make_pair(converter(map[a]), a));
  1625       }
  1626       return *this;
  1627     }
  1628 
  1629     /// \brief Skip the reading of node section
  1630     ///
  1631     /// Omit the reading of the node section. This implies that each node
  1632     /// map reading rule will be abandoned, and the nodes of the graph
  1633     /// will not be constructed, which usually cause that the edge set
  1634     /// could not be read due to lack of node name
  1635     /// could not be read due to lack of node name resolving.
  1636     /// Therefore \c skipEdges() function should also be used, or
  1637     /// \c useNodes() should be used to specify the label of the nodes.
  1638     GraphReader& skipNodes() {
  1639       LEMON_ASSERT(!_skip_nodes, "Skip nodes already set");
  1640       _skip_nodes = true;
  1641       return *this;
  1642     }
  1643 
  1644     /// \brief Skip the reading of edge section
  1645     ///
  1646     /// Omit the reading of the edge section. This implies that each edge
  1647     /// map reading rule will be abandoned, and the edges of the graph
  1648     /// will not be constructed.
  1649     GraphReader& skipEdges() {
  1650       LEMON_ASSERT(!_skip_edges, "Skip edges already set");
  1651       _skip_edges = true;
  1652       return *this;
  1653     }
  1654 
  1655     /// @}
  1656 
  1657   private:
  1658 
  1659     bool readLine() {
  1660       std::string str;
  1661       while(++line_num, std::getline(*_is, str)) {
  1662         line.clear(); line.str(str);
  1663         char c;
  1664         if (line >> std::ws >> c && c != '#') {
  1665           line.putback(c);
  1666           return true;
  1667         }
  1668       }
  1669       return false;
  1670     }
  1671 
  1672     bool readSuccess() {
  1673       return static_cast<bool>(*_is);
  1674     }
  1675 
  1676     void skipSection() {
  1677       char c;
  1678       while (readSuccess() && line >> c && c != '@') {
  1679         readLine();
  1680       }
  1681       line.putback(c);
  1682     }
  1683 
  1684     void readNodes() {
  1685 
  1686       std::vector<int> map_index(_node_maps.size());
  1687       int map_num, label_index;
  1688 
  1689       char c;
  1690       if (!readLine() || !(line >> c) || c == '@') {
  1691         if (readSuccess() && line) line.putback(c);
  1692         if (!_node_maps.empty())
  1693           throw FormatError("Cannot find map names");
  1694         return;
  1695       }
  1696       line.putback(c);
  1697 
  1698       {
  1699         std::map<std::string, int> maps;
  1700 
  1701         std::string map;
  1702         int index = 0;
  1703         while (_reader_bits::readToken(line, map)) {
  1704           if (maps.find(map) != maps.end()) {
  1705             std::ostringstream msg;
  1706             msg << "Multiple occurence of node map: " << map;
  1707             throw FormatError(msg.str());
  1708           }
  1709           maps.insert(std::make_pair(map, index));
  1710           ++index;
  1711         }
  1712 
  1713         for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
  1714           std::map<std::string, int>::iterator jt =
  1715             maps.find(_node_maps[i].first);
  1716           if (jt == maps.end()) {
  1717             std::ostringstream msg;
  1718             msg << "Map not found: " << _node_maps[i].first;
  1719             throw FormatError(msg.str());
  1720           }
  1721           map_index[i] = jt->second;
  1722         }
  1723 
  1724         {
  1725           std::map<std::string, int>::iterator jt = maps.find("label");
  1726           if (jt != maps.end()) {
  1727             label_index = jt->second;
  1728           } else {
  1729             label_index = -1;
  1730           }
  1731         }
  1732         map_num = maps.size();
  1733       }
  1734 
  1735       while (readLine() && line >> c && c != '@') {
  1736         line.putback(c);
  1737 
  1738         std::vector<std::string> tokens(map_num);
  1739         for (int i = 0; i < map_num; ++i) {
  1740           if (!_reader_bits::readToken(line, tokens[i])) {
  1741             std::ostringstream msg;
  1742             msg << "Column not found (" << i + 1 << ")";
  1743             throw FormatError(msg.str());
  1744           }
  1745         }
  1746         if (line >> std::ws >> c)
  1747           throw FormatError("Extra character at the end of line");
  1748 
  1749         Node n;
  1750         if (!_use_nodes) {
  1751           n = _graph.addNode();
  1752           if (label_index != -1)
  1753             _node_index.insert(std::make_pair(tokens[label_index], n));
  1754         } else {
  1755           if (label_index == -1)
  1756             throw FormatError("Label map not found");
  1757           typename std::map<std::string, Node>::iterator it =
  1758             _node_index.find(tokens[label_index]);
  1759           if (it == _node_index.end()) {
  1760             std::ostringstream msg;
  1761             msg << "Node with label not found: " << tokens[label_index];
  1762             throw FormatError(msg.str());
  1763           }
  1764           n = it->second;
  1765         }
  1766 
  1767         for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
  1768           _node_maps[i].second->set(n, tokens[map_index[i]]);
  1769         }
  1770 
  1771       }
  1772       if (readSuccess()) {
  1773         line.putback(c);
  1774       }
  1775     }
  1776 
  1777     void readEdges() {
  1778 
  1779       std::vector<int> map_index(_edge_maps.size());
  1780       int map_num, label_index;
  1781 
  1782       char c;
  1783       if (!readLine() || !(line >> c) || c == '@') {
  1784         if (readSuccess() && line) line.putback(c);
  1785         if (!_edge_maps.empty())
  1786           throw FormatError("Cannot find map names");
  1787         return;
  1788       }
  1789       line.putback(c);
  1790 
  1791       {
  1792         std::map<std::string, int> maps;
  1793 
  1794         std::string map;
  1795         int index = 0;
  1796         while (_reader_bits::readToken(line, map)) {
  1797           if (maps.find(map) != maps.end()) {
  1798             std::ostringstream msg;
  1799             msg << "Multiple occurence of edge map: " << map;
  1800             throw FormatError(msg.str());
  1801           }
  1802           maps.insert(std::make_pair(map, index));
  1803           ++index;
  1804         }
  1805 
  1806         for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) {
  1807           std::map<std::string, int>::iterator jt =
  1808             maps.find(_edge_maps[i].first);
  1809           if (jt == maps.end()) {
  1810             std::ostringstream msg;
  1811             msg << "Map not found: " << _edge_maps[i].first;
  1812             throw FormatError(msg.str());
  1813           }
  1814           map_index[i] = jt->second;
  1815         }
  1816 
  1817         {
  1818           std::map<std::string, int>::iterator jt = maps.find("label");
  1819           if (jt != maps.end()) {
  1820             label_index = jt->second;
  1821           } else {
  1822             label_index = -1;
  1823           }
  1824         }
  1825         map_num = maps.size();
  1826       }
  1827 
  1828       while (readLine() && line >> c && c != '@') {
  1829         line.putback(c);
  1830 
  1831         std::string source_token;
  1832         std::string target_token;
  1833 
  1834         if (!_reader_bits::readToken(line, source_token))
  1835           throw FormatError("Node u not found");
  1836 
  1837         if (!_reader_bits::readToken(line, target_token))
  1838           throw FormatError("Node v not found");
  1839 
  1840         std::vector<std::string> tokens(map_num);
  1841         for (int i = 0; i < map_num; ++i) {
  1842           if (!_reader_bits::readToken(line, tokens[i])) {
  1843             std::ostringstream msg;
  1844             msg << "Column not found (" << i + 1 << ")";
  1845             throw FormatError(msg.str());
  1846           }
  1847         }
  1848         if (line >> std::ws >> c)
  1849           throw FormatError("Extra character at the end of line");
  1850 
  1851         Edge e;
  1852         if (!_use_edges) {
  1853 
  1854           typename NodeIndex::iterator it;
  1855 
  1856           it = _node_index.find(source_token);
  1857           if (it == _node_index.end()) {
  1858             std::ostringstream msg;
  1859             msg << "Item not found: " << source_token;
  1860             throw FormatError(msg.str());
  1861           }
  1862           Node source = it->second;
  1863 
  1864           it = _node_index.find(target_token);
  1865           if (it == _node_index.end()) {
  1866             std::ostringstream msg;
  1867             msg << "Item not found: " << target_token;
  1868             throw FormatError(msg.str());
  1869           }
  1870           Node target = it->second;
  1871 
  1872           e = _graph.addEdge(source, target);
  1873           if (label_index != -1)
  1874             _edge_index.insert(std::make_pair(tokens[label_index], e));
  1875         } else {
  1876           if (label_index == -1)
  1877             throw FormatError("Label map not found");
  1878           typename std::map<std::string, Edge>::iterator it =
  1879             _edge_index.find(tokens[label_index]);
  1880           if (it == _edge_index.end()) {
  1881             std::ostringstream msg;
  1882             msg << "Edge with label not found: " << tokens[label_index];
  1883             throw FormatError(msg.str());
  1884           }
  1885           e = it->second;
  1886         }
  1887 
  1888         for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) {
  1889           _edge_maps[i].second->set(e, tokens[map_index[i]]);
  1890         }
  1891 
  1892       }
  1893       if (readSuccess()) {
  1894         line.putback(c);
  1895       }
  1896     }
  1897 
  1898     void readAttributes() {
  1899 
  1900       std::set<std::string> read_attr;
  1901 
  1902       char c;
  1903       while (readLine() && line >> c && c != '@') {
  1904         line.putback(c);
  1905 
  1906         std::string attr, token;
  1907         if (!_reader_bits::readToken(line, attr))
  1908           throw FormatError("Attribute name not found");
  1909         if (!_reader_bits::readToken(line, token))
  1910           throw FormatError("Attribute value not found");
  1911         if (line >> c)
  1912           throw FormatError("Extra character at the end of line");
  1913 
  1914         {
  1915           std::set<std::string>::iterator it = read_attr.find(attr);
  1916           if (it != read_attr.end()) {
  1917             std::ostringstream msg;
  1918             msg << "Multiple occurence of attribute: " << attr;
  1919             throw FormatError(msg.str());
  1920           }
  1921           read_attr.insert(attr);
  1922         }
  1923 
  1924         {
  1925           typename Attributes::iterator it = _attributes.lower_bound(attr);
  1926           while (it != _attributes.end() && it->first == attr) {
  1927             it->second->set(token);
  1928             ++it;
  1929           }
  1930         }
  1931 
  1932       }
  1933       if (readSuccess()) {
  1934         line.putback(c);
  1935       }
  1936       for (typename Attributes::iterator it = _attributes.begin();
  1937            it != _attributes.end(); ++it) {
  1938         if (read_attr.find(it->first) == read_attr.end()) {
  1939           std::ostringstream msg;
  1940           msg << "Attribute not found: " << it->first;
  1941           throw FormatError(msg.str());
  1942         }
  1943       }
  1944     }
  1945 
  1946   public:
  1947 
  1948     /// \name Execution of the reader
  1949     /// @{
  1950 
  1951     /// \brief Start the batch processing
  1952     ///
  1953     /// This function starts the batch processing
  1954     void run() {
  1955 
  1956       LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
  1957 
  1958       bool nodes_done = _skip_nodes;
  1959       bool edges_done = _skip_edges;
  1960       bool attributes_done = false;
  1961 
  1962       line_num = 0;
  1963       readLine();
  1964       skipSection();
  1965 
  1966       while (readSuccess()) {
  1967         try {
  1968           char c;
  1969           std::string section, caption;
  1970           line >> c;
  1971           _reader_bits::readToken(line, section);
  1972           _reader_bits::readToken(line, caption);
  1973 
  1974           if (line >> c)
  1975             throw FormatError("Extra character at the end of line");
  1976 
  1977           if (section == "nodes" && !nodes_done) {
  1978             if (_nodes_caption.empty() || _nodes_caption == caption) {
  1979               readNodes();
  1980               nodes_done = true;
  1981             }
  1982           } else if ((section == "edges" || section == "arcs") &&
  1983                      !edges_done) {
  1984             if (_edges_caption.empty() || _edges_caption == caption) {
  1985               readEdges();
  1986               edges_done = true;
  1987             }
  1988           } else if (section == "attributes" && !attributes_done) {
  1989             if (_attributes_caption.empty() || _attributes_caption == caption) {
  1990               readAttributes();
  1991               attributes_done = true;
  1992             }
  1993           } else {
  1994             readLine();
  1995             skipSection();
  1996           }
  1997         } catch (FormatError& error) {
  1998           error.line(line_num);
  1999           error.file(_filename);
  2000           throw;
  2001         }
  2002       }
  2003 
  2004       if (!nodes_done) {
  2005         throw FormatError("Section @nodes not found");
  2006       }
  2007 
  2008       if (!edges_done) {
  2009         throw FormatError("Section @edges not found");
  2010       }
  2011 
  2012       if (!attributes_done && !_attributes.empty()) {
  2013         throw FormatError("Section @attributes not found");
  2014       }
  2015 
  2016     }
  2017 
  2018     /// @}
  2019 
  2020   };
  2021 
  2022   /// \brief Return a \ref GraphReader class
  2023   ///
  2024   /// This function just returns a \ref GraphReader class.
  2025   /// \relates GraphReader
  2026   template <typename Graph>
  2027   GraphReader<Graph> graphReader(Graph& graph, std::istream& is = std::cin) {
  2028     GraphReader<Graph> tmp(graph, is);
  2029     return tmp;
  2030   }
  2031 
  2032   /// \brief Return a \ref GraphReader class
  2033   ///
  2034   /// This function just returns a \ref GraphReader class.
  2035   /// \relates GraphReader
  2036   template <typename Graph>
  2037   GraphReader<Graph> graphReader(Graph& graph, const std::string& fn) {
  2038     GraphReader<Graph> tmp(graph, fn);
  2039     return tmp;
  2040   }
  2041 
  2042   /// \brief Return a \ref GraphReader class
  2043   ///
  2044   /// This function just returns a \ref GraphReader class.
  2045   /// \relates GraphReader
  2046   template <typename Graph>
  2047   GraphReader<Graph> graphReader(Graph& graph, const char* fn) {
  2048     GraphReader<Graph> tmp(graph, fn);
  2049     return tmp;
  2050   }
  2051 
  2052   class SectionReader;
  2053 
  2054   SectionReader sectionReader(std::istream& is);
  2055   SectionReader sectionReader(const std::string& fn);
  2056   SectionReader sectionReader(const char* fn);
  2057 
  2058   /// \ingroup lemon_io
  2059   ///
  2060   /// \brief Section reader class
  2061   ///
  2062   /// In the \ref lgf-format "LGF" file extra sections can be placed,
  2063   /// which contain any data in arbitrary format. Such sections can be
  2064   /// read with this class. A reading rule can be added to the class
  2065   /// with two different functions. With the \c sectionLines() function a
  2066   /// functor can process the section line-by-line, while with the \c
  2067   /// sectionStream() member the section can be read from an input
  2068   /// stream.
  2069   class SectionReader {
  2070   private:
  2071 
  2072     std::istream* _is;
  2073     bool local_is;
  2074     std::string _filename;
  2075 
  2076     typedef std::map<std::string, _reader_bits::Section*> Sections;
  2077     Sections _sections;
  2078 
  2079     int line_num;
  2080     std::istringstream line;
  2081 
  2082   public:
  2083 
  2084     /// \brief Constructor
  2085     ///
  2086     /// Construct a section reader, which reads from the given input
  2087     /// stream.
  2088     SectionReader(std::istream& is)
  2089       : _is(&is), local_is(false) {}
  2090 
  2091     /// \brief Constructor
  2092     ///
  2093     /// Construct a section reader, which reads from the given file.
  2094     SectionReader(const std::string& fn)
  2095       : _is(new std::ifstream(fn.c_str())), local_is(true),
  2096         _filename(fn) {
  2097       if (!(*_is)) throw IoError("Cannot open file", fn);
  2098     }
  2099 
  2100     /// \brief Constructor
  2101     ///
  2102     /// Construct a section reader, which reads from the given file.
  2103     SectionReader(const char* fn)
  2104       : _is(new std::ifstream(fn)), local_is(true),
  2105         _filename(fn) {
  2106       if (!(*_is)) throw IoError("Cannot open file", fn);
  2107     }
  2108 
  2109     /// \brief Destructor
  2110     ~SectionReader() {
  2111       for (Sections::iterator it = _sections.begin();
  2112            it != _sections.end(); ++it) {
  2113         delete it->second;
  2114       }
  2115 
  2116       if (local_is) {
  2117         delete _is;
  2118       }
  2119 
  2120     }
  2121 
  2122   private:
  2123 
  2124     friend SectionReader sectionReader(std::istream& is);
  2125     friend SectionReader sectionReader(const std::string& fn);
  2126     friend SectionReader sectionReader(const char* fn);
  2127 
  2128     SectionReader(SectionReader& other)
  2129       : _is(other._is), local_is(other.local_is) {
  2130 
  2131       other._is = 0;
  2132       other.local_is = false;
  2133 
  2134       _sections.swap(other._sections);
  2135     }
  2136 
  2137     SectionReader& operator=(const SectionReader&);
  2138 
  2139   public:
  2140 
  2141     /// \name Section readers
  2142     /// @{
  2143 
  2144     /// \brief Add a section processor with line oriented reading
  2145     ///
  2146     /// The first parameter is the type descriptor of the section, the
  2147     /// second is a functor, which takes just one \c std::string
  2148     /// parameter. At the reading process, each line of the section
  2149     /// will be given to the functor object. However, the empty lines
  2150     /// and the comment lines are filtered out, and the leading
  2151     /// whitespaces are trimmed from each processed string.
  2152     ///
  2153     /// For example let's see a section, which contain several
  2154     /// integers, which should be inserted into a vector.
  2155     ///\code
  2156     ///  @numbers
  2157     ///  12 45 23
  2158     ///  4
  2159     ///  23 6
  2160     ///\endcode
  2161     ///
  2162     /// The functor is implemented as a struct:
  2163     ///\code
  2164     ///  struct NumberSection {
  2165     ///    std::vector<int>& _data;
  2166     ///    NumberSection(std::vector<int>& data) : _data(data) {}
  2167     ///    void operator()(const std::string& line) {
  2168     ///      std::istringstream ls(line);
  2169     ///      int value;
  2170     ///      while (ls >> value) _data.push_back(value);
  2171     ///    }
  2172     ///  };
  2173     ///
  2174     ///  // ...
  2175     ///
  2176     ///  reader.sectionLines("numbers", NumberSection(vec));
  2177     ///\endcode
  2178     template <typename Functor>
  2179     SectionReader& sectionLines(const std::string& type, Functor functor) {
  2180       LEMON_ASSERT(!type.empty(), "Type is empty.");
  2181       LEMON_ASSERT(_sections.find(type) == _sections.end(),
  2182                    "Multiple reading of section.");
  2183       _sections.insert(std::make_pair(type,
  2184         new _reader_bits::LineSection<Functor>(functor)));
  2185       return *this;
  2186     }
  2187 
  2188 
  2189     /// \brief Add a section processor with stream oriented reading
  2190     ///
  2191     /// The first parameter is the type of the section, the second is
  2192     /// a functor, which takes an \c std::istream& and an \c int&
  2193     /// parameter, the latter regard to the line number of stream. The
  2194     /// functor can read the input while the section go on, and the
  2195     /// line number should be modified accordingly.
  2196     template <typename Functor>
  2197     SectionReader& sectionStream(const std::string& type, Functor functor) {
  2198       LEMON_ASSERT(!type.empty(), "Type is empty.");
  2199       LEMON_ASSERT(_sections.find(type) == _sections.end(),
  2200                    "Multiple reading of section.");
  2201       _sections.insert(std::make_pair(type,
  2202          new _reader_bits::StreamSection<Functor>(functor)));
  2203       return *this;
  2204     }
  2205 
  2206     /// @}
  2207 
  2208   private:
  2209 
  2210     bool readLine() {
  2211       std::string str;
  2212       while(++line_num, std::getline(*_is, str)) {
  2213         line.clear(); line.str(str);
  2214         char c;
  2215         if (line >> std::ws >> c && c != '#') {
  2216           line.putback(c);
  2217           return true;
  2218         }
  2219       }
  2220       return false;
  2221     }
  2222 
  2223     bool readSuccess() {
  2224       return static_cast<bool>(*_is);
  2225     }
  2226 
  2227     void skipSection() {
  2228       char c;
  2229       while (readSuccess() && line >> c && c != '@') {
  2230         readLine();
  2231       }
  2232       line.putback(c);
  2233     }
  2234 
  2235   public:
  2236 
  2237 
  2238     /// \name Execution of the reader
  2239     /// @{
  2240 
  2241     /// \brief Start the batch processing
  2242     ///
  2243     /// This function starts the batch processing.
  2244     void run() {
  2245 
  2246       LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
  2247 
  2248       std::set<std::string> extra_sections;
  2249 
  2250       line_num = 0;
  2251       readLine();
  2252       skipSection();
  2253 
  2254       while (readSuccess()) {
  2255         try {
  2256           char c;
  2257           std::string section, caption;
  2258           line >> c;
  2259           _reader_bits::readToken(line, section);
  2260           _reader_bits::readToken(line, caption);
  2261 
  2262           if (line >> c)
  2263             throw FormatError("Extra character at the end of line");
  2264 
  2265           if (extra_sections.find(section) != extra_sections.end()) {
  2266             std::ostringstream msg;
  2267             msg << "Multiple occurence of section: " << section;
  2268             throw FormatError(msg.str());
  2269           }
  2270           Sections::iterator it = _sections.find(section);
  2271           if (it != _sections.end()) {
  2272             extra_sections.insert(section);
  2273             it->second->process(*_is, line_num);
  2274           }
  2275           readLine();
  2276           skipSection();
  2277         } catch (FormatError& error) {
  2278           error.line(line_num);
  2279           error.file(_filename);
  2280           throw;
  2281         }
  2282       }
  2283       for (Sections::iterator it = _sections.begin();
  2284            it != _sections.end(); ++it) {
  2285         if (extra_sections.find(it->first) == extra_sections.end()) {
  2286           std::ostringstream os;
  2287           os << "Cannot find section: " << it->first;
  2288           throw FormatError(os.str());
  2289         }
  2290       }
  2291     }
  2292 
  2293     /// @}
  2294 
  2295   };
  2296 
  2297   /// \brief Return a \ref SectionReader class
  2298   ///
  2299   /// This function just returns a \ref SectionReader class.
  2300   /// \relates SectionReader
  2301   inline SectionReader sectionReader(std::istream& is) {
  2302     SectionReader tmp(is);
  2303     return tmp;
  2304   }
  2305 
  2306   /// \brief Return a \ref SectionReader class
  2307   ///
  2308   /// This function just returns a \ref SectionReader class.
  2309   /// \relates SectionReader
  2310   inline SectionReader sectionReader(const std::string& fn) {
  2311     SectionReader tmp(fn);
  2312     return tmp;
  2313   }
  2314 
  2315   /// \brief Return a \ref SectionReader class
  2316   ///
  2317   /// This function just returns a \ref SectionReader class.
  2318   /// \relates SectionReader
  2319   inline SectionReader sectionReader(const char* fn) {
  2320     SectionReader tmp(fn);
  2321     return tmp;
  2322   }
  2323 
  2324   /// \ingroup lemon_io
  2325   ///
  2326   /// \brief Reader for the contents of the \ref lgf-format "LGF" file
  2327   ///
  2328   /// This class can be used to read the sections, the map names and
  2329   /// the attributes from a file. Usually, the LEMON programs know
  2330   /// that, which type of graph, which maps and which attributes
  2331   /// should be read from a file, but in general tools (like glemon)
  2332   /// the contents of an LGF file should be guessed somehow. This class
  2333   /// reads the graph and stores the appropriate information for
  2334   /// reading the graph.
  2335   ///
  2336   ///\code
  2337   /// LgfContents contents("graph.lgf");
  2338   /// contents.run();
  2339   ///
  2340   /// // Does it contain any node section and arc section?
  2341   /// if (contents.nodeSectionNum() == 0 || contents.arcSectionNum()) {
  2342   ///   std::cerr << "Failure, cannot find graph." << std::endl;
  2343   ///   return -1;
  2344   /// }
  2345   /// std::cout << "The name of the default node section: "
  2346   ///           << contents.nodeSection(0) << std::endl;
  2347   /// std::cout << "The number of the arc maps: "
  2348   ///           << contents.arcMaps(0).size() << std::endl;
  2349   /// std::cout << "The name of second arc map: "
  2350   ///           << contents.arcMaps(0)[1] << std::endl;
  2351   ///\endcode
  2352   class LgfContents {
  2353   private:
  2354 
  2355     std::istream* _is;
  2356     bool local_is;
  2357 
  2358     std::vector<std::string> _node_sections;
  2359     std::vector<std::string> _edge_sections;
  2360     std::vector<std::string> _attribute_sections;
  2361     std::vector<std::string> _extra_sections;
  2362 
  2363     std::vector<bool> _arc_sections;
  2364 
  2365     std::vector<std::vector<std::string> > _node_maps;
  2366     std::vector<std::vector<std::string> > _edge_maps;
  2367 
  2368     std::vector<std::vector<std::string> > _attributes;
  2369 
  2370 
  2371     int line_num;
  2372     std::istringstream line;
  2373 
  2374   public:
  2375 
  2376     /// \brief Constructor
  2377     ///
  2378     /// Construct an \e LGF contents reader, which reads from the given
  2379     /// input stream.
  2380     LgfContents(std::istream& is)
  2381       : _is(&is), local_is(false) {}
  2382 
  2383     /// \brief Constructor
  2384     ///
  2385     /// Construct an \e LGF contents reader, which reads from the given
  2386     /// file.
  2387     LgfContents(const std::string& fn)
  2388       : _is(new std::ifstream(fn.c_str())), local_is(true) {
  2389       if (!(*_is)) throw IoError("Cannot open file", fn);
  2390     }
  2391 
  2392     /// \brief Constructor
  2393     ///
  2394     /// Construct an \e LGF contents reader, which reads from the given
  2395     /// file.
  2396     LgfContents(const char* fn)
  2397       : _is(new std::ifstream(fn)), local_is(true) {
  2398       if (!(*_is)) throw IoError("Cannot open file", fn);
  2399     }
  2400 
  2401     /// \brief Destructor
  2402     ~LgfContents() {
  2403       if (local_is) delete _is;
  2404     }
  2405 
  2406   private:
  2407 
  2408     LgfContents(const LgfContents&);
  2409     LgfContents& operator=(const LgfContents&);
  2410 
  2411   public:
  2412 
  2413 
  2414     /// \name Node sections
  2415     /// @{
  2416 
  2417     /// \brief Gives back the number of node sections in the file.
  2418     ///
  2419     /// Gives back the number of node sections in the file.
  2420     int nodeSectionNum() const {
  2421       return _node_sections.size();
  2422     }
  2423 
  2424     /// \brief Returns the node section name at the given position.
  2425     ///
  2426     /// Returns the node section name at the given position.
  2427     const std::string& nodeSection(int i) const {
  2428       return _node_sections[i];
  2429     }
  2430 
  2431     /// \brief Gives back the node maps for the given section.
  2432     ///
  2433     /// Gives back the node maps for the given section.
  2434     const std::vector<std::string>& nodeMapNames(int i) const {
  2435       return _node_maps[i];
  2436     }
  2437 
  2438     /// @}
  2439 
  2440     /// \name Arc/Edge sections
  2441     /// @{
  2442 
  2443     /// \brief Gives back the number of arc/edge sections in the file.
  2444     ///
  2445     /// Gives back the number of arc/edge sections in the file.
  2446     /// \note It is synonym of \c edgeSectionNum().
  2447     int arcSectionNum() const {
  2448       return _edge_sections.size();
  2449     }
  2450 
  2451     /// \brief Returns the arc/edge section name at the given position.
  2452     ///
  2453     /// Returns the arc/edge section name at the given position.
  2454     /// \note It is synonym of \c edgeSection().
  2455     const std::string& arcSection(int i) const {
  2456       return _edge_sections[i];
  2457     }
  2458 
  2459     /// \brief Gives back the arc/edge maps for the given section.
  2460     ///
  2461     /// Gives back the arc/edge maps for the given section.
  2462     /// \note It is synonym of \c edgeMapNames().
  2463     const std::vector<std::string>& arcMapNames(int i) const {
  2464       return _edge_maps[i];
  2465     }
  2466 
  2467     /// @}
  2468 
  2469     /// \name Synonyms
  2470     /// @{
  2471 
  2472     /// \brief Gives back the number of arc/edge sections in the file.
  2473     ///
  2474     /// Gives back the number of arc/edge sections in the file.
  2475     /// \note It is synonym of \c arcSectionNum().
  2476     int edgeSectionNum() const {
  2477       return _edge_sections.size();
  2478     }
  2479 
  2480     /// \brief Returns the section name at the given position.
  2481     ///
  2482     /// Returns the section name at the given position.
  2483     /// \note It is synonym of \c arcSection().
  2484     const std::string& edgeSection(int i) const {
  2485       return _edge_sections[i];
  2486     }
  2487 
  2488     /// \brief Gives back the edge maps for the given section.
  2489     ///
  2490     /// Gives back the edge maps for the given section.
  2491     /// \note It is synonym of \c arcMapNames().
  2492     const std::vector<std::string>& edgeMapNames(int i) const {
  2493       return _edge_maps[i];
  2494     }
  2495 
  2496     /// @}
  2497 
  2498     /// \name Attribute sections
  2499     /// @{
  2500 
  2501     /// \brief Gives back the number of attribute sections in the file.
  2502     ///
  2503     /// Gives back the number of attribute sections in the file.
  2504     int attributeSectionNum() const {
  2505       return _attribute_sections.size();
  2506     }
  2507 
  2508     /// \brief Returns the attribute section name at the given position.
  2509     ///
  2510     /// Returns the attribute section name at the given position.
  2511     const std::string& attributeSectionNames(int i) const {
  2512       return _attribute_sections[i];
  2513     }
  2514 
  2515     /// \brief Gives back the attributes for the given section.
  2516     ///
  2517     /// Gives back the attributes for the given section.
  2518     const std::vector<std::string>& attributes(int i) const {
  2519       return _attributes[i];
  2520     }
  2521 
  2522     /// @}
  2523 
  2524     /// \name Extra sections
  2525     /// @{
  2526 
  2527     /// \brief Gives back the number of extra sections in the file.
  2528     ///
  2529     /// Gives back the number of extra sections in the file.
  2530     int extraSectionNum() const {
  2531       return _extra_sections.size();
  2532     }
  2533 
  2534     /// \brief Returns the extra section type at the given position.
  2535     ///
  2536     /// Returns the section type at the given position.
  2537     const std::string& extraSection(int i) const {
  2538       return _extra_sections[i];
  2539     }
  2540 
  2541     /// @}
  2542 
  2543   private:
  2544 
  2545     bool readLine() {
  2546       std::string str;
  2547       while(++line_num, std::getline(*_is, str)) {
  2548         line.clear(); line.str(str);
  2549         char c;
  2550         if (line >> std::ws >> c && c != '#') {
  2551           line.putback(c);
  2552           return true;
  2553         }
  2554       }
  2555       return false;
  2556     }
  2557 
  2558     bool readSuccess() {
  2559       return static_cast<bool>(*_is);
  2560     }
  2561 
  2562     void skipSection() {
  2563       char c;
  2564       while (readSuccess() && line >> c && c != '@') {
  2565         readLine();
  2566       }
  2567       line.putback(c);
  2568     }
  2569 
  2570     void readMaps(std::vector<std::string>& maps) {
  2571       char c;
  2572       if (!readLine() || !(line >> c) || c == '@') {
  2573         if (readSuccess() && line) line.putback(c);
  2574         return;
  2575       }
  2576       line.putback(c);
  2577       std::string map;
  2578       while (_reader_bits::readToken(line, map)) {
  2579         maps.push_back(map);
  2580       }
  2581     }
  2582 
  2583     void readAttributes(std::vector<std::string>& attrs) {
  2584       readLine();
  2585       char c;
  2586       while (readSuccess() && line >> c && c != '@') {
  2587         line.putback(c);
  2588         std::string attr;
  2589         _reader_bits::readToken(line, attr);
  2590         attrs.push_back(attr);
  2591         readLine();
  2592       }
  2593       line.putback(c);
  2594     }
  2595 
  2596   public:
  2597 
  2598     /// \name Execution of the contents reader
  2599     /// @{
  2600 
  2601     /// \brief Starts the reading
  2602     ///
  2603     /// This function starts the reading.
  2604     void run() {
  2605 
  2606       readLine();
  2607       skipSection();
  2608 
  2609       while (readSuccess()) {
  2610 
  2611         char c;
  2612         line >> c;
  2613 
  2614         std::string section, caption;
  2615         _reader_bits::readToken(line, section);
  2616         _reader_bits::readToken(line, caption);
  2617 
  2618         if (section == "nodes") {
  2619           _node_sections.push_back(caption);
  2620           _node_maps.push_back(std::vector<std::string>());
  2621           readMaps(_node_maps.back());
  2622           readLine(); skipSection();
  2623         } else if (section == "arcs" || section == "edges") {
  2624           _edge_sections.push_back(caption);
  2625           _arc_sections.push_back(section == "arcs");
  2626           _edge_maps.push_back(std::vector<std::string>());
  2627           readMaps(_edge_maps.back());
  2628           readLine(); skipSection();
  2629         } else if (section == "attributes") {
  2630           _attribute_sections.push_back(caption);
  2631           _attributes.push_back(std::vector<std::string>());
  2632           readAttributes(_attributes.back());
  2633         } else {
  2634           _extra_sections.push_back(section);
  2635           readLine(); skipSection();
  2636         }
  2637       }
  2638     }
  2639 
  2640     /// @}
  2641 
  2642   };
  2643 }
  2644 
  2645 #endif