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