lemon/lgf_writer.h
author Alpar Juttner <alpar@cs.elte.hu>
Wed, 08 Oct 2008 13:16:04 +0100
changeset 306 1871777f62b7
parent 294 cbe3ec2d59d2
child 307 a3a69f5bba62
permissions -rw-r--r--
Merge
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" writer.
deba@127
    22
deba@127
    23
deba@127
    24
#ifndef LEMON_LGF_WRITER_H
deba@127
    25
#define LEMON_LGF_WRITER_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 <algorithm>
deba@127
    32
deba@127
    33
#include <vector>
deba@127
    34
#include <functional>
deba@127
    35
deba@127
    36
#include <lemon/assert.h>
deba@220
    37
#include <lemon/core.h>
deba@220
    38
#include <lemon/maps.h>
deba@127
    39
deba@248
    40
#include <lemon/concept_check.h>
deba@248
    41
#include <lemon/concepts/maps.h>
deba@248
    42
deba@127
    43
namespace lemon {
deba@127
    44
deba@127
    45
  namespace _writer_bits {
deba@127
    46
deba@127
    47
    template <typename Value>
deba@127
    48
    struct DefaultConverter {
deba@127
    49
      std::string operator()(const Value& value) {
alpar@209
    50
        std::ostringstream os;
alpar@209
    51
        os << value;
alpar@209
    52
        return os.str();
deba@127
    53
      }
deba@127
    54
    };
deba@127
    55
deba@127
    56
    template <typename T>
deba@127
    57
    bool operator<(const T&, const T&) {
deba@290
    58
      throw FormatError("Label map is not comparable");
deba@127
    59
    }
deba@127
    60
deba@127
    61
    template <typename _Map>
deba@127
    62
    class MapLess {
deba@127
    63
    public:
deba@127
    64
      typedef _Map Map;
deba@127
    65
      typedef typename Map::Key Item;
deba@127
    66
deba@127
    67
    private:
deba@127
    68
      const Map& _map;
alpar@209
    69
deba@127
    70
    public:
deba@127
    71
      MapLess(const Map& map) : _map(map) {}
deba@127
    72
deba@127
    73
      bool operator()(const Item& left, const Item& right) {
alpar@209
    74
        return _map[left] < _map[right];
deba@127
    75
      }
deba@127
    76
    };
deba@127
    77
deba@165
    78
    template <typename _Graph, bool _dir, typename _Map>
deba@165
    79
    class GraphArcMapLess {
deba@165
    80
    public:
deba@165
    81
      typedef _Map Map;
deba@165
    82
      typedef _Graph Graph;
deba@165
    83
      typedef typename Graph::Edge Item;
deba@165
    84
deba@165
    85
    private:
deba@165
    86
      const Graph& _graph;
deba@165
    87
      const Map& _map;
alpar@209
    88
deba@165
    89
    public:
alpar@209
    90
      GraphArcMapLess(const Graph& graph, const Map& map)
alpar@209
    91
        : _graph(graph), _map(map) {}
deba@165
    92
deba@165
    93
      bool operator()(const Item& left, const Item& right) {
alpar@209
    94
        return _map[_graph.direct(left, _dir)] <
alpar@209
    95
          _map[_graph.direct(right, _dir)];
deba@165
    96
      }
deba@165
    97
    };
deba@165
    98
alpar@209
    99
    template <typename _Item>
deba@127
   100
    class MapStorageBase {
deba@127
   101
    public:
deba@127
   102
      typedef _Item Item;
deba@127
   103
deba@127
   104
    public:
deba@127
   105
      MapStorageBase() {}
deba@127
   106
      virtual ~MapStorageBase() {}
deba@127
   107
deba@127
   108
      virtual std::string get(const Item& item) = 0;
deba@127
   109
      virtual void sort(std::vector<Item>&) = 0;
deba@127
   110
    };
deba@127
   111
alpar@209
   112
    template <typename _Item, typename _Map,
alpar@209
   113
              typename _Converter = DefaultConverter<typename _Map::Value> >
deba@127
   114
    class MapStorage : public MapStorageBase<_Item> {
deba@127
   115
    public:
deba@127
   116
      typedef _Map Map;
deba@127
   117
      typedef _Converter Converter;
deba@127
   118
      typedef _Item Item;
alpar@209
   119
deba@127
   120
    private:
deba@127
   121
      const Map& _map;
deba@127
   122
      Converter _converter;
deba@127
   123
deba@127
   124
    public:
alpar@209
   125
      MapStorage(const Map& map, const Converter& converter = Converter())
alpar@209
   126
        : _map(map), _converter(converter) {}
deba@127
   127
      virtual ~MapStorage() {}
deba@127
   128
deba@127
   129
      virtual std::string get(const Item& item) {
alpar@209
   130
        return _converter(_map[item]);
deba@127
   131
      }
deba@127
   132
      virtual void sort(std::vector<Item>& items) {
alpar@209
   133
        MapLess<Map> less(_map);
alpar@209
   134
        std::sort(items.begin(), items.end(), less);
deba@127
   135
      }
deba@127
   136
    };
deba@127
   137
alpar@209
   138
    template <typename _Graph, bool _dir, typename _Map,
alpar@209
   139
              typename _Converter = DefaultConverter<typename _Map::Value> >
deba@165
   140
    class GraphArcMapStorage : public MapStorageBase<typename _Graph::Edge> {
deba@165
   141
    public:
deba@165
   142
      typedef _Map Map;
deba@165
   143
      typedef _Converter Converter;
deba@165
   144
      typedef _Graph Graph;
deba@165
   145
      typedef typename Graph::Edge Item;
deba@165
   146
      static const bool dir = _dir;
alpar@209
   147
deba@165
   148
    private:
deba@165
   149
      const Graph& _graph;
deba@165
   150
      const Map& _map;
deba@165
   151
      Converter _converter;
deba@165
   152
deba@165
   153
    public:
alpar@209
   154
      GraphArcMapStorage(const Graph& graph, const Map& map,
alpar@209
   155
                         const Converter& converter = Converter())
alpar@209
   156
        : _graph(graph), _map(map), _converter(converter) {}
deba@165
   157
      virtual ~GraphArcMapStorage() {}
deba@165
   158
deba@165
   159
      virtual std::string get(const Item& item) {
alpar@209
   160
        return _converter(_map[_graph.direct(item, dir)]);
deba@165
   161
      }
deba@165
   162
      virtual void sort(std::vector<Item>& items) {
alpar@209
   163
        GraphArcMapLess<Graph, dir, Map> less(_graph, _map);
alpar@209
   164
        std::sort(items.begin(), items.end(), less);
deba@165
   165
      }
deba@165
   166
    };
deba@165
   167
deba@127
   168
    class ValueStorageBase {
deba@127
   169
    public:
deba@127
   170
      ValueStorageBase() {}
deba@127
   171
      virtual ~ValueStorageBase() {}
deba@127
   172
alpar@209
   173
      virtual std::string get() = 0;
deba@127
   174
    };
deba@127
   175
deba@127
   176
    template <typename _Value, typename _Converter = DefaultConverter<_Value> >
deba@127
   177
    class ValueStorage : public ValueStorageBase {
deba@127
   178
    public:
deba@127
   179
      typedef _Value Value;
deba@127
   180
      typedef _Converter Converter;
deba@127
   181
deba@127
   182
    private:
deba@127
   183
      const Value& _value;
deba@127
   184
      Converter _converter;
deba@127
   185
deba@127
   186
    public:
deba@127
   187
      ValueStorage(const Value& value, const Converter& converter = Converter())
kpeter@212
   188
        : _value(value), _converter(converter) {}
deba@127
   189
deba@127
   190
      virtual std::string get() {
alpar@209
   191
        return _converter(_value);
deba@127
   192
      }
deba@127
   193
    };
deba@127
   194
deba@127
   195
    template <typename Value>
deba@127
   196
    struct MapLookUpConverter {
deba@127
   197
      const std::map<Value, std::string>& _map;
alpar@209
   198
alpar@209
   199
      MapLookUpConverter(const std::map<Value, std::string>& map)
alpar@209
   200
        : _map(map) {}
alpar@209
   201
deba@127
   202
      std::string operator()(const Value& str) {
alpar@209
   203
        typename std::map<Value, std::string>::const_iterator it =
alpar@209
   204
          _map.find(str);
alpar@209
   205
        if (it == _map.end()) {
deba@290
   206
          throw FormatError("Item not found");
alpar@209
   207
        }
alpar@209
   208
        return it->second;
deba@127
   209
      }
deba@127
   210
    };
deba@127
   211
deba@165
   212
    template <typename Graph>
deba@165
   213
    struct GraphArcLookUpConverter {
deba@165
   214
      const Graph& _graph;
deba@165
   215
      const std::map<typename Graph::Edge, std::string>& _map;
alpar@209
   216
alpar@209
   217
      GraphArcLookUpConverter(const Graph& graph,
alpar@209
   218
                              const std::map<typename Graph::Edge,
alpar@209
   219
                                             std::string>& map)
alpar@209
   220
        : _graph(graph), _map(map) {}
alpar@209
   221
deba@165
   222
      std::string operator()(const typename Graph::Arc& val) {
alpar@209
   223
        typename std::map<typename Graph::Edge, std::string>
alpar@209
   224
          ::const_iterator it = _map.find(val);
alpar@209
   225
        if (it == _map.end()) {
deba@290
   226
          throw FormatError("Item not found");
alpar@209
   227
        }
alpar@209
   228
        return (_graph.direction(val) ? '+' : '-') + it->second;
deba@165
   229
      }
deba@165
   230
    };
deba@165
   231
deba@197
   232
    inline bool isWhiteSpace(char c) {
alpar@209
   233
      return c == ' ' || c == '\t' || c == '\v' ||
alpar@209
   234
        c == '\n' || c == '\r' || c == '\f';
deba@127
   235
    }
deba@127
   236
deba@197
   237
    inline bool isEscaped(char c) {
alpar@209
   238
      return c == '\\' || c == '\"' || c == '\'' ||
alpar@209
   239
        c == '\a' || c == '\b';
deba@127
   240
    }
deba@127
   241
deba@197
   242
    inline static void writeEscape(std::ostream& os, char c) {
deba@127
   243
      switch (c) {
deba@127
   244
      case '\\':
alpar@209
   245
        os << "\\\\";
alpar@209
   246
        return;
deba@127
   247
      case '\"':
alpar@209
   248
        os << "\\\"";
alpar@209
   249
        return;
deba@127
   250
      case '\a':
alpar@209
   251
        os << "\\a";
alpar@209
   252
        return;
deba@127
   253
      case '\b':
alpar@209
   254
        os << "\\b";
alpar@209
   255
        return;
deba@127
   256
      case '\f':
alpar@209
   257
        os << "\\f";
alpar@209
   258
        return;
deba@127
   259
      case '\r':
alpar@209
   260
        os << "\\r";
alpar@209
   261
        return;
deba@127
   262
      case '\n':
alpar@209
   263
        os << "\\n";
alpar@209
   264
        return;
deba@127
   265
      case '\t':
alpar@209
   266
        os << "\\t";
alpar@209
   267
        return;
deba@127
   268
      case '\v':
alpar@209
   269
        os << "\\v";
alpar@209
   270
        return;
deba@127
   271
      default:
alpar@209
   272
        if (c < 0x20) {
alpar@209
   273
          std::ios::fmtflags flags = os.flags();
alpar@209
   274
          os << '\\' << std::oct << static_cast<int>(c);
alpar@209
   275
          os.flags(flags);
alpar@209
   276
        } else {
alpar@209
   277
          os << c;
alpar@209
   278
        }
alpar@209
   279
        return;
alpar@209
   280
      }
deba@127
   281
    }
deba@127
   282
deba@197
   283
    inline bool requireEscape(const std::string& str) {
alpar@156
   284
      if (str.empty() || str[0] == '@') return true;
deba@127
   285
      std::istringstream is(str);
deba@127
   286
      char c;
deba@127
   287
      while (is.get(c)) {
alpar@209
   288
        if (isWhiteSpace(c) || isEscaped(c)) {
alpar@209
   289
          return true;
alpar@209
   290
        }
deba@127
   291
      }
deba@127
   292
      return false;
deba@127
   293
    }
alpar@209
   294
deba@197
   295
    inline std::ostream& writeToken(std::ostream& os, const std::string& str) {
deba@127
   296
deba@127
   297
      if (requireEscape(str)) {
alpar@209
   298
        os << '\"';
alpar@209
   299
        for (std::string::const_iterator it = str.begin();
alpar@209
   300
             it != str.end(); ++it) {
alpar@209
   301
          writeEscape(os, *it);
alpar@209
   302
        }
alpar@209
   303
        os << '\"';
deba@127
   304
      } else {
alpar@209
   305
        os << str;
deba@127
   306
      }
deba@127
   307
      return os;
deba@127
   308
    }
deba@127
   309
deba@248
   310
    class Section {
deba@248
   311
    public:
deba@248
   312
      virtual ~Section() {}
deba@248
   313
      virtual void process(std::ostream& os) = 0;
deba@248
   314
    };
deba@248
   315
deba@248
   316
    template <typename Functor>
deba@248
   317
    class LineSection : public Section {
deba@248
   318
    private:
deba@248
   319
deba@248
   320
      Functor _functor;
deba@248
   321
deba@248
   322
    public:
deba@248
   323
deba@248
   324
      LineSection(const Functor& functor) : _functor(functor) {}
deba@248
   325
      virtual ~LineSection() {}
deba@248
   326
deba@248
   327
      virtual void process(std::ostream& os) {
deba@248
   328
        std::string line;
deba@248
   329
        while (!(line = _functor()).empty()) os << line << std::endl;
deba@248
   330
      }
deba@248
   331
    };
deba@248
   332
deba@248
   333
    template <typename Functor>
deba@248
   334
    class StreamSection : public Section {
deba@248
   335
    private:
deba@248
   336
deba@248
   337
      Functor _functor;
deba@248
   338
deba@248
   339
    public:
deba@248
   340
deba@248
   341
      StreamSection(const Functor& functor) : _functor(functor) {}
deba@248
   342
      virtual ~StreamSection() {}
deba@248
   343
deba@248
   344
      virtual void process(std::ostream& os) {
deba@248
   345
        _functor(os);
deba@248
   346
      }
deba@248
   347
    };
deba@248
   348
deba@127
   349
  }
deba@190
   350
deba@190
   351
  template <typename Digraph>
deba@190
   352
  class DigraphWriter;
deba@190
   353
deba@190
   354
  template <typename Digraph>
kpeter@293
   355
  DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
kpeter@293
   356
                                       std::ostream& os = std::cout);
