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