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