deba@190
   357
deba@190
   358
  template <typename Digraph>
kpeter@293
   359
  DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
kpeter@293
   360
                                       const std::string& fn);
deba@190
   361
deba@190
   362
  template <typename Digraph>
kpeter@293
   363
  DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
kpeter@293
   364
                                       const char *fn);
alpar@209
   365
alpar@156
   366
  /// \ingroup lemon_io
alpar@209
   367
  ///
kpeter@192
   368
  /// \brief \ref lgf-format "LGF" writer for directed graphs
alpar@156
   369
  ///
alpar@156
   370
  /// This utility writes an \ref lgf-format "LGF" file.
alpar@156
   371
  ///
alpar@156
   372
  /// The writing method does a batch processing. The user creates a
alpar@156
   373
  /// writer object, then various writing rules can be added to the
alpar@156
   374
  /// writer, and eventually the writing is executed with the \c run()
alpar@156
   375
  /// member function. A map writing rule can be added to the writer
alpar@156
   376
  /// with the \c nodeMap() or \c arcMap() members. An optional
deba@163
   377
  /// converter parameter can also be added as a standard functor
kpeter@192
   378
  /// converting from the value type of the map to \c std::string. If it
kpeter@192
   379
  /// is set, it will determine how the value type of the map is written to
deba@163
   380
  /// the output stream. If the functor is not set, then a default
deba@163
   381
  /// conversion will be used. The \c attribute(), \c node() and \c
deba@163
   382
  /// arc() functions are used to add attribute writing rules.
alpar@156
   383
  ///
alpar@156
   384
  ///\code
kpeter@293
   385
  /// DigraphWriter<Digraph>(digraph, std::cout).
kpeter@192
   386
  ///   nodeMap("coordinates", coord_map).
kpeter@192
   387
  ///   nodeMap("size", size).
kpeter@192
   388
  ///   nodeMap("title", title).
kpeter@192
   389
  ///   arcMap("capacity", cap_map).
kpeter@192
   390
  ///   node("source", src).
kpeter@192
   391
  ///   node("target", trg).
kpeter@192
   392
  ///   attribute("caption", caption).
kpeter@192
   393
  ///   run();
alpar@156
   394
  ///\endcode
alpar@156
   395
  ///
alpar@156
   396
  ///
alpar@156
   397
  /// By default, the writer does not write additional captions to the
alpar@156
   398
  /// sections, but they can be give as an optional parameter of
alpar@156
   399
  /// the \c nodes(), \c arcs() or \c
alpar@156
   400
  /// attributes() functions.
alpar@156
   401
  ///
alpar@156
   402
  /// The \c skipNodes() and \c skipArcs() functions forbid the
deba@163
   403
  /// writing of the sections. If two arc sections should be written
deba@163
   404
  /// to the output, it can be done in two passes, the first pass
deba@163
   405
  /// writes the node section and the first arc section, then the
deba@163
   406
  /// second pass skips the node section and writes just the arc
deba@163
   407
  /// section to the stream. The output stream can be retrieved with
deba@163
   408
  /// the \c ostream() function, hence the second pass can append its
deba@163
   409
  /// output to the output of the first pass.
deba@127
   410
  template <typename _Digraph>
