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