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