deba@127
   411
  class DigraphWriter {
deba@127
   412
  public:
deba@127
   413
deba@127
   414
    typedef _Digraph Digraph;
deba@148
   415
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
alpar@209
   416
deba@127
   417
  private:
deba@127
   418
deba@127
   419
deba@127
   420
    std::ostream* _os;
deba@127
   421
    bool local_os;
deba@127
   422
deba@190
   423
    const Digraph& _digraph;
deba@127
   424
deba@127
   425
    std::string _nodes_caption;
deba@127
   426
    std::string _arcs_caption;
deba@127
   427
    std::string _attributes_caption;
alpar@209
   428
deba@127
   429
    typedef std::map<Node, std::string> NodeIndex;
deba@127
   430
    NodeIndex _node_index;
deba@127
   431
    typedef std::map<Arc, std::string> ArcIndex;
deba@127
   432
    ArcIndex _arc_index;
deba@127
   433
alpar@209
   434
    typedef std::vector<std::pair<std::string,
alpar@209
   435
      _writer_bits::MapStorageBase<Node>* > > NodeMaps;
alpar@209
   436
    NodeMaps _node_maps;
deba@127
   437
alpar@209
   438
    typedef std::vector<std::pair<std::string,
deba@127
   439
      _writer_bits::MapStorageBase<Arc>* > >ArcMaps;
deba@127
   440
    ArcMaps _arc_maps;
deba@127
   441
alpar@209
   442
    typedef std::vector<std::pair<std::string,
deba@127
   443
      _writer_bits::ValueStorageBase*> > Attributes;
deba@127
   444
    Attributes _attributes;
deba@127
   445
deba@127
   446
    bool _skip_nodes;
deba@127
   447
    bool _skip_arcs;
deba@127
   448
deba@127
   449
  public:
deba@127
   450
alpar@156
   451
    /// \brief Constructor
alpar@156
   452
    ///
alpar@156
   453
    /// Construct a directed graph writer, which writes to the given
alpar@156
   454
    /// output stream.
kpeter@293
   455
    DigraphWriter(const Digraph& digraph, std::ostream& os = std::cout)
kpeter@293
   456
      : _os(&os), local_os(false), _digraph(digraph),
alpar@209
   457
        _skip_nodes(false), _skip_arcs(false) {}
deba@127
   458
alpar@156
   459
    /// \brief Constructor
alpar@156
   460
    ///
alpar@156
   461
    /// Construct a directed graph writer, which writes to the given
alpar@156
   462
    /// output file.
kpeter@293
   463
    DigraphWriter(const Digraph& digraph, const std::string& fn)
deba@127
   464
      : _os(new std::ofstream(fn.c_str())), local_os(true), _digraph(digraph),
deba@290
   465
        _skip_nodes(false), _skip_arcs(false) {
deba@295
   466
      if (!(*_os)) {
deba@295
   467
        delete _os;
deba@295
   468
        throw IoError("Cannot write file", fn);
deba@295
   469
      }
deba@290
   470
    }
deba@127
   471
alpar@156
   472
    /// \brief Constructor
alpar@156
   473
    ///
alpar@156
   474
    /// Construct a directed graph writer, which writes to the given
alpar@156
   475
    /// output file.
kpeter@293
   476
    DigraphWriter(const Digraph& digraph, const char* fn)
deba@127
   477
      : _os(new std::ofstream(fn)), local_os(true), _digraph(digraph),
deba@290
   478
        _skip_nodes(false), _skip_arcs(false) {
deba@295
   479
      if (!(*_os)) {
deba@295
   480
        delete _os;
deba@295
   481
        throw IoError("Cannot write file", fn);
deba@295
   482
      }
deba@290
   483
    }
deba@127
   484
alpar@156
   485
    /// \brief Destructor
deba@127
   486
    ~DigraphWriter() {
alpar@209
   487
      for (typename NodeMaps::iterator it = _node_maps.begin();
alpar@209
   488
           it != _node_maps.end(); ++it) {
alpar@209
   489
        delete it->second;
deba@127
   490
      }
deba@127
   491
alpar@209
   492
      for (typename ArcMaps::iterator it = _arc_maps.begin();
alpar@209
   493
           it != _arc_maps.end(); ++it) {
alpar@209
   494
        delete it->second;
deba@127
   495
      }
deba@127
   496
alpar@209
   497
      for (typename Attributes::iterator it = _attributes.begin();
alpar@209
   498
           it != _attributes.end(); ++it) {
alpar@209
   499
        delete it->second;
deba@127
   500
      }
deba@127
   501
deba@127
   502
      if (local_os) {
alpar@209
   503
        delete _os;
deba@127
   504
      }
deba@127
   505
    }
deba@127
   506
deba@127
   507
  private:
deba@190
   508
kpeter@293
   509
    friend DigraphWriter<Digraph> digraphWriter<>(const Digraph& digraph,
kpeter@293
   510
                                                  std::ostream& os);
kpeter@293
   511
    friend DigraphWriter<Digraph> digraphWriter<>(const Digraph& digraph,
kpeter@293
   512
                                                  const std::string& fn);
kpeter@293
   513
    friend DigraphWriter<Digraph> digraphWriter<>(const Digraph& digraph,
kpeter@293
   514
                                                  const char *fn);
deba@190
   515
alpar@209
   516
    DigraphWriter(DigraphWriter& other)
deba@190
   517
      : _os(other._os), local_os(other.local_os), _digraph(other._digraph),
alpar@209
   518
        _skip_nodes(other._skip_nodes), _skip_arcs(other._skip_arcs) {
deba@190
   519
deba@190
   520
      other._os = 0;
deba@190
   521
      other.local_os = false;
deba@190
   522
deba@190
   523
      _node_index.swap(other._node_index);
deba@190
   524
      _arc_index.swap(other._arc_index);
deba@190
   525
deba@190
   526
      _node_maps.swap(other._node_maps);
deba@190
   527
      _arc_maps.swap(other._arc_maps);
deba@190
   528
      _attributes.swap(other._attributes);
deba@190
   529
deba@190
   530
      _nodes_caption = other._nodes_caption;
deba@190
   531
      _arcs_caption = other._arcs_caption;
deba@190
   532
      _attributes_caption = other._attributes_caption;
deba@190
   533
    }
alpar@209
   534
deba@127
   535
    DigraphWriter& operator=(const DigraphWriter&);
deba@127
   536
deba@127
   537
  public:
deba@127
   538
alpar@156
   539
    /// \name Writing rules
alpar@156
   540
    /// @{
alpar@209
   541
kpeter@192
   542
    /// \brief Node map writing rule
alpar@156
   543
    ///
kpeter@192
   544
    /// Add a node map writing rule to the writer.
deba@127
   545
    template <typename Map>
deba@127
   546
    DigraphWriter& nodeMap(const std::string& caption, const Map& map) {
deba@127
   547
      checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
alpar@209
   548
      _writer_bits::MapStorageBase<Node>* storage =
alpar@209
   549
        new _writer_bits::MapStorage<Node, Map>(map);
deba@127
   550
      _node_maps.push_back(std::make_pair(caption, storage));
deba@127
   551
      return *this;
deba@127
   552
    }
deba@127
   553
alpar@156
   554
    /// \brief Node map writing rule
alpar@156
   555
    ///
alpar@156
   556
    /// Add a node map writing rule with specialized converter to the
alpar@156
   557
    /// writer.
deba@127
   558
    template <typename Map, typename Converter>
alpar@209
   559
    DigraphWriter& nodeMap(const std::string& caption, const Map& map,
alpar@209
   560
                           const Converter& converter = Converter()) {
deba@127
   561
      checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
alpar@209
   562
      _writer_bits::MapStorageBase<Node>* storage =
alpar@209
   563
        new _writer_bits::MapStorage<Node, Map, Converter>(map, converter);
deba@127
   564
      _node_maps.push_back(std::make_pair(caption, storage));
deba@127
   565
      return *this;
deba@127
   566
    }
deba@127
   567
alpar@156
   568
    /// \brief Arc map writing rule
alpar@156
   569
    ///
alpar@156
   570
    /// Add an arc map writing rule to the writer.
deba@127
   571
    template <typename Map>
deba@127
   572
    DigraphWriter& arcMap(const std::string& caption, const Map& map) {
deba@127
   573
      checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
alpar@209
   574
      _writer_bits::MapStorageBase<Arc>* storage =
alpar@209
   575
        new _writer_bits::MapStorage<Arc, Map>(map);
deba@127
   576
      _arc_maps.push_back(std::make_pair(caption, storage));
deba@127
   577
      return *this;
deba@127
   578
    }
deba@127
   579
alpar@156
   580
    /// \brief Arc map writing rule
alpar@156
   581
    ///
alpar@156
   582
    /// Add an arc map writing rule with specialized converter to the
alpar@156
   583
    /// writer.
deba@127
   584
    template <typename Map, typename Converter>
alpar@209
   585
    DigraphWriter& arcMap(const std::string& caption, const Map& map,
alpar@209
   586
                          const Converter& converter = Converter()) {
deba@127
   587
      checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
alpar@209
   588
      _writer_bits::MapStorageBase<Arc>* storage =
alpar@209
   589
        new _writer_bits::MapStorage<Arc, Map, Converter>(map, converter);
deba@127
   590
      _arc_maps.push_back(std::make_pair(caption, storage));
deba@127
   591
      return *this;
deba@127
   592
    }
deba@127
   593
alpar@156
   594
    /// \brief Attribute writing rule
alpar@156
   595
    ///
alpar@156
   596
    /// Add an attribute writing rule to the writer.
deba@127
   597
    template <typename Value>
deba@127
   598
    DigraphWriter& attribute(const std::string& caption, const Value& value) {
alpar@209
   599
      _writer_bits::ValueStorageBase* storage =
alpar@209
   600
        new _writer_bits::ValueStorage<Value>(value);
deba@127
   601
      _attributes.push_back(std::make_pair(caption, storage));
deba@127
   602
      return *this;
deba@127
   603
    }
deba@127
   604
alpar@156
   605
    /// \brief Attribute writing rule
alpar@156
   606
    ///
alpar@156
   607
    /// Add an attribute writing rule with specialized converter to the
alpar@156
   608
    /// writer.
deba@127
   609
    template <typename Value, typename Converter>
alpar@209
   610
    DigraphWriter& attribute(const std::string& caption, const Value& value,
alpar@209
   611
                             const Converter& converter = Converter()) {
alpar@209
   612
      _writer_bits::ValueStorageBase* storage =
alpar@209
   613
        new _writer_bits::ValueStorage<Value, Converter>(value, converter);
deba@127
   614
      _attributes.push_back(std::make_pair(caption, storage));
deba@127
   615
      return *this;
deba@127
   616
    }
deba@127
   617
alpar@156
   618
    /// \brief Node writing rule
alpar@156
   619
    ///
alpar@156
   620
    /// Add a node writing rule to the writer.
deba@127
   621
    DigraphWriter& node(const std::string& caption, const Node& node) {
deba@127
   622
      typedef _writer_bits::MapLookUpConverter<Node> Converter;
deba@127
   623
      Converter converter(_node_index);
alpar@209
   624
      _writer_bits::ValueStorageBase* storage =
alpar@209
   625
        new _writer_bits::ValueStorage<Node, Converter>(node, converter);
deba@127
   626
      _attributes.push_back(std::make_pair(caption, storage));
deba@127
   627
      return *this;
deba@127
   628
    }
deba@127
   629
alpar@156
   630
    /// \brief Arc writing rule
alpar@156
   631
    ///
alpar@156
   632
    /// Add an arc writing rule to writer.
deba@127
   633
    DigraphWriter& arc(const std::string& caption, const Arc& arc) {
deba@127
   634
      typedef _writer_bits::MapLookUpConverter<Arc> Converter;
deba@127
   635
      Converter converter(_arc_index);
alpar@209
   636
      _writer_bits::ValueStorageBase* storage =
alpar@209
   637
        new _writer_bits::ValueStorage<Arc, Converter>(arc, converter);
deba@127
   638
      _attributes.push_back(std::make_pair(caption, storage));
deba@127
   639
      return *this;
deba@127
   640
    }
deba@127
   641
kpeter@192
   642
    /// \name Section captions
alpar@156
   643
    /// @{
alpar@156
   644
kpeter@192
   645
    /// \brief Add an additional caption to the \c \@nodes section
alpar@156
   646
    ///
kpeter@192
   647
    /// Add an additional caption to the \c \@nodes section.
deba@127
   648
    DigraphWriter& nodes(const std::string& caption) {
deba@127
   649
      _nodes_caption = caption;
deba@127
   650
      return *this;
deba@127
   651
    }
deba@127
   652
kpeter@192
   653
    /// \brief Add an additional caption to the \c \@arcs section
alpar@156
   654
    ///
kpeter@192
   655
    /// Add an additional caption to the \c \@arcs section.
deba@127
   656
    DigraphWriter& arcs(const std::string& caption) {
deba@127
   657
      _arcs_caption = caption;
deba@127
   658
      return *this;
deba@127
   659
    }
deba@127
   660
kpeter@192
   661
    /// \brief Add an additional caption to the \c \@attributes section
alpar@156
   662
    ///
kpeter@192
   663
    /// Add an additional caption to the \c \@attributes section.
deba@127
   664
    DigraphWriter& attributes(const std::string& caption) {
deba@127
   665
      _attributes_caption = caption;
deba@127
   666
      return *this;
deba@127
   667
    }
deba@127
   668
alpar@156
   669
    /// \name Skipping section
alpar@156
   670
    /// @{
alpar@156
   671
alpar@156
   672
    /// \brief Skip writing the node set
alpar@156
   673
    ///
kpeter@192
   674
    /// The \c \@nodes section will not be written to the stream.
deba@127
   675
    DigraphWriter& skipNodes() {
deba@127
   676
      LEMON_ASSERT(!_skip_nodes, "Multiple usage of skipNodes() member");
deba@185
   677
      _skip_nodes = true;
deba@127
   678
      return *this;
deba@127
   679
    }
deba@127
   680
alpar@156
   681
    /// \brief Skip writing arc set
alpar@156
   682
    ///
kpeter@192
   683
    /// The \c \@arcs section will not be written to the stream.
deba@127
   684
    DigraphWriter& skipArcs() {
deba@127
   685
      LEMON_ASSERT(!_skip_arcs, "Multiple usage of skipArcs() member");
deba@185
   686
      _skip_arcs = true;
deba@127
   687
      return *this;
deba@127
   688
    }
deba@127
   689
alpar@156
   690
    /// @}
alpar@156
   691
deba@127
   692
  private:
deba@127
   693
deba@127
   694
    void writeNodes() {
deba@127
   695
      _writer_bits::MapStorageBase<Node>* label = 0;
deba@127
   696
      for (typename NodeMaps::iterator it = _node_maps.begin();
alpar@209
   697
           it != _node_maps.end(); ++it) {
deba@127
   698
        if (it->first == "label") {
alpar@209
   699
          label = it->second;
alpar@209
   700
          break;
alpar@209
   701
        }
deba@127
   702
      }
deba@127
   703
deba@127
   704
      *_os << "@nodes";
deba@127
   705
      if (!_nodes_caption.empty()) {
alpar@209
   706
        _writer_bits::writeToken(*_os << ' ', _nodes_caption);
deba@127
   707
      }
deba@127
   708
      *_os << std::endl;
deba@127
   709
deba@127
   710
      if (label == 0) {
alpar@209
   711
        *_os << "label" << '\t';
deba@127
   712
      }
deba@127
   713
      for (typename NodeMaps::iterator it = _node_maps.begin();
alpar@209
   714
           it != _node_maps.end(); ++it) {
alpar@209
   715
        _writer_bits::writeToken(*_os, it->first) << '\t';
deba@127
   716
      }
deba@127
   717
      *_os << std::endl;
deba@127
   718
deba@127
   719
      std::vector<Node> nodes;
deba@127
   720
      for (NodeIt n(_digraph); n != INVALID; ++n) {
alpar@209
   721
        nodes.push_back(n);
deba@127
   722
      }
alpar@209
   723
deba@127
   724
      if (label == 0) {
alpar@209
   725
        IdMap<Digraph, Node> id_map(_digraph);
alpar@209
   726
        _writer_bits::MapLess<IdMap<Digraph, Node> > id_less(id_map);
alpar@209
   727
        std::sort(nodes.begin(), nodes.end(), id_less);
deba@127
   728
      } else {
alpar@209
   729
        label->sort(nodes);
deba@127
   730
      }
deba@127
   731
deba@127
   732
      for (int i = 0; i < static_cast<int>(nodes.size()); ++i) {
alpar@209
   733
        Node n = nodes[i];
alpar@209
   734
        if (label == 0) {
alpar@209
   735
          std::ostringstream os;
alpar@209
   736
          os << _digraph.id(n);
alpar@209
   737
          _writer_bits::writeToken(*_os, os.str());
alpar@209
   738
          *_os << '\t';
alpar@209
   739
          _node_index.insert(std::make_pair(n, os.str()));
alpar@209
   740
        }
alpar@209
   741
        for (typename NodeMaps::iterator it = _node_maps.begin();
alpar@209
   742
             it != _node_maps.end(); ++it) {
alpar@209
   743
          std::string value = it->second->get(n);
alpar@209
   744
          _writer_bits::writeToken(*_os, value);
alpar@209
   745
          if (it->first == "label") {
alpar@209
   746
            _node_index.insert(std::make_pair(n, value));
alpar@209
   747
          }
alpar@209
   748
          *_os << '\t';
alpar@209
   749
        }
alpar@209
   750
        *_os << std::endl;
deba@127
   751
      }
deba@127
   752
    }
deba@127
   753
deba@185
   754
    void createNodeIndex() {
deba@185
   755
      _writer_bits::MapStorageBase<Node>* label = 0;
deba@185
   756
      for (typename NodeMaps::iterator it = _node_maps.begin();
alpar@209
   757
           it != _node_maps.end(); ++it) {
deba@185
   758
        if (it->first == "label") {
alpar@209
   759
          label = it->second;
alpar@209
   760
          break;
alpar@209
   761
        }
deba@185
   762
      }
deba@185
   763
deba@185
   764
      if (label == 0) {
alpar@209
   765
        for (NodeIt n(_digraph); n != INVALID; ++n) {
alpar@209
   766
          std::ostringstream os;
alpar@209
   767
          os << _digraph.id(n);
alpar@209
   768
          _node_index.insert(std::make_pair(n, os.str()));
alpar@209
   769
        }
deba@185
   770
      } else {
alpar@209
   771
        for (NodeIt n(_digraph); n != INVALID; ++n) {
alpar@209
   772
          std::string value = label->get(n);
alpar@209
   773
          _node_index.insert(std::make_pair(n, value));
alpar@209
   774
        }
deba@185
   775
      }
deba@185
   776
    }
deba@185
   777
deba@127
   778
    void writeArcs() {
deba@127
   779
      _writer_bits::MapStorageBase<Arc>* label = 0;
deba@127
   780
      for (typename ArcMaps::iterator it = _arc_maps.begin();
alpar@209
   781
           it != _arc_maps.end(); ++it) {
deba@127
   782
        if (it->first == "label") {
alpar@209
   783
          label = it->second;
alpar@209
   784
          break;
alpar@209
   785
        }
deba@127
   786
      }
deba@127
   787
deba@127
   788
      *_os << "@arcs";
deba@127
   789
      if (!_arcs_caption.empty()) {
alpar@209
   790
        _writer_bits::writeToken(*_os << ' ', _arcs_caption);
deba@127
   791
      }
deba@127
   792
      *_os << std::endl;
deba@127
   793
deba@127
   794
      *_os << '\t' << '\t';
deba@127
   795
      if (label == 0) {
alpar@209
   796
        *_os << "label" << '\t';
deba@127
   797
      }
deba@127
   798
      for (typename ArcMaps::iterator it = _arc_maps.begin();
alpar@209
   799
           it != _arc_maps.end(); ++it) {
alpar@209
   800
        _writer_bits::writeToken(*_os, it->first) << '\t';
deba@127
   801
      }
deba@127
   802
      *_os << std::endl;
deba@127
   803
deba@127
   804
      std::vector<Arc> arcs;
deba@127
   805
      for (ArcIt n(_digraph); n != INVALID; ++n) {
alpar@209
   806
        arcs.push_back(n);
deba@127
   807
      }
alpar@209
   808
deba@127
   809
      if (label == 0) {
alpar@209
   810
        IdMap<Digraph, Arc> id_map(_digraph);
alpar@209
   811
        _writer_bits::MapLess<IdMap<Digraph, Arc> > id_less(id_map);
alpar@209
   812
        std::sort(arcs.begin(), arcs.end(), id_less);
deba@127
   813
      } else {
alpar@209
   814
        label->sort(arcs);
deba@127
   815
      }
deba@127
   816
deba@127
   817
      for (int i = 0; i < static_cast<int>(arcs.size()); ++i) {
alpar@209
   818
        Arc a = arcs[i];
alpar@209
   819
        _writer_bits::writeToken(*_os, _node_index.
alpar@209
   820
                                 find(_digraph.source(a))->second);
alpar@209
   821
        *_os << '\t';
alpar@209
   822
        _writer_bits::writeToken(*_os, _node_index.
alpar@209
   823
                                 find(_digraph.target(a))->second);
alpar@209
   824
        *_os << '\t';
alpar@209
   825
        if (label == 0) {
alpar@209
   826
          std::ostringstream os;
alpar@209
   827
          os << _digraph.id(a);
alpar@209
   828
          _writer_bits::writeToken(*_os, os.str());
alpar@209
   829
          *_os << '\t';
alpar@209
   830
          _arc_index.insert(std::make_pair(a, os.str()));
alpar@209
   831
        }
alpar@209
   832
        for (typename ArcMaps::iterator it = _arc_maps.begin();
alpar@209
   833
             it != _arc_maps.end(); ++it) {
alpar@209
   834
          std::string value = it->second->get(a);
alpar@209
   835
          _writer_bits::writeToken(*_os, value);
alpar@209
   836
          if (it->first == "label") {
alpar@209
   837
            _arc_index.insert(std::make_pair(a, value));
alpar@209
   838
          }
alpar@209
   839
          *_os << '\t';
alpar@209
   840
        }
alpar@209
   841
        *_os << std::endl;
deba@127
   842
      }
deba@127
   843
    }
deba@127
   844
deba@185
   845
    void createArcIndex() {
deba@185
   846
      _writer_bits::MapStorageBase<Arc>* label = 0;
deba@185
   847
      for (typename ArcMaps::iterator it = _arc_maps.begin();
alpar@209
   848
           it != _arc_maps.end(); ++it) {
deba@185
   849
        if (it->first == "label") {
alpar@209
   850
          label = it->second;
alpar@209
   851
          break;
alpar@209
   852
        }
deba@185
   853
      }
deba@185
   854
deba@185
   855
      if (label == 0) {
alpar@209
   856
        for (ArcIt a(_digraph); a != INVALID; ++a) {
alpar@209
   857
          std::ostringstream os;
alpar@209
   858
          os << _digraph.id(a);
alpar@209
   859
          _arc_index.insert(std::make_pair(a, os.str()));
alpar@209
   860
        }
deba@185
   861
      } else {
alpar@209
   862
        for (ArcIt a(_digraph); a != INVALID; ++a) {
alpar@209
   863
          std::string value = label->get(a);
alpar@209
   864
          _arc_index.insert(std::make_pair(a, value));
alpar@209
   865
        }
deba@185
   866
      }
deba@185
   867
    }
deba@185
   868
deba@127
   869
    void writeAttributes() {
deba@127
   870
      if (_attributes.empty()) return;
deba@127
   871
      *_os << "@attributes";
deba@127
   872
      if (!_attributes_caption.empty()) {
alpar@209
   873
        _writer_bits::writeToken(*_os << ' ', _attributes_caption);
deba@127
   874
      }
deba@127
   875
      *_os << std::endl;
deba@127
   876
      for (typename Attributes::iterator it = _attributes.begin();
alpar@209
   877
           it != _attributes.end(); ++it) {
alpar@209
   878
        _writer_bits::writeToken(*_os, it->first) << ' ';
alpar@209
   879
        _writer_bits::writeToken(*_os, it->second->get());
alpar@209
   880
        *_os << std::endl;
deba@127
   881
      }
deba@127
   882
    }
alpar@209
   883
deba@127
   884
  public:
alpar@209
   885
alpar@209
   886
    /// \name Execution of the writer
alpar@156
   887
    /// @{
alpar@156
   888
alpar@156
   889
    /// \brief Start the batch processing
alpar@156
   890
    ///
kpeter@192
   891
    /// This function starts the batch processing.
deba@127
   892
    void run() {
deba@127
   893
      if (!_skip_nodes) {
alpar@209
   894
        writeNodes();
deba@185
   895
      } else {
alpar@209
   896
        createNodeIndex();
deba@127
   897
      }
alpar@209
   898
      if (!_skip_arcs) {
alpar@209
   899
        writeArcs();
deba@185
   900
      } else {
alpar@209
   901
        createArcIndex();
deba@127
   902
      }
deba@127
   903
      writeAttributes();
deba@127
   904
    }
deba@127
   905
kpeter@192
   906
    /// \brief Give back the stream of the writer
alpar@156
   907
    ///
kpeter@192
   908
    /// Give back the stream of the writer.
alpar@156
   909
    std::ostream& ostream() {
deba@127
   910
      return *_os;
deba@127
   911
    }
alpar@156
   912
alpar@156
   913
    /// @}
deba@127
   914
  };
