1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2008
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
21 ///\brief \ref lgf-format "LEMON Graph Format" writer.
24 #ifndef LEMON_LGF_WRITER_H
25 #define LEMON_LGF_WRITER_H
36 #include <lemon/assert.h>
37 #include <lemon/core.h>
38 #include <lemon/maps.h>
40 #include <lemon/concept_check.h>
41 #include <lemon/concepts/maps.h>
45 namespace _writer_bits {
47 template <typename Value>
48 struct DefaultConverter {
49 std::string operator()(const Value& value) {
50 std::ostringstream os;
57 bool operator<(const T&, const T&) {
58 throw FormatError("Label map is not comparable");
61 template <typename _Map>
65 typedef typename Map::Key Item;
71 MapLess(const Map& map) : _map(map) {}
73 bool operator()(const Item& left, const Item& right) {
74 return _map[left] < _map[right];
78 template <typename _Graph, bool _dir, typename _Map>
79 class GraphArcMapLess {
83 typedef typename Graph::Edge Item;
90 GraphArcMapLess(const Graph& graph, const Map& map)
91 : _graph(graph), _map(map) {}
93 bool operator()(const Item& left, const Item& right) {
94 return _map[_graph.direct(left, _dir)] <
95 _map[_graph.direct(right, _dir)];
99 template <typename _Item>
100 class MapStorageBase {
106 virtual ~MapStorageBase() {}
108 virtual std::string get(const Item& item) = 0;
109 virtual void sort(std::vector<Item>&) = 0;
112 template <typename _Item, typename _Map,
113 typename _Converter = DefaultConverter<typename _Map::Value> >
114 class MapStorage : public MapStorageBase<_Item> {
117 typedef _Converter Converter;
122 Converter _converter;
125 MapStorage(const Map& map, const Converter& converter = Converter())
126 : _map(map), _converter(converter) {}
127 virtual ~MapStorage() {}
129 virtual std::string get(const Item& item) {
130 return _converter(_map[item]);
132 virtual void sort(std::vector<Item>& items) {
133 MapLess<Map> less(_map);
134 std::sort(items.begin(), items.end(), less);
138 template <typename _Graph, bool _dir, typename _Map,
139 typename _Converter = DefaultConverter<typename _Map::Value> >
140 class GraphArcMapStorage : public MapStorageBase<typename _Graph::Edge> {
143 typedef _Converter Converter;
144 typedef _Graph Graph;
145 typedef typename Graph::Edge Item;
146 static const bool dir = _dir;
151 Converter _converter;
154 GraphArcMapStorage(const Graph& graph, const Map& map,
155 const Converter& converter = Converter())
156 : _graph(graph), _map(map), _converter(converter) {}
157 virtual ~GraphArcMapStorage() {}
159 virtual std::string get(const Item& item) {
160 return _converter(_map[_graph.direct(item, dir)]);
162 virtual void sort(std::vector<Item>& items) {
163 GraphArcMapLess<Graph, dir, Map> less(_graph, _map);
164 std::sort(items.begin(), items.end(), less);
168 class ValueStorageBase {
170 ValueStorageBase() {}
171 virtual ~ValueStorageBase() {}
173 virtual std::string get() = 0;
176 template <typename _Value, typename _Converter = DefaultConverter<_Value> >
177 class ValueStorage : public ValueStorageBase {
179 typedef _Value Value;
180 typedef _Converter Converter;
184 Converter _converter;
187 ValueStorage(const Value& value, const Converter& converter = Converter())
188 : _value(value), _converter(converter) {}
190 virtual std::string get() {
191 return _converter(_value);
195 template <typename Value>
196 struct MapLookUpConverter {
197 const std::map<Value, std::string>& _map;
199 MapLookUpConverter(const std::map<Value, std::string>& map)
202 std::string operator()(const Value& str) {
203 typename std::map<Value, std::string>::const_iterator it =
205 if (it == _map.end()) {
206 throw FormatError("Item not found");
212 template <typename Graph>
213 struct GraphArcLookUpConverter {
215 const std::map<typename Graph::Edge, std::string>& _map;
217 GraphArcLookUpConverter(const Graph& graph,
218 const std::map<typename Graph::Edge,
220 : _graph(graph), _map(map) {}
222 std::string operator()(const typename Graph::Arc& val) {
223 typename std::map<typename Graph::Edge, std::string>
224 ::const_iterator it = _map.find(val);
225 if (it == _map.end()) {
226 throw FormatError("Item not found");
228 return (_graph.direction(val) ? '+' : '-') + it->second;
232 inline bool isWhiteSpace(char c) {
233 return c == ' ' || c == '\t' || c == '\v' ||
234 c == '\n' || c == '\r' || c == '\f';
237 inline bool isEscaped(char c) {
238 return c == '\\' || c == '\"' || c == '\'' ||
239 c == '\a' || c == '\b';
242 inline static void writeEscape(std::ostream& os, char c) {
273 std::ios::fmtflags flags = os.flags();
274 os << '\\' << std::oct << static_cast<int>(c);
283 inline bool requireEscape(const std::string& str) {
284 if (str.empty() || str[0] == '@') return true;
285 std::istringstream is(str);
288 if (isWhiteSpace(c) || isEscaped(c)) {
295 inline std::ostream& writeToken(std::ostream& os, const std::string& str) {
297 if (requireEscape(str)) {
299 for (std::string::const_iterator it = str.begin();
300 it != str.end(); ++it) {
301 writeEscape(os, *it);
312 virtual ~Section() {}
313 virtual void process(std::ostream& os) = 0;
316 template <typename Functor>
317 class LineSection : public Section {
324 LineSection(const Functor& functor) : _functor(functor) {}
325 virtual ~LineSection() {}
327 virtual void process(std::ostream& os) {
329 while (!(line = _functor()).empty()) os << line << std::endl;
333 template <typename Functor>
334 class StreamSection : public Section {
341 StreamSection(const Functor& functor) : _functor(functor) {}
342 virtual ~StreamSection() {}
344 virtual void process(std::ostream& os) {
351 template <typename Digraph>
354 template <typename Digraph>
355 DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
356 std::ostream& os = std::cout);
358 template <typename Digraph>
359 DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
360 const std::string& fn);
362 template <typename Digraph>
363 DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
366 /// \ingroup lemon_io
368 /// \brief \ref lgf-format "LGF" writer for directed graphs
370 /// This utility writes an \ref lgf-format "LGF" file.
372 /// The writing method does a batch processing. The user creates a
373 /// writer object, then various writing rules can be added to the
374 /// writer, and eventually the writing is executed with the \c run()
375 /// member function. A map writing rule can be added to the writer
376 /// with the \c nodeMap() or \c arcMap() members. An optional
377 /// converter parameter can also be added as a standard functor
378 /// converting from the value type of the map to \c std::string. If it
379 /// is set, it will determine how the value type of the map is written to
380 /// the output stream. If the functor is not set, then a default
381 /// conversion will be used. The \c attribute(), \c node() and \c
382 /// arc() functions are used to add attribute writing rules.
385 /// DigraphWriter<Digraph>(digraph, std::cout).
386 /// nodeMap("coordinates", coord_map).
387 /// nodeMap("size", size).
388 /// nodeMap("title", title).
389 /// arcMap("capacity", cap_map).
390 /// node("source", src).
391 /// node("target", trg).
392 /// attribute("caption", caption).
397 /// By default, the writer does not write additional captions to the
398 /// sections, but they can be give as an optional parameter of
399 /// the \c nodes(), \c arcs() or \c
400 /// attributes() functions.
402 /// The \c skipNodes() and \c skipArcs() functions forbid the
403 /// writing of the sections. If two arc sections should be written
404 /// to the output, it can be done in two passes, the first pass
405 /// writes the node section and the first arc section, then the
406 /// second pass skips the node section and writes just the arc
407 /// section to the stream. The output stream can be retrieved with
408 /// the \c ostream() function, hence the second pass can append its
409 /// output to the output of the first pass.
410 template <typename _Digraph>
411 class DigraphWriter {
414 typedef _Digraph Digraph;
415 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
423 const Digraph& _digraph;
425 std::string _nodes_caption;
426 std::string _arcs_caption;
427 std::string _attributes_caption;
429 typedef std::map<Node, std::string> NodeIndex;
430 NodeIndex _node_index;
431 typedef std::map<Arc, std::string> ArcIndex;
434 typedef std::vector<std::pair<std::string,
435 _writer_bits::MapStorageBase<Node>* > > NodeMaps;
438 typedef std::vector<std::pair<std::string,
439 _writer_bits::MapStorageBase<Arc>* > >ArcMaps;
442 typedef std::vector<std::pair<std::string,
443 _writer_bits::ValueStorageBase*> > Attributes;
444 Attributes _attributes;
451 /// \brief Constructor
453 /// Construct a directed graph writer, which writes to the given
455 DigraphWriter(const Digraph& digraph, std::ostream& os = std::cout)
456 : _os(&os), local_os(false), _digraph(digraph),
457 _skip_nodes(false), _skip_arcs(false) {}
459 /// \brief Constructor
461 /// Construct a directed graph writer, which writes to the given
463 DigraphWriter(const Digraph& digraph, const std::string& fn)
464 : _os(new std::ofstream(fn.c_str())), local_os(true), _digraph(digraph),
465 _skip_nodes(false), _skip_arcs(false) {
468 throw IoError("Cannot write file", fn);
472 /// \brief Constructor
474 /// Construct a directed graph writer, which writes to the given
476 DigraphWriter(const Digraph& digraph, const char* fn)
477 : _os(new std::ofstream(fn)), local_os(true), _digraph(digraph),
478 _skip_nodes(false), _skip_arcs(false) {
481 throw IoError("Cannot write file", fn);
485 /// \brief Destructor
487 for (typename NodeMaps::iterator it = _node_maps.begin();
488 it != _node_maps.end(); ++it) {
492 for (typename ArcMaps::iterator it = _arc_maps.begin();
493 it != _arc_maps.end(); ++it) {
497 for (typename Attributes::iterator it = _attributes.begin();
498 it != _attributes.end(); ++it) {
509 friend DigraphWriter<Digraph> digraphWriter<>(const Digraph& digraph,
511 friend DigraphWriter<Digraph> digraphWriter<>(const Digraph& digraph,
512 const std::string& fn);
513 friend DigraphWriter<Digraph> digraphWriter<>(const Digraph& digraph,
516 DigraphWriter(DigraphWriter& other)
517 : _os(other._os), local_os(other.local_os), _digraph(other._digraph),
518 _skip_nodes(other._skip_nodes), _skip_arcs(other._skip_arcs) {
521 other.local_os = false;
523 _node_index.swap(other._node_index);
524 _arc_index.swap(other._arc_index);
526 _node_maps.swap(other._node_maps);
527 _arc_maps.swap(other._arc_maps);
528 _attributes.swap(other._attributes);
530 _nodes_caption = other._nodes_caption;
531 _arcs_caption = other._arcs_caption;
532 _attributes_caption = other._attributes_caption;
535 DigraphWriter& operator=(const DigraphWriter&);
539 /// \name Writing rules
542 /// \brief Node map writing rule
544 /// Add a node map writing rule to the writer.
545 template <typename Map>
546 DigraphWriter& nodeMap(const std::string& caption, const Map& map) {
547 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
548 _writer_bits::MapStorageBase<Node>* storage =
549 new _writer_bits::MapStorage<Node, Map>(map);
550 _node_maps.push_back(std::make_pair(caption, storage));
554 /// \brief Node map writing rule
556 /// Add a node map writing rule with specialized converter to the
558 template <typename Map, typename Converter>
559 DigraphWriter& nodeMap(const std::string& caption, const Map& map,
560 const Converter& converter = Converter()) {
561 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
562 _writer_bits::MapStorageBase<Node>* storage =
563 new _writer_bits::MapStorage<Node, Map, Converter>(map, converter);
564 _node_maps.push_back(std::make_pair(caption, storage));
568 /// \brief Arc map writing rule
570 /// Add an arc map writing rule to the writer.
571 template <typename Map>
572 DigraphWriter& arcMap(const std::string& caption, const Map& map) {
573 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
574 _writer_bits::MapStorageBase<Arc>* storage =
575 new _writer_bits::MapStorage<Arc, Map>(map);
576 _arc_maps.push_back(std::make_pair(caption, storage));
580 /// \brief Arc map writing rule
582 /// Add an arc map writing rule with specialized converter to the
584 template <typename Map, typename Converter>
585 DigraphWriter& arcMap(const std::string& caption, const Map& map,
586 const Converter& converter = Converter()) {
587 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
588 _writer_bits::MapStorageBase<Arc>* storage =
589 new _writer_bits::MapStorage<Arc, Map, Converter>(map, converter);
590 _arc_maps.push_back(std::make_pair(caption, storage));
594 /// \brief Attribute writing rule
596 /// Add an attribute writing rule to the writer.
597 template <typename Value>
598 DigraphWriter& attribute(const std::string& caption, const Value& value) {
599 _writer_bits::ValueStorageBase* storage =
600 new _writer_bits::ValueStorage<Value>(value);
601 _attributes.push_back(std::make_pair(caption, storage));
605 /// \brief Attribute writing rule
607 /// Add an attribute writing rule with specialized converter to the
609 template <typename Value, typename Converter>
610 DigraphWriter& attribute(const std::string& caption, const Value& value,
611 const Converter& converter = Converter()) {
612 _writer_bits::ValueStorageBase* storage =
613 new _writer_bits::ValueStorage<Value, Converter>(value, converter);
614 _attributes.push_back(std::make_pair(caption, storage));
618 /// \brief Node writing rule
620 /// Add a node writing rule to the writer.
621 DigraphWriter& node(const std::string& caption, const Node& node) {
622 typedef _writer_bits::MapLookUpConverter<Node> Converter;
623 Converter converter(_node_index);
624 _writer_bits::ValueStorageBase* storage =
625 new _writer_bits::ValueStorage<Node, Converter>(node, converter);
626 _attributes.push_back(std::make_pair(caption, storage));
630 /// \brief Arc writing rule
632 /// Add an arc writing rule to writer.
633 DigraphWriter& arc(const std::string& caption, const Arc& arc) {
634 typedef _writer_bits::MapLookUpConverter<Arc> Converter;
635 Converter converter(_arc_index);
636 _writer_bits::ValueStorageBase* storage =
637 new _writer_bits::ValueStorage<Arc, Converter>(arc, converter);
638 _attributes.push_back(std::make_pair(caption, storage));
642 /// \name Section captions
645 /// \brief Add an additional caption to the \c \@nodes section
647 /// Add an additional caption to the \c \@nodes section.
648 DigraphWriter& nodes(const std::string& caption) {
649 _nodes_caption = caption;
653 /// \brief Add an additional caption to the \c \@arcs section
655 /// Add an additional caption to the \c \@arcs section.
656 DigraphWriter& arcs(const std::string& caption) {
657 _arcs_caption = caption;
661 /// \brief Add an additional caption to the \c \@attributes section
663 /// Add an additional caption to the \c \@attributes section.
664 DigraphWriter& attributes(const std::string& caption) {
665 _attributes_caption = caption;
669 /// \name Skipping section
672 /// \brief Skip writing the node set
674 /// The \c \@nodes section will not be written to the stream.
675 DigraphWriter& skipNodes() {
676 LEMON_ASSERT(!_skip_nodes, "Multiple usage of skipNodes() member");
681 /// \brief Skip writing arc set
683 /// The \c \@arcs section will not be written to the stream.
684 DigraphWriter& skipArcs() {
685 LEMON_ASSERT(!_skip_arcs, "Multiple usage of skipArcs() member");
695 _writer_bits::MapStorageBase<Node>* label = 0;
696 for (typename NodeMaps::iterator it = _node_maps.begin();
697 it != _node_maps.end(); ++it) {
698 if (it->first == "label") {
705 if (!_nodes_caption.empty()) {
706 _writer_bits::writeToken(*_os << ' ', _nodes_caption);
711 *_os << "label" << '\t';
713 for (typename NodeMaps::iterator it = _node_maps.begin();
714 it != _node_maps.end(); ++it) {
715 _writer_bits::writeToken(*_os, it->first) << '\t';
719 std::vector<Node> nodes;
720 for (NodeIt n(_digraph); n != INVALID; ++n) {
725 IdMap<Digraph, Node> id_map(_digraph);
726 _writer_bits::MapLess<IdMap<Digraph, Node> > id_less(id_map);
727 std::sort(nodes.begin(), nodes.end(), id_less);
732 for (int i = 0; i < static_cast<int>(nodes.size()); ++i) {
735 std::ostringstream os;
736 os << _digraph.id(n);
737 _writer_bits::writeToken(*_os, os.str());
739 _node_index.insert(std::make_pair(n, os.str()));
741 for (typename NodeMaps::iterator it = _node_maps.begin();
742 it != _node_maps.end(); ++it) {
743 std::string value = it->second->get(n);
744 _writer_bits::writeToken(*_os, value);
745 if (it->first == "label") {
746 _node_index.insert(std::make_pair(n, value));
754 void createNodeIndex() {
755 _writer_bits::MapStorageBase<Node>* label = 0;
756 for (typename NodeMaps::iterator it = _node_maps.begin();
757 it != _node_maps.end(); ++it) {
758 if (it->first == "label") {
765 for (NodeIt n(_digraph); n != INVALID; ++n) {
766 std::ostringstream os;
767 os << _digraph.id(n);
768 _node_index.insert(std::make_pair(n, os.str()));
771 for (NodeIt n(_digraph); n != INVALID; ++n) {
772 std::string value = label->get(n);
773 _node_index.insert(std::make_pair(n, value));
779 _writer_bits::MapStorageBase<Arc>* label = 0;
780 for (typename ArcMaps::iterator it = _arc_maps.begin();
781 it != _arc_maps.end(); ++it) {
782 if (it->first == "label") {
789 if (!_arcs_caption.empty()) {
790 _writer_bits::writeToken(*_os << ' ', _arcs_caption);
794 *_os << '\t' << '\t';
796 *_os << "label" << '\t';
798 for (typename ArcMaps::iterator it = _arc_maps.begin();
799 it != _arc_maps.end(); ++it) {
800 _writer_bits::writeToken(*_os, it->first) << '\t';
804 std::vector<Arc> arcs;
805 for (ArcIt n(_digraph); n != INVALID; ++n) {
810 IdMap<Digraph, Arc> id_map(_digraph);
811 _writer_bits::MapLess<IdMap<Digraph, Arc> > id_less(id_map);
812 std::sort(arcs.begin(), arcs.end(), id_less);
817 for (int i = 0; i < static_cast<int>(arcs.size()); ++i) {
819 _writer_bits::writeToken(*_os, _node_index.
820 find(_digraph.source(a))->second);
822 _writer_bits::writeToken(*_os, _node_index.
823 find(_digraph.target(a))->second);
826 std::ostringstream os;
827 os << _digraph.id(a);
828 _writer_bits::writeToken(*_os, os.str());
830 _arc_index.insert(std::make_pair(a, os.str()));
832 for (typename ArcMaps::iterator it = _arc_maps.begin();
833 it != _arc_maps.end(); ++it) {
834 std::string value = it->second->get(a);
835 _writer_bits::writeToken(*_os, value);
836 if (it->first == "label") {
837 _arc_index.insert(std::make_pair(a, value));
845 void createArcIndex() {
846 _writer_bits::MapStorageBase<Arc>* label = 0;
847 for (typename ArcMaps::iterator it = _arc_maps.begin();
848 it != _arc_maps.end(); ++it) {
849 if (it->first == "label") {
856 for (ArcIt a(_digraph); a != INVALID; ++a) {
857 std::ostringstream os;
858 os << _digraph.id(a);
859 _arc_index.insert(std::make_pair(a, os.str()));
862 for (ArcIt a(_digraph); a != INVALID; ++a) {
863 std::string value = label->get(a);
864 _arc_index.insert(std::make_pair(a, value));
869 void writeAttributes() {
870 if (_attributes.empty()) return;
871 *_os << "@attributes";
872 if (!_attributes_caption.empty()) {
873 _writer_bits::writeToken(*_os << ' ', _attributes_caption);
876 for (typename Attributes::iterator it = _attributes.begin();
877 it != _attributes.end(); ++it) {
878 _writer_bits::writeToken(*_os, it->first) << ' ';
879 _writer_bits::writeToken(*_os, it->second->get());
886 /// \name Execution of the writer
889 /// \brief Start the batch processing
891 /// This function starts the batch processing.
906 /// \brief Give back the stream of the writer
908 /// Give back the stream of the writer.
909 std::ostream& ostream() {
916 /// \brief Return a \ref DigraphWriter class
918 /// This function just returns a \ref DigraphWriter class.
919 /// \relates DigraphWriter
920 template <typename Digraph>
921 DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
922 std::ostream& os = std::cout) {
923 DigraphWriter<Digraph> tmp(digraph, os);
927 /// \brief Return a \ref DigraphWriter class
929 /// This function just returns a \ref DigraphWriter class.
930 /// \relates DigraphWriter
931 template <typename Digraph>
932 DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
933 const std::string& fn) {
934 DigraphWriter<Digraph> tmp(digraph, fn);
938 /// \brief Return a \ref DigraphWriter class
940 /// This function just returns a \ref DigraphWriter class.
941 /// \relates DigraphWriter
942 template <typename Digraph>
943 DigraphWriter<Digraph> digraphWriter(const Digraph& digraph,
945 DigraphWriter<Digraph> tmp(digraph, fn);
949 template <typename Graph>
952 template <typename Graph>
953 GraphWriter<Graph> graphWriter(const Graph& graph,
954 std::ostream& os = std::cout);
956 template <typename Graph>
957 GraphWriter<Graph> graphWriter(const Graph& graph, const std::string& fn);
959 template <typename Graph>
960 GraphWriter<Graph> graphWriter(const Graph& graph, const char *fn);
962 /// \ingroup lemon_io
964 /// \brief \ref lgf-format "LGF" writer for directed graphs
966 /// This utility writes an \ref lgf-format "LGF" file.
968 /// It can be used almost the same way as \c DigraphWriter.
969 /// The only difference is that this class can handle edges and
970 /// edge maps as well as arcs and arc maps.
972 /// The arc maps are written into the file as two columns, the
973 /// caption of the columns are the name of the map prefixed with \c
974 /// '+' and \c '-'. The arcs are written into the \c \@attributes
975 /// section as a \c '+' or a \c '-' prefix (depends on the direction
976 /// of the arc) and the label of corresponding edge.
977 template <typename _Graph>
981 typedef _Graph Graph;
982 TEMPLATE_GRAPH_TYPEDEFS(Graph);
992 std::string _nodes_caption;
993 std::string _edges_caption;
994 std::string _attributes_caption;
996 typedef std::map<Node, std::string> NodeIndex;
997 NodeIndex _node_index;
998 typedef std::map<Edge, std::string> EdgeIndex;
999 EdgeIndex _edge_index;
1001 typedef std::vector<std::pair<std::string,
1002 _writer_bits::MapStorageBase<Node>* > > NodeMaps;
1003 NodeMaps _node_maps;
1005 typedef std::vector<std::pair<std::string,
1006 _writer_bits::MapStorageBase<Edge>* > >EdgeMaps;
1007 EdgeMaps _edge_maps;
1009 typedef std::vector<std::pair<std::string,
1010 _writer_bits::ValueStorageBase*> > Attributes;
1011 Attributes _attributes;
1018 /// \brief Constructor
1020 /// Construct a directed graph writer, which writes to the given
1022 GraphWriter(const Graph& graph, std::ostream& os = std::cout)
1023 : _os(&os), local_os(false), _graph(graph),
1024 _skip_nodes(false), _skip_edges(false) {}
1026 /// \brief Constructor
1028 /// Construct a directed graph writer, which writes to the given
1030 GraphWriter(const Graph& graph, const std::string& fn)
1031 : _os(new std::ofstream(fn.c_str())), local_os(true), _graph(graph),
1032 _skip_nodes(false), _skip_edges(false) {
1035 throw IoError("Cannot write file", fn);
1039 /// \brief Constructor
1041 /// Construct a directed graph writer, which writes to the given
1043 GraphWriter(const Graph& graph, const char* fn)
1044 : _os(new std::ofstream(fn)), local_os(true), _graph(graph),
1045 _skip_nodes(false), _skip_edges(false) {
1048 throw IoError("Cannot write file", fn);
1052 /// \brief Destructor
1054 for (typename NodeMaps::iterator it = _node_maps.begin();
1055 it != _node_maps.end(); ++it) {
1059 for (typename EdgeMaps::iterator it = _edge_maps.begin();
1060 it != _edge_maps.end(); ++it) {
1064 for (typename Attributes::iterator it = _attributes.begin();
1065 it != _attributes.end(); ++it) {
1076 friend GraphWriter<Graph> graphWriter<>(const Graph& graph,
1078 friend GraphWriter<Graph> graphWriter<>(const Graph& graph,
1079 const std::string& fn);
1080 friend GraphWriter<Graph> graphWriter<>(const Graph& graph,
1083 GraphWriter(GraphWriter& other)
1084 : _os(other._os), local_os(other.local_os), _graph(other._graph),
1085 _skip_nodes(other._skip_nodes), _skip_edges(other._skip_edges) {
1088 other.local_os = false;
1090 _node_index.swap(other._node_index);
1091 _edge_index.swap(other._edge_index);
1093 _node_maps.swap(other._node_maps);
1094 _edge_maps.swap(other._edge_maps);
1095 _attributes.swap(other._attributes);
1097 _nodes_caption = other._nodes_caption;
1098 _edges_caption = other._edges_caption;
1099 _attributes_caption = other._attributes_caption;
1102 GraphWriter& operator=(const GraphWriter&);
1106 /// \name Writing rules
1109 /// \brief Node map writing rule
1111 /// Add a node map writing rule to the writer.
1112 template <typename Map>
1113 GraphWriter& nodeMap(const std::string& caption, const Map& map) {
1114 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
1115 _writer_bits::MapStorageBase<Node>* storage =
1116 new _writer_bits::MapStorage<Node, Map>(map);
1117 _node_maps.push_back(std::make_pair(caption, storage));
1121 /// \brief Node map writing rule
1123 /// Add a node map writing rule with specialized converter to the
1125 template <typename Map, typename Converter>
1126 GraphWriter& nodeMap(const std::string& caption, const Map& map,
1127 const Converter& converter = Converter()) {
1128 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
1129 _writer_bits::MapStorageBase<Node>* storage =
1130 new _writer_bits::MapStorage<Node, Map, Converter>(map, converter);
1131 _node_maps.push_back(std::make_pair(caption, storage));
1135 /// \brief Edge map writing rule
1137 /// Add an edge map writing rule to the writer.
1138 template <typename Map>
1139 GraphWriter& edgeMap(const std::string& caption, const Map& map) {
1140 checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
1141 _writer_bits::MapStorageBase<Edge>* storage =
1142 new _writer_bits::MapStorage<Edge, Map>(map);
1143 _edge_maps.push_back(std::make_pair(caption, storage));
1147 /// \brief Edge map writing rule
1149 /// Add an edge map writing rule with specialized converter to the
1151 template <typename Map, typename Converter>
1152 GraphWriter& edgeMap(const std::string& caption, const Map& map,
1153 const Converter& converter = Converter()) {
1154 checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
1155 _writer_bits::MapStorageBase<Edge>* storage =
1156 new _writer_bits::MapStorage<Edge, Map, Converter>(map, converter);
1157 _edge_maps.push_back(std::make_pair(caption, storage));
1161 /// \brief Arc map writing rule
1163 /// Add an arc map writing rule to the writer.
1164 template <typename Map>
1165 GraphWriter& arcMap(const std::string& caption, const Map& map) {
1166 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
1167 _writer_bits::MapStorageBase<Edge>* forward_storage =
1168 new _writer_bits::GraphArcMapStorage<Graph, true, Map>(_graph, map);
1169 _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
1170 _writer_bits::MapStorageBase<Edge>* backward_storage =
1171 new _writer_bits::GraphArcMapStorage<Graph, false, Map>(_graph, map);
1172 _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
1176 /// \brief Arc map writing rule
1178 /// Add an arc map writing rule with specialized converter to the
1180 template <typename Map, typename Converter>
1181 GraphWriter& arcMap(const std::string& caption, const Map& map,
1182 const Converter& converter = Converter()) {
1183 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
1184 _writer_bits::MapStorageBase<Edge>* forward_storage =
1185 new _writer_bits::GraphArcMapStorage<Graph, true, Map, Converter>
1186 (_graph, map, converter);
1187 _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
1188 _writer_bits::MapStorageBase<Edge>* backward_storage =
1189 new _writer_bits::GraphArcMapStorage<Graph, false, Map, Converter>
1190 (_graph, map, converter);
1191 _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
1195 /// \brief Attribute writing rule
1197 /// Add an attribute writing rule to the writer.
1198 template <typename Value>
1199 GraphWriter& attribute(const std::string& caption, const Value& value) {
1200 _writer_bits::ValueStorageBase* storage =
1201 new _writer_bits::ValueStorage<Value>(value);
1202 _attributes.push_back(std::make_pair(caption, storage));
1206 /// \brief Attribute writing rule
1208 /// Add an attribute writing rule with specialized converter to the
1210 template <typename Value, typename Converter>
1211 GraphWriter& attribute(const std::string& caption, const Value& value,
1212 const Converter& converter = Converter()) {
1213 _writer_bits::ValueStorageBase* storage =
1214 new _writer_bits::ValueStorage<Value, Converter>(value, converter);
1215 _attributes.push_back(std::make_pair(caption, storage));
1219 /// \brief Node writing rule
1221 /// Add a node writing rule to the writer.
1222 GraphWriter& node(const std::string& caption, const Node& node) {
1223 typedef _writer_bits::MapLookUpConverter<Node> Converter;
1224 Converter converter(_node_index);
1225 _writer_bits::ValueStorageBase* storage =
1226 new _writer_bits::ValueStorage<Node, Converter>(node, converter);
1227 _attributes.push_back(std::make_pair(caption, storage));
1231 /// \brief Edge writing rule
1233 /// Add an edge writing rule to writer.
1234 GraphWriter& edge(const std::string& caption, const Edge& edge) {
1235 typedef _writer_bits::MapLookUpConverter<Edge> Converter;
1236 Converter converter(_edge_index);
1237 _writer_bits::ValueStorageBase* storage =
1238 new _writer_bits::ValueStorage<Edge, Converter>(edge, converter);
1239 _attributes.push_back(std::make_pair(caption, storage));
1243 /// \brief Arc writing rule
1245 /// Add an arc writing rule to writer.
1246 GraphWriter& arc(const std::string& caption, const Arc& arc) {
1247 typedef _writer_bits::GraphArcLookUpConverter<Graph> Converter;
1248 Converter converter(_graph, _edge_index);
1249 _writer_bits::ValueStorageBase* storage =
1250 new _writer_bits::ValueStorage<Arc, Converter>(arc, converter);
1251 _attributes.push_back(std::make_pair(caption, storage));
1255 /// \name Section captions
1258 /// \brief Add an additional caption to the \c \@nodes section
1260 /// Add an additional caption to the \c \@nodes section.
1261 GraphWriter& nodes(const std::string& caption) {
1262 _nodes_caption = caption;
1266 /// \brief Add an additional caption to the \c \@arcs section
1268 /// Add an additional caption to the \c \@arcs section.
1269 GraphWriter& edges(const std::string& caption) {
1270 _edges_caption = caption;
1274 /// \brief Add an additional caption to the \c \@attributes section
1276 /// Add an additional caption to the \c \@attributes section.
1277 GraphWriter& attributes(const std::string& caption) {
1278 _attributes_caption = caption;
1282 /// \name Skipping section
1285 /// \brief Skip writing the node set
1287 /// The \c \@nodes section will not be written to the stream.
1288 GraphWriter& skipNodes() {
1289 LEMON_ASSERT(!_skip_nodes, "Multiple usage of skipNodes() member");
1294 /// \brief Skip writing edge set
1296 /// The \c \@edges section will not be written to the stream.
1297 GraphWriter& skipEdges() {
1298 LEMON_ASSERT(!_skip_edges, "Multiple usage of skipEdges() member");
1308 _writer_bits::MapStorageBase<Node>* label = 0;
1309 for (typename NodeMaps::iterator it = _node_maps.begin();
1310 it != _node_maps.end(); ++it) {
1311 if (it->first == "label") {
1318 if (!_nodes_caption.empty()) {
1319 _writer_bits::writeToken(*_os << ' ', _nodes_caption);
1324 *_os << "label" << '\t';
1326 for (typename NodeMaps::iterator it = _node_maps.begin();
1327 it != _node_maps.end(); ++it) {
1328 _writer_bits::writeToken(*_os, it->first) << '\t';
1332 std::vector<Node> nodes;
1333 for (NodeIt n(_graph); n != INVALID; ++n) {
1338 IdMap<Graph, Node> id_map(_graph);
1339 _writer_bits::MapLess<IdMap<Graph, Node> > id_less(id_map);
1340 std::sort(nodes.begin(), nodes.end(), id_less);
1345 for (int i = 0; i < static_cast<int>(nodes.size()); ++i) {
1348 std::ostringstream os;
1350 _writer_bits::writeToken(*_os, os.str());
1352 _node_index.insert(std::make_pair(n, os.str()));
1354 for (typename NodeMaps::iterator it = _node_maps.begin();
1355 it != _node_maps.end(); ++it) {
1356 std::string value = it->second->get(n);
1357 _writer_bits::writeToken(*_os, value);
1358 if (it->first == "label") {
1359 _node_index.insert(std::make_pair(n, value));
1367 void createNodeIndex() {
1368 _writer_bits::MapStorageBase<Node>* label = 0;
1369 for (typename NodeMaps::iterator it = _node_maps.begin();
1370 it != _node_maps.end(); ++it) {
1371 if (it->first == "label") {
1378 for (NodeIt n(_graph); n != INVALID; ++n) {
1379 std::ostringstream os;
1381 _node_index.insert(std::make_pair(n, os.str()));
1384 for (NodeIt n(_graph); n != INVALID; ++n) {
1385 std::string value = label->get(n);
1386 _node_index.insert(std::make_pair(n, value));
1392 _writer_bits::MapStorageBase<Edge>* label = 0;
1393 for (typename EdgeMaps::iterator it = _edge_maps.begin();
1394 it != _edge_maps.end(); ++it) {
1395 if (it->first == "label") {
1402 if (!_edges_caption.empty()) {
1403 _writer_bits::writeToken(*_os << ' ', _edges_caption);
1407 *_os << '\t' << '\t';
1409 *_os << "label" << '\t';
1411 for (typename EdgeMaps::iterator it = _edge_maps.begin();
1412 it != _edge_maps.end(); ++it) {
1413 _writer_bits::writeToken(*_os, it->first) << '\t';
1417 std::vector<Edge> edges;
1418 for (EdgeIt n(_graph); n != INVALID; ++n) {
1423 IdMap<Graph, Edge> id_map(_graph);
1424 _writer_bits::MapLess<IdMap<Graph, Edge> > id_less(id_map);
1425 std::sort(edges.begin(), edges.end(), id_less);
1430 for (int i = 0; i < static_cast<int>(edges.size()); ++i) {
1432 _writer_bits::writeToken(*_os, _node_index.
1433 find(_graph.u(e))->second);
1435 _writer_bits::writeToken(*_os, _node_index.
1436 find(_graph.v(e))->second);
1439 std::ostringstream os;
1441 _writer_bits::writeToken(*_os, os.str());
1443 _edge_index.insert(std::make_pair(e, os.str()));
1445 for (typename EdgeMaps::iterator it = _edge_maps.begin();
1446 it != _edge_maps.end(); ++it) {
1447 std::string value = it->second->get(e);
1448 _writer_bits::writeToken(*_os, value);
1449 if (it->first == "label") {
1450 _edge_index.insert(std::make_pair(e, value));
1458 void createEdgeIndex() {
1459 _writer_bits::MapStorageBase<Edge>* label = 0;
1460 for (typename EdgeMaps::iterator it = _edge_maps.begin();
1461 it != _edge_maps.end(); ++it) {
1462 if (it->first == "label") {
1469 for (EdgeIt e(_graph); e != INVALID; ++e) {
1470 std::ostringstream os;
1472 _edge_index.insert(std::make_pair(e, os.str()));
1475 for (EdgeIt e(_graph); e != INVALID; ++e) {
1476 std::string value = label->get(e);
1477 _edge_index.insert(std::make_pair(e, value));
1482 void writeAttributes() {
1483 if (_attributes.empty()) return;
1484 *_os << "@attributes";
1485 if (!_attributes_caption.empty()) {
1486 _writer_bits::writeToken(*_os << ' ', _attributes_caption);
1489 for (typename Attributes::iterator it = _attributes.begin();
1490 it != _attributes.end(); ++it) {
1491 _writer_bits::writeToken(*_os, it->first) << ' ';
1492 _writer_bits::writeToken(*_os, it->second->get());
1499 /// \name Execution of the writer
1502 /// \brief Start the batch processing
1504 /// This function starts the batch processing.
1519 /// \brief Give back the stream of the writer
1521 /// Give back the stream of the writer
1522 std::ostream& ostream() {
1529 /// \brief Return a \ref GraphWriter class
1531 /// This function just returns a \ref GraphWriter class.
1532 /// \relates GraphWriter
1533 template <typename Graph>
1534 GraphWriter<Graph> graphWriter(const Graph& graph,
1535 std::ostream& os = std::cout) {
1536 GraphWriter<Graph> tmp(graph, os);
1540 /// \brief Return a \ref GraphWriter class
1542 /// This function just returns a \ref GraphWriter class.
1543 /// \relates GraphWriter
1544 template <typename Graph>
1545 GraphWriter<Graph> graphWriter(const Graph& graph, const std::string& fn) {
1546 GraphWriter<Graph> tmp(graph, fn);
1550 /// \brief Return a \ref GraphWriter class
1552 /// This function just returns a \ref GraphWriter class.
1553 /// \relates GraphWriter
1554 template <typename Graph>
1555 GraphWriter<Graph> graphWriter(const Graph& graph, const char* fn) {
1556 GraphWriter<Graph> tmp(graph, fn);
1560 class SectionWriter;
1562 SectionWriter sectionWriter(std::istream& is);
1563 SectionWriter sectionWriter(const std::string& fn);
1564 SectionWriter sectionWriter(const char* fn);
1566 /// \ingroup lemon_io
1568 /// \brief Section writer class
1570 /// In the \ref lgf-format "LGF" file extra sections can be placed,
1571 /// which contain any data in arbitrary format. Such sections can be
1572 /// written with this class. A writing rule can be added to the
1573 /// class with two different functions. With the \c sectionLines()
1574 /// function a generator can write the section line-by-line, while
1575 /// with the \c sectionStream() member the section can be written to
1576 /// an output stream.
1577 class SectionWriter {
1583 typedef std::vector<std::pair<std::string, _writer_bits::Section*> >
1590 /// \brief Constructor
1592 /// Construct a section writer, which writes to the given output
1594 SectionWriter(std::ostream& os)
1595 : _os(&os), local_os(false) {}
1597 /// \brief Constructor
1599 /// Construct a section writer, which writes into the given file.
1600 SectionWriter(const std::string& fn)
1601 : _os(new std::ofstream(fn.c_str())), local_os(true) {
1604 throw IoError("Cannot write file", fn);
1608 /// \brief Constructor
1610 /// Construct a section writer, which writes into the given file.
1611 SectionWriter(const char* fn)
1612 : _os(new std::ofstream(fn)), local_os(true) {
1615 throw IoError("Cannot write file", fn);
1619 /// \brief Destructor
1621 for (Sections::iterator it = _sections.begin();
1622 it != _sections.end(); ++it) {
1634 friend SectionWriter sectionWriter(std::ostream& os);
1635 friend SectionWriter sectionWriter(const std::string& fn);
1636 friend SectionWriter sectionWriter(const char* fn);
1638 SectionWriter(SectionWriter& other)
1639 : _os(other._os), local_os(other.local_os) {
1642 other.local_os = false;
1644 _sections.swap(other._sections);
1647 SectionWriter& operator=(const SectionWriter&);
1651 /// \name Section writers
1654 /// \brief Add a section writer with line oriented writing
1656 /// The first parameter is the type descriptor of the section, the
1657 /// second is a generator with std::string values. At the writing
1658 /// process, the returned \c std::string will be written into the
1659 /// output file until it is an empty string.
1661 /// For example, an integer vector is written into a section.
1669 /// The generator is implemented as a struct.
1671 /// struct NumberSection {
1672 /// std::vector<int>::const_iterator _it, _end;
1673 /// NumberSection(const std::vector<int>& data)
1674 /// : _it(data.begin()), _end(data.end()) {}
1675 /// std::string operator()() {
1676 /// int rem_in_line = 4;
1677 /// std::ostringstream ls;
1678 /// while (rem_in_line > 0 && _it != _end) {
1679 /// ls << *(_it++) << ' ';
1682 /// return ls.str();
1688 /// writer.sectionLines("numbers", NumberSection(vec));
1690 template <typename Functor>
1691 SectionWriter& sectionLines(const std::string& type, Functor functor) {
1692 LEMON_ASSERT(!type.empty(), "Type is empty.");
1693 _sections.push_back(std::make_pair(type,
1694 new _writer_bits::LineSection<Functor>(functor)));
1699 /// \brief Add a section writer with stream oriented writing
1701 /// The first parameter is the type of the section, the second is
1702 /// a functor, which takes a \c std::ostream& parameter. The
1703 /// functor writes the section to the output stream.
1704 /// \warning The last line must be closed with end-line character.
1705 template <typename Functor>
1706 SectionWriter& sectionStream(const std::string& type, Functor functor) {
1707 LEMON_ASSERT(!type.empty(), "Type is empty.");
1708 _sections.push_back(std::make_pair(type,
1709 new _writer_bits::StreamSection<Functor>(functor)));
1718 /// \name Execution of the writer
1721 /// \brief Start the batch processing
1723 /// This function starts the batch processing.
1726 LEMON_ASSERT(_os != 0, "This writer is assigned to an other writer");
1728 for (Sections::iterator it = _sections.begin();
1729 it != _sections.end(); ++it) {
1730 (*_os) << '@' << it->first << std::endl;
1731 it->second->process(*_os);
1735 /// \brief Give back the stream of the writer
1737 /// Returns the stream of the writer
1738 std::ostream& ostream() {
1746 /// \brief Return a \ref SectionWriter class
1748 /// This function just returns a \ref SectionWriter class.
1749 /// \relates SectionWriter
1750 inline SectionWriter sectionWriter(std::ostream& os) {
1751 SectionWriter tmp(os);
1755 /// \brief Return a \ref SectionWriter class
1757 /// This function just returns a \ref SectionWriter class.
1758 /// \relates SectionWriter
1759 inline SectionWriter sectionWriter(const std::string& fn) {
1760 SectionWriter tmp(fn);
1764 /// \brief Return a \ref SectionWriter class
1766 /// This function just returns a \ref SectionWriter class.
1767 /// \relates SectionWriter
1768 inline SectionWriter sectionWriter(const char* fn) {
1769 SectionWriter tmp(fn);