deba@127
   915
kpeter@192
   916
  /// \brief Return a \ref DigraphWriter class
alpar@209
   917
  ///
kpeter@192
   918
  /// This function just returns a \ref DigraphWriter class.
alpar@156
   919
  /// \relates DigraphWriter
deba@127
   920
  template <typename Digraph>
kpeter@293
   921
  DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
kpeter@293
   922
                                       std::ostream& os = std::cout) {
kpeter@293
   923
    DigraphWriter<Digraph> tmp(digraph, os);
deba@163
   924
    return tmp;
deba@127
   925
  }
deba@127
   926
kpeter@192
   927
  /// \brief Return a \ref DigraphWriter class
alpar@209
   928
  ///
kpeter@192
   929
  /// This function just returns a \ref DigraphWriter class.
alpar@156
   930
  /// \relates DigraphWriter
deba@127
   931
  template <typename Digraph>
kpeter@293
   932
  DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
kpeter@293
   933
                                       const std::string& fn) {
kpeter@293
   934
    DigraphWriter<Digraph> tmp(digraph, fn);
deba@163
   935
    return tmp;
deba@127
   936
  }
deba@127
   937
kpeter@192
   938
  /// \brief Return a \ref DigraphWriter class
alpar@209
   939
  ///
kpeter@192
   940
  /// This function just returns a \ref DigraphWriter class.
alpar@156
   941
  /// \relates DigraphWriter
deba@127
   942
  template <typename Digraph>
kpeter@293
   943
  DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
kpeter@293
   944
                                       const char* fn) {
kpeter@293
   945
    DigraphWriter<Digraph> tmp(digraph, fn);
deba@163
   946
    return tmp;
deba@127
   947
  }
deba@165
   948
deba@190
   949
  template <typename Graph>
deba@190
   950
  class GraphWriter;
deba@190
   951
deba@190
   952
  template <typename Graph>
kpeter@293
   953
  GraphWriter<Graph> graphWriter(const Graph& graph,
kpeter@293
   954
                                 std::ostream& os = std::cout);
deba@190
   955
deba@190
   956
  template <typename Graph>
kpeter@293
   957
  GraphWriter<Graph> graphWriter(const Graph& graph, const std::string& fn);
deba@190
   958
deba@190
   959
  template <typename Graph>
kpeter@293
   960
  GraphWriter<Graph> graphWriter(const Graph& graph, const char *fn);
deba@190
   961
deba@165
   962
  /// \ingroup lemon_io
alpar@209
   963
  ///
kpeter@192
   964
  /// \brief \ref lgf-format "LGF" writer for directed graphs
deba@165
   965
  ///
deba@165
   966
  /// This utility writes an \ref lgf-format "LGF" file.
kpeter@192
   967
  ///
kpeter@192
   968
  /// It can be used almost the same way as \c DigraphWriter.
kpeter@192
   969
  /// The only difference is that this class can handle edges and
kpeter@192
   970
  /// edge maps as well as arcs and arc maps.
deba@201
   971
  ///
deba@201
   972
  /// The arc maps are written into the file as two columns, the
deba@201
   973
  /// caption of the columns are the name of the map prefixed with \c
deba@201
   974
  /// '+' and \c '-'. The arcs are written into the \c \@attributes
deba@201
   975
  /// section as a \c '+' or a \c '-' prefix (depends on the direction
deba@201
   976
  /// of the arc) and the label of corresponding edge.
deba@165
   977
  template <typename _Graph>
deba@165
   978
  class GraphWriter {
deba@165
   979
  public:
deba@165
   980
deba@165
   981
    typedef _Graph Graph;
deba@165
   982
    TEMPLATE_GRAPH_TYPEDEFS(Graph);
alpar@209
   983
deba@165
   984
  private:
deba@165
   985
deba@165
   986
deba@165
   987
    std::ostream* _os;
deba@165
   988
    bool local_os;
deba@165
   989
deba@237
   990
    const Graph& _graph;
deba@165
   991
deba@165
   992
    std::string _nodes_caption;
deba@165
   993
    std::string _edges_caption;
deba@165
   994
    std::string _attributes_caption;
alpar@209
   995
deba@165
   996
    typedef std::map<Node, std::string> NodeIndex;
deba@165
   997
    NodeIndex _node_index;
deba@165
   998
    typedef std::map<Edge, std::string> EdgeIndex;
deba@165
   999
    EdgeIndex _edge_index;
deba@165
  1000
alpar@209
  1001
    typedef std::vector<std::pair<std::string,
alpar@209
  1002
      _writer_bits::MapStorageBase<Node>* > > NodeMaps;
alpar@209
  1003
    NodeMaps _node_maps;
deba@165
  1004
alpar@209
  1005
    typedef std::vector<std::pair<std::string,
deba@165
  1006
      _writer_bits::MapStorageBase<Edge>* > >EdgeMaps;
deba@165
  1007
    EdgeMaps _edge_maps;
deba@165
  1008
alpar@209
  1009
    typedef std::vector<std::pair<std::string,
deba@165
  1010
      _writer_bits::ValueStorageBase*> > Attributes;
deba@165
  1011
    Attributes _attributes;
deba@165
  1012
deba@165
  1013
    bool _skip_nodes;
deba@165
  1014
    bool _skip_edges;
deba@165
  1015
deba@165
  1016
  public:
deba@165
  1017
deba@165
  1018
    /// \brief Constructor
deba@165
  1019
    ///
deba@165
  1020
    /// Construct a directed graph writer, which writes to the given
deba@165
  1021
    /// output stream.
kpeter@293
  1022
    GraphWriter(const Graph& graph, std::ostream& os = std::cout)
kpeter@293
  1023
      : _os(&os), local_os(false), _graph(graph),
alpar@209
  1024
        _skip_nodes(false), _skip_edges(false) {}
deba@165
  1025
deba@165
  1026
    /// \brief Constructor
deba@165
  1027
    ///
deba@165
  1028
    /// Construct a directed graph writer, which writes to the given
deba@165
  1029
    /// output file.
kpeter@293
  1030
    GraphWriter(const Graph& graph, const std::string& fn)
deba@165
  1031
      : _os(new std::ofstream(fn.c_str())), local_os(true), _graph(graph),
deba@290
  1032
        _skip_nodes(false), _skip_edges(false) {
deba@295
  1033
      if (!(*_os)) {
deba@295
  1034
        delete _os;
deba@295
  1035
        throw IoError("Cannot write file", fn);
deba@295
  1036
      }
deba@290
  1037
    }
deba@165
  1038
deba@165
  1039
    /// \brief Constructor
deba@165
  1040
    ///
deba@165
  1041
    /// Construct a directed graph writer, which writes to the given
deba@165
  1042
    /// output file.
kpeter@293
  1043
    GraphWriter(const Graph& graph, const char* fn)
deba@165
  1044
      : _os(new std::ofstream(fn)), local_os(true), _graph(graph),
deba@290
  1045
        _skip_nodes(false), _skip_edges(false) {
deba@295
  1046
      if (!(*_os)) {
deba@295
  1047
        delete _os;
deba@295
  1048
        throw IoError("Cannot write file", fn);
deba@295
  1049
      }
deba@290
  1050
    }
deba@165
  1051
deba@165
  1052
    /// \brief Destructor
deba@165
  1053
    ~GraphWriter() {
alpar@209
  1054
      for (typename NodeMaps::iterator it = _node_maps.begin();
alpar@209
  1055
           it != _node_maps.end(); ++it) {
alpar@209
  1056
        delete it->second;
deba@165
  1057
      }
deba@165
  1058
alpar@209
  1059
      for (typename EdgeMaps::iterator it = _edge_maps.begin();
alpar@209
  1060
           it != _edge_maps.end(); ++it) {
alpar@209
  1061
        delete it->second;
deba@165
  1062
      }
deba@165
  1063
alpar@209
  1064
      for (typename Attributes::iterator it = _attributes.begin();
alpar@209
  1065
           it != _attributes.end(); ++it) {
alpar@209
  1066
        delete it->second;
deba@165
  1067
      }
deba@165
  1068
deba@165
  1069
      if (local_os) {
alpar@209
  1070
        delete _os;
deba@165
  1071
      }
deba@165
  1072
    }
alpar@209
  1073
deba@190
  1074
  private:
deba@165
  1075
kpeter@293
  1076
    friend GraphWriter<Graph> graphWriter<>(const Graph& graph,
kpeter@293
  1077
                                            std::ostream& os);
kpeter@293
  1078
    friend GraphWriter<Graph> graphWriter<>(const Graph& graph,
kpeter@293
  1079
                                            const std::string& fn);
kpeter@293
  1080
    friend GraphWriter<Graph> graphWriter<>(const Graph& graph,
kpeter@293
  1081
                                            const char *fn);
deba@190
  1082
alpar@209
  1083
    GraphWriter(GraphWriter& other)
deba@190
  1084
      : _os(other._os), local_os(other.local_os), _graph(other._graph),
alpar@209
  1085
        _skip_nodes(other._skip_nodes), _skip_edges(other._skip_edges) {
deba@190
  1086
deba@190
  1087
      other._os = 0;
deba@190
  1088
      other.local_os = false;
deba@190
  1089
deba@190
  1090
      _node_index.swap(other._node_index);
deba@190
  1091
      _edge_index.swap(other._edge_index);
deba@190
  1092
deba@190
  1093
      _node_maps.swap(other._node_maps);
deba@190
  1094
      _edge_maps.swap(other._edge_maps);
deba@190
  1095
      _attributes.swap(other._attributes);
deba@190
  1096
deba@190
  1097
      _nodes_caption = other._nodes_caption;
deba@190
  1098
      _edges_caption = other._edges_caption;
deba@190
  1099
      _attributes_caption = other._attributes_caption;
deba@190
  1100
    }
deba@190
  1101
deba@165
  1102
    GraphWriter& operator=(const GraphWriter&);
deba@165
  1103
deba@165
  1104
  public:
deba@165
  1105
deba@165
  1106
    /// \name Writing rules
deba@165
  1107
    /// @{
alpar@209
  1108
kpeter@192
  1109
    /// \brief Node map writing rule
deba@165
  1110
    ///
kpeter@192
  1111
    /// Add a node map writing rule to the writer.
deba@165
  1112
    template <typename Map>
deba@165
  1113
    GraphWriter& nodeMap(const std::string& caption, const Map& map) {
deba@165
  1114
      checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
alpar@209
  1115
      _writer_bits::MapStorageBase<Node>* storage =
alpar@209
  1116
        new _writer_bits::MapStorage<Node, Map>(map);
deba@165
  1117
      _node_maps.push_back(std::make_pair(caption, storage));
deba@165
  1118
      return *this;
deba@165
  1119
    }
deba@165
  1120
deba@165
  1121
    /// \brief Node map writing rule
deba@165
  1122
    ///
deba@165
  1123
    /// Add a node map writing rule with specialized converter to the
deba@165
  1124
    /// writer.
deba@165
  1125
    template <typename Map, typename Converter>
alpar@209
  1126
    GraphWriter& nodeMap(const std::string& caption, const Map& map,
alpar@209
  1127
                           const Converter& converter = Converter()) {
deba@165
  1128
      checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
alpar@209
  1129
      _writer_bits::MapStorageBase<Node>* storage =
alpar@209
  1130
        new _writer_bits::MapStorage<Node, Map, Converter>(map, converter);
deba@165
  1131
      _node_maps.push_back(std::make_pair(caption, storage));
deba@165
  1132
      return *this;
deba@165
  1133
    }
deba@165
  1134
deba@165
  1135
    /// \brief Edge map writing rule
deba@165
  1136
    ///
deba@165
  1137
    /// Add an edge map writing rule to the writer.
deba@165
  1138
    template <typename Map>
deba@165
  1139
    GraphWriter& edgeMap(const std::string& caption, const Map& map) {
deba@165
  1140
      checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
alpar@209
  1141
      _writer_bits::MapStorageBase<Edge>* storage =
alpar@209
  1142
        new _writer_bits::MapStorage<Edge, Map>(map);
deba@165
  1143
      _edge_maps.push_back(std::make_pair(caption, storage));
deba@165
  1144
      return *this;
deba@165
  1145
    }
deba@165
  1146
deba@165
  1147
    /// \brief Edge map writing rule
deba@165
  1148
    ///
deba@165
  1149
    /// Add an edge map writing rule with specialized converter to the
deba@165
  1150
    /// writer.
deba@165
  1151
    template <typename Map, typename Converter>
alpar@209
  1152
    GraphWriter& edgeMap(const std::string& caption, const Map& map,
alpar@209
  1153
                          const Converter& converter = Converter()) {
deba@165
  1154
      checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
alpar@209
  1155
      _writer_bits::MapStorageBase<Edge>* storage =
alpar@209
  1156
        new _writer_bits::MapStorage<Edge, Map, Converter>(map, converter);
deba@165
  1157
      _edge_maps.push_back(std::make_pair(caption, storage));
deba@165
  1158
      return *this;
deba@165
  1159
    }
deba@165
  1160
deba@165
  1161
    /// \brief Arc map writing rule
deba@165
  1162
    ///
deba@165
  1163
    /// Add an arc map writing rule to the writer.
deba@165
  1164
    template <typename Map>
deba@165
  1165
    GraphWriter& arcMap(const std::string& caption, const Map& map) {
deba@165
  1166
      checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
alpar@209
  1167
      _writer_bits::MapStorageBase<Edge>* forward_storage =
alpar@209
  1168
        new _writer_bits::GraphArcMapStorage<Graph, true, Map>(_graph, map);
deba@165
  1169
      _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
alpar@209
  1170
      _writer_bits::MapStorageBase<Edge>* backward_storage =
alpar@209
  1171
        new _writer_bits::GraphArcMapStorage<Graph, false, Map>(_graph, map);
deba@165
  1172
      _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
deba@165
  1173
      return *this;
deba@165
  1174
    }
deba@165
  1175
deba@165
  1176
    /// \brief Arc map writing rule
deba@165
  1177
    ///
deba@165
  1178
    /// Add an arc map writing rule with specialized converter to the
deba@165
  1179
    /// writer.
deba@165
  1180
    template <typename Map, typename Converter>
alpar@209
  1181
    GraphWriter& arcMap(const std::string& caption, const Map& map,
alpar@209
  1182
                          const Converter& converter = Converter()) {
deba@165
  1183
      checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
alpar@209
  1184
      _writer_bits::MapStorageBase<Edge>* forward_storage =
alpar@209
  1185
        new _writer_bits::GraphArcMapStorage<Graph, true, Map, Converter>
alpar@209
  1186
        (_graph, map, converter);
deba@165
  1187
      _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
alpar@209
  1188
      _writer_bits::MapStorageBase<Edge>* backward_storage =
alpar@209
  1189
        new _writer_bits::GraphArcMapStorage<Graph, false, Map, Converter>
alpar@209
  1190
        (_graph, map, converter);
deba@165
  1191
      _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
deba@165
  1192
      return *this;
deba@165
  1193
    }
deba@165
  1194
deba@165
  1195
    /// \brief Attribute writing rule
deba@165
  1196
    ///
deba@165
  1197
    /// Add an attribute writing rule to the writer.
deba@165
  1198
    template <typename Value>
deba@165
  1199
    GraphWriter& attribute(const std::string& caption, const Value& value) {
alpar@209
  1200
      _writer_bits::ValueStorageBase* storage =
alpar@209
  1201
        new _writer_bits::ValueStorage<Value>(value);
deba@165
  1202
      _attributes.push_back(std::make_pair(caption, storage));
deba@165
  1203
      return *this;
deba@165
  1204
    }
deba@165
  1205
deba@165
  1206
    /// \brief Attribute writing rule
deba@165
  1207
    ///
deba@165
  1208
    /// Add an attribute writing rule with specialized converter to the
deba@165
  1209
    /// writer.
deba@165
  1210
    template <typename Value, typename Converter>
alpar@209
  1211
    GraphWriter& attribute(const std::string& caption, const Value& value,
alpar@209
  1212
                             const Converter& converter = Converter()) {
alpar@209
  1213
      _writer_bits::ValueStorageBase* storage =
alpar@209
  1214
        new _writer_bits::ValueStorage<Value, Converter>(value, converter);
deba@165
  1215
      _attributes.push_back(std::make_pair(caption, storage));
deba@165
  1216
      return *this;
deba@165
  1217
    }
deba@165
  1218
deba@165
  1219
    /// \brief Node writing rule
deba@165
  1220
    ///
deba@165
  1221
    /// Add a node writing rule to the writer.
deba@165
  1222
    GraphWriter& node(const std::string& caption, const Node& node) {
deba@165
  1223
      typedef _writer_bits::MapLookUpConverter<Node> Converter;
deba@165
  1224
      Converter converter(_node_index);
alpar@209
  1225
      _writer_bits::ValueStorageBase* storage =
alpar@209
  1226
        new _writer_bits::ValueStorage<Node, Converter>(node, converter);
deba@165
  1227
      _attributes.push_back(std::make_pair(caption, storage));
deba@165
  1228
      return *this;
deba@165
  1229
    }
deba@165
  1230
deba@165
  1231
    /// \brief Edge writing rule
deba@165
  1232
    ///
deba@165
  1233
    /// Add an edge writing rule to writer.
deba@165
  1234
    GraphWriter& edge(const std::string& caption, const Edge& edge) {
deba@165
  1235
      typedef _writer_bits::MapLookUpConverter<Edge> Converter;
deba@165
  1236
      Converter converter(_edge_index);
alpar@209
  1237
      _writer_bits::ValueStorageBase* storage =
alpar@209
  1238
        new _writer_bits::ValueStorage<Edge, Converter>(edge, converter);
deba@165
  1239
      _attributes.push_back(std::make_pair(caption, storage));
deba@165
  1240
      return *this;
deba@165
  1241
    }
deba@165
  1242
deba@165
  1243
    /// \brief Arc writing rule
deba@165
  1244
    ///
deba@165
  1245
    /// Add an arc writing rule to writer.
deba@165
  1246
    GraphWriter& arc(const std::string& caption, const Arc& arc) {
deba@165
  1247
      typedef _writer_bits::GraphArcLookUpConverter<Graph> Converter;
deba@165
  1248
      Converter converter(_graph, _edge_index);
alpar@209
  1249
      _writer_bits::ValueStorageBase* storage =
alpar@209
  1250
        new _writer_bits::ValueStorage<Arc, Converter>(arc, converter);
deba@165
  1251
      _attributes.push_back(std::make_pair(caption, storage));
deba@165
  1252
      return *this;
deba@165
  1253
    }
deba@165
  1254
kpeter@192
  1255
    /// \name Section captions
deba@165
  1256
    /// @{
deba@165
  1257
kpeter@192
  1258
    /// \brief Add an additional caption to the \c \@nodes section
deba@165
  1259
    ///
kpeter@192
  1260
    /// Add an additional caption to the \c \@nodes section.
deba@165
  1261
    GraphWriter& nodes(const std::string& caption) {
deba@165
  1262
      _nodes_caption = caption;
deba@165
  1263
      return *this;
deba@165
  1264
    }
deba@165
  1265
kpeter@192
  1266
    /// \brief Add an additional caption to the \c \@arcs section
deba@165
  1267
    ///
kpeter@192
  1268
    /// Add an additional caption to the \c \@arcs section.
deba@165
  1269
    GraphWriter& edges(const std::string& caption) {
deba@165
  1270
      _edges_caption = caption;
deba@165
  1271
      return *this;
deba@165
  1272
    }
deba@165
  1273
kpeter@192
  1274
    /// \brief Add an additional caption to the \c \@attributes section
deba@165
  1275
    ///
kpeter@192
  1276
    /// Add an additional caption to the \c \@attributes section.
deba@165
  1277
    GraphWriter& attributes(const std::string& caption) {
deba@165
  1278
      _attributes_caption = caption;
deba@165
  1279
      return *this;
deba@165
  1280
    }
deba@165
  1281
deba@165
  1282
    /// \name Skipping section
deba@165
  1283
    /// @{
deba@165
  1284
deba@165
  1285
    /// \brief Skip writing the node set
deba@165
  1286
    ///
kpeter@192
  1287
    /// The \c \@nodes section will not be written to the stream.
deba@165
  1288
    GraphWriter& skipNodes() {
deba@165
  1289
      LEMON_ASSERT(!_skip_nodes, "Multiple usage of skipNodes() member");
deba@185
  1290
      _skip_nodes = true;
deba@165
  1291
      return *this;
deba@165
  1292
    }
deba@165
  1293
deba@165
  1294
    /// \brief Skip writing edge set
deba@165
  1295
    ///
kpeter@192
  1296
    /// The \c \@edges section will not be written to the stream.
deba@165
  1297
    GraphWriter& skipEdges() {
deba@165
  1298
      LEMON_ASSERT(!_skip_edges, "Multiple usage of skipEdges() member");
deba@185
  1299
      _skip_edges = true;
deba@165
  1300
      return *this;
deba@165
  1301
    }
deba@165
  1302
deba@165
  1303
    /// @}
deba@165
  1304
deba@165
  1305
  private:
deba@165
  1306
deba@165
  1307
    void writeNodes() {
deba@165
  1308
      _writer_bits::MapStorageBase<Node>* label = 0;
deba@165
  1309
      for (typename NodeMaps::iterator it = _node_maps.begin();
alpar@209
  1310
           it != _node_maps.end(); ++it) {
deba@165
  1311
        if (it->first == "label") {
alpar@209
  1312
          label = it->second;
alpar@209
  1313
          break;
alpar@209
  1314
        }
deba@165
  1315
      }
deba@165
  1316
deba@165
  1317
      *_os << "@nodes";
deba@165
  1318
      if (!_nodes_caption.empty()) {
alpar@209
  1319
        _writer_bits::writeToken(*_os << ' ', _nodes_caption);
deba@165
  1320
      }
deba@165
  1321
      *_os << std::endl;
deba@165
  1322
deba@165
  1323
      if (label == 0) {
alpar@209
  1324
        *_os << "label" << '\t';
deba@165
  1325
      }
deba@165
  1326
      for (typename NodeMaps::iterator it = _node_maps.begin();
alpar@209
  1327
           it != _node_maps.end(); ++it) {
alpar@209
  1328
        _writer_bits::writeToken(*_os, it->first) << '\t';
deba@165
  1329
      }
deba@165
  1330
      *_os << std::endl;
deba@165
  1331
deba@165
  1332
      std::vector<Node> nodes;
deba@165
  1333
      for (NodeIt n(_graph); n != INVALID; ++n) {
alpar@209
  1334
        nodes.push_back(n);
deba@165
  1335
      }
alpar@209
  1336
deba@165
  1337
      if (label == 0) {
alpar@209
  1338
        IdMap<Graph, Node> id_map(_graph);
alpar@209
  1339
        _writer_bits::MapLess<IdMap<Graph, Node> > id_less(id_map);
alpar@209
  1340
        std::sort(nodes.begin(), nodes.end(), id_less);
deba@165
  1341
      } else {
alpar@209
  1342
        label->sort(nodes);
deba@165
  1343
      }
deba@165
  1344
deba@165
  1345
      for (int i = 0; i < static_cast<int>(nodes.size()); ++i) {
alpar@209
  1346
        Node n = nodes[i];
alpar@209
  1347
        if (label == 0) {
alpar@209
  1348
          std::ostringstream os;
alpar@209
  1349
          os << _graph.id(n);
alpar@209
  1350
          _writer_bits::writeToken(*_os, os.str());
alpar@209
  1351
          *_os << '\t';
alpar@209
  1352
          _node_index.insert(std::make_pair(n, os.str()));
alpar@209
  1353
        }
alpar@209
  1354
        for (typename NodeMaps::iterator it = _node_maps.begin();
alpar@209
  1355
             it != _node_maps.end(); ++it) {
alpar@209
  1356
          std::string value = it->second->get(n);
alpar@209
  1357
          _writer_bits::writeToken(*_os, value);
alpar@209
  1358
          if (it->first == "label") {
alpar@209
  1359
            _node_index.insert(std::make_pair(n, value));
alpar@209
  1360
          }
alpar@209
  1361
          *_os << '\t';
alpar@209
  1362
        }
alpar@209
  1363
        *_os << std::endl;
deba@165
  1364
      }
deba@165
  1365
    }
deba@165
  1366
deba@185
  1367
    void createNodeIndex() {
deba@185
  1368
      _writer_bits::MapStorageBase<Node>* label = 0;
deba@185
  1369
      for (typename NodeMaps::iterator it = _node_maps.begin();
alpar@209
  1370
           it != _node_maps.end(); ++it) {
deba@185
  1371
        if (it->first == "label") {
alpar@209
  1372
          label = it->second;
alpar@209
  1373
          break;
alpar@209
  1374
        }
deba@185
  1375
      }
deba@185
  1376
deba@185
  1377
      if (label == 0) {
alpar@209
  1378
        for (NodeIt n(_graph); n != INVALID; ++n) {
alpar@209
  1379
          std::ostringstream os;
alpar@209
  1380
          os << _graph.id(n);
alpar@209
  1381
          _node_index.insert(std::make_pair(n, os.str()));
alpar@209
  1382
        }
deba@185
  1383
      } else {
alpar@209
  1384
        for (NodeIt n(_graph); n != INVALID; ++n) {
alpar@209
  1385
          std::string value = label->get(n);
alpar@209
  1386
          _node_index.insert(std::make_pair(n, value));
alpar@209
  1387
        }
deba@185
  1388
      }
deba@185
  1389
    }
deba@185
  1390
deba@165
  1391
    void writeEdges() {
deba@165
  1392
      _writer_bits::MapStorageBase<Edge>* label = 0;
deba@165
  1393
      for (typename EdgeMaps::iterator it = _edge_maps.begin();
alpar@209
  1394
           it != _edge_maps.end(); ++it) {
deba@165
  1395
        if (it->first == "label") {
alpar@209
  1396
          label = it->second;
alpar@209
  1397
          break;
alpar@209
  1398
        }
deba@165
  1399
      }
deba@165
  1400
deba@165
  1401
      *_os << "@edges";
deba@165
  1402
      if (!_edges_caption.empty()) {
alpar@209
  1403
        _writer_bits::writeToken(*_os << ' ', _edges_caption);
deba@165
  1404
      }
deba@165
  1405
      *_os << std::endl;
deba@165
  1406
deba@165
  1407
      *_os << '\t' << '\t';
deba@165
  1408
      if (label == 0) {
alpar@209
  1409
        *_os << "label" << '\t';
deba@165
  1410
      }
deba@165
  1411
      for (typename EdgeMaps::iterator it = _edge_maps.begin();
alpar@209
  1412
           it != _edge_maps.end(); ++it) {
alpar@209
  1413
        _writer_bits::writeToken(*_os, it->first) << '\t';
deba@165
  1414
      }
deba@165
  1415
      *_os << std::endl;
deba@165
  1416
deba@165
  1417
      std::vector<Edge> edges;
deba@165
  1418
      for (EdgeIt n(_graph); n != INVALID; ++n) {
alpar@209
  1419
        edges.push_back(n);
deba@165
  1420
      }
alpar@209
  1421
deba@165
  1422
      if (label == 0) {
alpar@209
  1423
        IdMap<Graph, Edge> id_map(_graph);
alpar@209
  1424
        _writer_bits::MapLess<IdMap<Graph, Edge> > id_less(id_map);
alpar@209
  1425
        std::sort(edges.begin(), edges.end(), id_less);
deba@165
  1426
      } else {
alpar@209
  1427
        label->sort(edges);
deba@165
  1428
      }
deba@165
  1429
deba@165
  1430
      for (int i = 0; i < static_cast<int>(edges.size()); ++i) {
alpar@209
  1431
        Edge e = edges[i];
alpar@209
  1432
        _writer_bits::writeToken(*_os, _node_index.
alpar@209
  1433
                                 find(_graph.u(e))->second);
alpar@209
  1434
        *_os << '\t';
alpar@209
  1435
        _writer_bits::writeToken(*_os, _node_index.
alpar@209
  1436
                                 find(_graph.v(e))->second);
alpar@209
  1437
        *_os << '\t';
alpar@209
  1438
        if (label == 0) {
alpar@209
  1439
          std::ostringstream os;
alpar@209
  1440
          os << _graph.id(e);
alpar@209
  1441
          _writer_bits::writeToken(*_os, os.str());
alpar@209
  1442
          *_os << '\t';
alpar@209
  1443
          _edge_index.insert(std::make_pair(e, os.str()));
alpar@209
  1444
        }
alpar@209
  1445
        for (typename EdgeMaps::iterator it = _edge_maps.begin();
alpar@209
  1446
             it != _edge_maps.end(); ++it) {
alpar@209
  1447
          std::string value = it->second->get(e);
alpar@209
  1448
          _writer_bits::writeToken(*_os, value);
alpar@209
  1449
          if (it->first == "label") {
alpar@209
  1450
            _edge_index.insert(std::make_pair(e, value));
alpar@209
  1451
          }
alpar@209
  1452
          *_os << '\t';
alpar@209
  1453
        }
alpar@209
  1454
        *_os << std::endl;
deba@165
  1455
      }
deba@165
  1456
    }
deba@165
  1457
deba@185
  1458
    void createEdgeIndex() {
deba@185
  1459
      _writer_bits::MapStorageBase<Edge>* label = 0;
deba@185
  1460
      for (typename EdgeMaps::iterator it = _edge_maps.begin();
alpar@209
  1461
           it != _edge_maps.end(); ++it) {
deba@185
  1462
        if (it->first == "label") {
alpar@209
  1463
          label = it->second;
alpar@209
  1464
          break;
alpar@209
  1465
        }
deba@185
  1466
      }
deba@185
  1467
deba@185
  1468
      if (label == 0) {
alpar@209
  1469
        for (EdgeIt e(_graph); e != INVALID; ++e) {
alpar@209
  1470
          std::ostringstream os;
alpar@209
  1471
          os << _graph.id(e);
alpar@209
  1472
          _edge_index.insert(std::make_pair(e, os.str()));
alpar@209
  1473
        }
deba@185
  1474
      } else {
alpar@209
  1475
        for (EdgeIt e(_graph); e != INVALID; ++e) {
alpar@209
  1476
          std::string value = label->get(e);
alpar@209
  1477
          _edge_index.insert(std::make_pair(e, value));
alpar@209
  1478
        }
deba@185
  1479
      }
deba@185
  1480
    }
deba@185
  1481
deba@165
  1482
    void writeAttributes() {
deba@165
  1483
      if (_attributes.empty()) return;
deba@165
  1484
      *_os << "@attributes";
deba@165
  1485
      if (!_attributes_caption.empty()) {
alpar@209
  1486
        _writer_bits::writeToken(*_os << ' ', _attributes_caption);
deba@165
  1487
      }
deba@165
  1488
      *_os << std::endl;
deba@165
  1489
      for (typename Attributes::iterator it = _attributes.begin();
alpar@209
  1490
           it != _attributes.end(); ++it) {
alpar@209
  1491
        _writer_bits::writeToken(*_os, it->first) << ' ';
alpar@209
  1492
        _writer_bits::writeToken(*_os, it->second->get());
alpar@209
  1493
        *_os << std::endl;
deba@165
  1494
      }
deba@165
  1495
    }
alpar@209
  1496
deba@165
  1497
  public:
alpar@209
  1498
alpar@209
  1499
    /// \name Execution of the writer
deba@165
  1500
    /// @{
deba@165
  1501
deba@165
  1502
    /// \brief Start the batch processing
deba@165
  1503
    ///
kpeter@192
  1504
    /// This function starts the batch processing.
deba@165
  1505
    void run() {
deba@165
  1506
      if (!_skip_nodes) {
alpar@209
  1507
        writeNodes();
deba@185
  1508
      } else {
alpar@209
  1509
        createNodeIndex();
deba@165
  1510
      }
alpar@209
  1511
      if (!_skip_edges) {
alpar@209
  1512
        writeEdges();
deba@185
  1513
      } else {
alpar@209
  1514
        createEdgeIndex();
deba@165
  1515
      }
deba@165
  1516
      writeAttributes();
deba@165
  1517
    }
deba@165
  1518
kpeter@192
  1519
    /// \brief Give back the stream of the writer
deba@165
  1520
    ///
kpeter@192
  1521
    /// Give back the stream of the writer
deba@165
  1522
    std::ostream& ostream() {
deba@165
  1523
      return *_os;
deba@165
  1524
    }
deba@165
  1525
deba@165
  1526
    /// @}
deba@165
  1527
  };
deba@165
  1528
kpeter@192
  1529
  /// \brief Return a \ref GraphWriter class
alpar@209
  1530
  ///
kpeter@192
  1531
  /// This function just returns a \ref GraphWriter class.
deba@165
  1532
  /// \relates GraphWriter
deba@165
  1533
  template <typename Graph>
kpeter@293
  1534
  GraphWriter<Graph> graphWriter(const Graph& graph,
kpeter@293
  1535
                                 std::ostream& os = std::cout) {
kpeter@293
  1536
    GraphWriter<Graph> tmp(graph, os);
deba@165
  1537
    return tmp;
deba@165
  1538
  }
deba@165
  1539
kpeter@192
  1540
  /// \brief Return a \ref GraphWriter class
alpar@209
  1541
  ///
kpeter@192
  1542
  /// This function just returns a \ref GraphWriter class.
deba@165
  1543
  /// \relates GraphWriter
deba@165
  1544
  template <typename Graph>
kpeter@293
  1545
  GraphWriter<Graph> graphWriter(const Graph& graph, const std::string& fn) {
kpeter@293
  1546
    GraphWriter<Graph> tmp(graph, fn);
deba@165
  1547
    return tmp;
deba@165
  1548
  }
deba@165
  1549
kpeter@192
  1550
  /// \brief Return a \ref GraphWriter class
alpar@209
  1551
  ///
kpeter@192
  1552
  /// This function just returns a \ref GraphWriter class.
deba@165
  1553
  /// \relates GraphWriter
deba@165
  1554
  template <typename Graph>
kpeter@293
  1555
  GraphWriter<Graph> graphWriter(const Graph& graph, const char* fn) {
kpeter@293
  1556
    GraphWriter<Graph> tmp(graph, fn);
deba@165
  1557
    return tmp;
deba@165
  1558
  }
deba@248
  1559
deba@248
  1560
  class SectionWriter;
deba@248
  1561
deba@248
  1562
  SectionWriter sectionWriter(std::istream& is);
deba@248
  1563
  SectionWriter sectionWriter(const std::string& fn);
deba@248
  1564
  SectionWriter sectionWriter(const char* fn);
deba@248
  1565
deba@248
  1566
  /// \ingroup lemon_io
deba@248
  1567
  ///
deba@248
  1568
  /// \brief Section writer class
deba@248
  1569
  ///
deba@248
  1570
  /// In the \ref lgf-format "LGF" file extra sections can be placed,
deba@248
  1571
  /// which contain any data in arbitrary format. Such sections can be
deba@248
  1572
  /// written with this class. A writing rule can be added to the
deba@248
  1573
  /// class with two different functions. With the \c sectionLines()
deba@248
  1574
  /// function a generator can write the section line-by-line, while
deba@248
  1575
  /// with the \c sectionStream() member the section can be written to
deba@248
  1576
  /// an output stream.
deba@248
  1577
  class SectionWriter {
deba@248
  1578
  private:
deba@248
  1579
deba@248
  1580
    std::ostream* _os;
deba@248
  1581
    bool local_os;
deba@248
  1582
deba@248
  1583
    typedef std::vector<std::pair<std::string, _writer_bits::Section*> >
deba@248
  1584
    Sections;
deba@248
  1585
deba@248
  1586
    Sections _sections;
deba@248
  1587
deba@248
  1588
  public:
deba@248
  1589
deba@248
  1590
    /// \brief Constructor
deba@248
  1591
    ///
deba@248
  1592
    /// Construct a section writer, which writes to the given output
deba@248
  1593
    /// stream.
deba@248
  1594
    SectionWriter(std::ostream& os)
deba@248
  1595
      : _os(&os), local_os(false) {}
deba@248
  1596
deba@248
  1597
    /// \brief Constructor
deba@248
  1598
    ///
deba@248
  1599
    /// Construct a section writer, which writes into the given file.
deba@248
  1600
    SectionWriter(const std::string& fn)
deba@290
  1601
      : _os(new std::ofstream(fn.c_str())), local_os(true) {
deba@295
  1602
      if (!(*_os)) {
deba@295
  1603
        delete _os;
deba@295
  1604
        throw IoError("Cannot write file", fn);
deba@295
  1605
      }
deba@290
  1606
    }
deba@248
  1607
deba@248
  1608
    /// \brief Constructor
deba@248
  1609
    ///
deba@248
  1610
    /// Construct a section writer, which writes into the given file.
deba@248
  1611
    SectionWriter(const char* fn)
deba@290
  1612
      : _os(new std::ofstream(fn)), local_os(true) {
deba@295
  1613
      if (!(*_os)) {
deba@295
  1614
        delete _os;
deba@295
  1615
        throw IoError("Cannot write file", fn);
deba@295
  1616
      }
deba@290
  1617
    }
deba@248
  1618
deba@248
  1619
    /// \brief Destructor
deba@248
  1620
    ~SectionWriter() {
deba@248
  1621
      for (Sections::iterator it = _sections.begin();
deba@248
  1622
           it != _sections.end(); ++it) {
deba@248
  1623
        delete it->second;
deba@248
  1624
      }
deba@248
  1625
deba@248
  1626
      if (local_os) {
deba@248
  1627
        delete _os;
deba@248
  1628
      }
deba@248
  1629
deba@248
  1630
    }
deba@248
  1631
deba@248
  1632
  private:
deba@248
  1633
deba@248
  1634
    friend SectionWriter sectionWriter(std::ostream& os);
deba@248
  1635
    friend SectionWriter sectionWriter(const std::string& fn);
deba@248
  1636
    friend SectionWriter sectionWriter(const char* fn);
deba@248
  1637
deba@248
  1638
    SectionWriter(SectionWriter& other)
deba@248
  1639
      : _os(other._os), local_os(other.local_os) {
deba@248
  1640
deba@248
  1641
      other._os = 0;
deba@248
  1642
      other.local_os = false;
deba@248
  1643
deba@248
  1644
      _sections.swap(other._sections);
deba@248
  1645
    }
deba@248
  1646
deba@248
  1647
    SectionWriter& operator=(const SectionWriter&);
deba@248
  1648
deba@248
  1649
  public:
deba@248
  1650
deba@248
  1651
    /// \name Section writers
deba@248
  1652
    /// @{
deba@248
  1653
deba@248
  1654
    /// \brief Add a section writer with line oriented writing
deba@248
  1655
    ///
deba@248
  1656
    /// The first parameter is the type descriptor of the section, the
deba@248
  1657
    /// second is a generator with std::string values. At the writing
deba@248
  1658
    /// process, the returned \c std::string will be written into the
deba@248
  1659
    /// output file until it is an empty string.
deba@248
  1660
    ///
deba@248
  1661
    /// For example, an integer vector is written into a section.
deba@248
  1662
    ///\code
deba@248
  1663
    ///  @numbers
deba@248
  1664
    ///  12 45 23 78
deba@248
  1665
    ///  4 28 38 28
deba@248
  1666
    ///  23 6 16
deba@248
  1667
    ///\endcode
deba@248
  1668
    ///
deba@248
  1669
    /// The generator is implemented as a struct.
deba@248
  1670
    ///\code
deba@248
  1671
    ///  struct NumberSection {
deba@248
  1672
    ///    std::vector<int>::const_iterator _it, _end;
deba@248
  1673
    ///    NumberSection(const std::vector<int>& data)
deba@248
  1674
    ///      : _it(data.begin()), _end(data.end()) {}
deba@248
  1675
    ///    std::string operator()() {
deba@248
  1676
    ///      int rem_in_line = 4;
deba@248
  1677
    ///      std::ostringstream ls;
deba@248
  1678
    ///      while (rem_in_line > 0 && _it != _end) {
deba@248
  1679
    ///        ls << *(_it++) << ' ';
deba@248
  1680
    ///        --rem_in_line;
deba@248
  1681
    ///      }
deba@248
  1682
    ///      return ls.str();
deba@248
  1683
    ///    }
deba@248
  1684
    ///  };
deba@248
  1685
    ///
deba@248
  1686
    ///  // ...
deba@248
  1687
    ///
deba@248
  1688
    ///  writer.sectionLines("numbers", NumberSection(vec));
deba@248
  1689
    ///\endcode
deba@248
  1690
    template <typename Functor>
deba@248
  1691
    SectionWriter& sectionLines(const std::string& type, Functor functor) {
deba@248
  1692
      LEMON_ASSERT(!type.empty(), "Type is empty.");
deba@248
  1693
      _sections.push_back(std::make_pair(type,
deba@248
  1694
        new _writer_bits::LineSection<Functor>(functor)));
deba@248
  1695
      return *this;
deba@248
  1696
    }
deba@248
  1697
deba@248
  1698
deba@248
  1699
    /// \brief Add a section writer with stream oriented writing
deba@248
  1700
    ///
deba@248
  1701
    /// The first parameter is the type of the section, the second is
deba@248
  1702
    /// a functor, which takes a \c std::ostream& parameter. The
deba@248
  1703
    /// functor writes the section to the output stream.
deba@248
  1704
    /// \warning The last line must be closed with end-line character.
deba@248
  1705
    template <typename Functor>
deba@248
  1706
    SectionWriter& sectionStream(const std::string& type, Functor functor) {
deba@248
  1707
      LEMON_ASSERT(!type.empty(), "Type is empty.");
deba@248
  1708
      _sections.push_back(std::make_pair(type,
deba@248
  1709
         new _writer_bits::StreamSection<Functor>(functor)));
deba@248
  1710
      return *this;
deba@248
  1711
    }
deba@248
  1712
deba@248
  1713
    /// @}
deba@248
  1714
deba@248
  1715
  public:
deba@248
  1716
deba@248
  1717
deba@248
  1718
    /// \name Execution of the writer
deba@248
  1719
    /// @{
deba@248
  1720
deba@248
  1721
    /// \brief Start the batch processing
deba@248
  1722
    ///
deba@248
  1723
    /// This function starts the batch processing.
deba@248
  1724
    void run() {
deba@248
  1725
deba@248
  1726
      LEMON_ASSERT(_os != 0, "This writer is assigned to an other writer");
deba@248
  1727
deba@248
  1728
      for (Sections::iterator it = _sections.begin();
deba@248
  1729
           it != _sections.end(); ++it) {
deba@248
  1730
        (*_os) << '@' << it->first << std::endl;
deba@248
  1731
        it->second->process(*_os);
deba@248
  1732
      }
deba@248
  1733
    }
deba@248
  1734
deba@248
  1735
    /// \brief Give back the stream of the writer
deba@248
  1736
    ///
deba@248
  1737
    /// Returns the stream of the writer
deba@248
  1738
    std::ostream& ostream() {
deba@248
  1739
      return *_os;
deba@248
  1740
    }
deba@248
  1741
deba@248
  1742
    /// @}
deba@248
  1743
deba@248
  1744
  };
deba@248
  1745
deba@248
  1746
  /// \brief Return a \ref SectionWriter class
deba@248
  1747
  ///
deba@248
  1748
  /// This function just returns a \ref SectionWriter class.
deba@248
  1749
  /// \relates SectionWriter
deba@248
  1750
  inline SectionWriter sectionWriter(std::ostream& os) {
deba@248
  1751
    SectionWriter tmp(os);
deba@248
  1752
    return tmp;
deba@248
  1753
  }
deba@248
  1754
deba@248
  1755
  /// \brief Return a \ref SectionWriter class
deba@248
  1756
  ///
deba@248
  1757
  /// This function just returns a \ref SectionWriter class.
deba@248
  1758
  /// \relates SectionWriter
deba@248
  1759
  inline SectionWriter sectionWriter(const std::string& fn) {
deba@248
  1760
    SectionWriter tmp(fn);
deba@248
  1761
    return tmp;
deba@248
  1762
  }
deba@248
  1763
deba@248
  1764
  /// \brief Return a \ref SectionWriter class
deba@248
  1765
  ///
deba@248
  1766
  /// This function just returns a \ref SectionWriter class.
deba@248
  1767
  /// \relates SectionWriter
deba@248
  1768
  inline SectionWriter sectionWriter(const char* fn) {
deba@248
  1769
    SectionWriter tmp(fn);
deba@248
  1770
    return tmp;
deba@248
  1771
  }
deba@127
  1772
}
deba@127
  1773
deba@127
  1774
#endif