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 Lemon Graph Format reader.
24 #ifndef LEMON_LGF_READER_H
25 #define LEMON_LGF_READER_H
34 #include <lemon/assert.h>
35 #include <lemon/graph_utils.h>
37 #include <lemon/lgf_writer.h>
39 #include <lemon/concept_check.h>
40 #include <lemon/concepts/maps.h>
44 namespace _reader_bits {
46 template <typename Value>
47 struct DefaultConverter {
48 Value operator()(const std::string& str) {
49 std::istringstream is(str);
54 if (is >> std::ws >> c) {
55 throw DataFormatError("Remaining characters in token");
62 struct DefaultConverter<std::string> {
63 std::string operator()(const std::string& str) {
68 template <typename _Item>
69 class MapStorageBase {
75 virtual ~MapStorageBase() {}
77 virtual void set(const Item& item, const std::string& value) = 0;
81 template <typename _Item, typename _Map,
82 typename _Converter = DefaultConverter<typename _Map::Value> >
83 class MapStorage : public MapStorageBase<_Item> {
86 typedef _Converter Converter;
94 MapStorage(Map& map, const Converter& converter = Converter())
95 : _map(map), _converter(converter) {}
96 virtual ~MapStorage() {}
98 virtual void set(const Item& item ,const std::string& value) {
99 _map.set(item, _converter(value));
103 template <typename _Graph, bool _dir, typename _Map,
104 typename _Converter = DefaultConverter<typename _Map::Value> >
105 class GraphArcMapStorage : public MapStorageBase<typename _Graph::Edge> {
108 typedef _Converter Converter;
109 typedef _Graph Graph;
110 typedef typename Graph::Edge Item;
111 static const bool dir = _dir;
116 Converter _converter;
119 GraphArcMapStorage(const Graph& graph, Map& map,
120 const Converter& converter = Converter())
121 : _graph(graph), _map(map), _converter(converter) {}
122 virtual ~GraphArcMapStorage() {}
124 virtual void set(const Item& item ,const std::string& value) {
125 _map.set(_graph.direct(item, dir), _converter(value));
129 class ValueStorageBase {
131 ValueStorageBase() {}
132 virtual ~ValueStorageBase() {}
134 virtual void set(const std::string&) = 0;
137 template <typename _Value, typename _Converter = DefaultConverter<_Value> >
138 class ValueStorage : public ValueStorageBase {
140 typedef _Value Value;
141 typedef _Converter Converter;
145 Converter _converter;
148 ValueStorage(Value& value, const Converter& converter = Converter())
149 : _value(value), _converter(converter) {}
151 virtual void set(const std::string& value) {
152 _value = _converter(value);
156 template <typename Value>
157 struct MapLookUpConverter {
158 const std::map<std::string, Value>& _map;
160 MapLookUpConverter(const std::map<std::string, Value>& map)
163 Value operator()(const std::string& str) {
164 typename std::map<std::string, Value>::const_iterator it =
166 if (it == _map.end()) {
167 std::ostringstream msg;
168 msg << "Item not found: " << str;
169 throw DataFormatError(msg.str().c_str());
175 template <typename Graph>
176 struct GraphArcLookUpConverter {
178 const std::map<std::string, typename Graph::Edge>& _map;
180 GraphArcLookUpConverter(const Graph& graph,
181 const std::map<std::string,
182 typename Graph::Edge>& map)
183 : _graph(graph), _map(map) {}
185 typename Graph::Arc operator()(const std::string& str) {
186 if (str.empty() || (str[0] != '+' && str[0] != '-')) {
187 throw DataFormatError("Item must start with '+' or '-'");
189 typename std::map<std::string, typename Graph::Edge>
190 ::const_iterator it = _map.find(str.substr(1));
191 if (it == _map.end()) {
192 throw DataFormatError("Item not found");
194 return _graph.direct(it->second, str[0] == '+');
198 bool isWhiteSpace(char c) {
199 return c == ' ' || c == '\t' || c == '\v' ||
200 c == '\n' || c == '\r' || c == '\f';
204 return '0' <= c && c <='7';
207 int valueOct(char c) {
208 LEMON_ASSERT(isOct(c), "The character is not octal.");
213 return ('0' <= c && c <= '9') ||
214 ('a' <= c && c <= 'z') ||
215 ('A' <= c && c <= 'Z');
218 int valueHex(char c) {
219 LEMON_ASSERT(isHex(c), "The character is not hexadecimal.");
220 if ('0' <= c && c <= '9') return c - '0';
221 if ('a' <= c && c <= 'z') return c - 'a' + 10;
225 bool isIdentifierFirstChar(char c) {
226 return ('a' <= c && c <= 'z') ||
227 ('A' <= c && c <= 'Z') || c == '_';
230 bool isIdentifierChar(char c) {
231 return isIdentifierFirstChar(c) ||
232 ('0' <= c && c <= '9');
235 char readEscape(std::istream& is) {
238 throw DataFormatError("Escape format error");
266 if (!is.get(c) || !isHex(c))
267 throw DataFormatError("Escape format error");
268 else if (code = valueHex(c), !is.get(c) || !isHex(c)) is.putback(c);
269 else code = code * 16 + valueHex(c);
276 throw DataFormatError("Escape format error");
277 else if (code = valueOct(c), !is.get(c) || !isOct(c))
279 else if (code = code * 8 + valueOct(c), !is.get(c) || !isOct(c))
281 else code = code * 8 + valueOct(c);
287 std::istream& readToken(std::istream& is, std::string& str) {
288 std::ostringstream os;
297 while (is.get(c) && c != '\"') {
303 throw DataFormatError("Quoted format error");
306 while (is.get(c) && !isWhiteSpace(c)) {
323 virtual ~Section() {}
324 virtual void process(std::istream& is, int& line_num) = 0;
327 template <typename Functor>
328 class LineSection : public Section {
335 LineSection(const Functor& functor) : _functor(functor) {}
336 virtual ~LineSection() {}
338 virtual void process(std::istream& is, int& line_num) {
341 while (is.get(c) && c != '@') {
344 } else if (c == '#') {
347 } else if (!isWhiteSpace(c)) {
354 if (is) is.putback(c);
355 else if (is.eof()) is.clear();
359 template <typename Functor>
360 class StreamSection : public Section {
367 StreamSection(const Functor& functor) : _functor(functor) {}
368 virtual ~StreamSection() {}
370 virtual void process(std::istream& is, int& line_num) {
371 _functor(is, line_num);
374 while (is.get(c) && c != '@') {
377 } else if (!isWhiteSpace(c)) {
382 if (is) is.putback(c);
383 else if (is.eof()) is.clear();
389 template <typename Digraph>
392 template <typename Digraph>
393 DigraphReader<Digraph> digraphReader(std::istream& is, Digraph& digraph);
395 template <typename Digraph>
396 DigraphReader<Digraph> digraphReader(const std::string& fn, Digraph& digraph);
398 template <typename Digraph>
399 DigraphReader<Digraph> digraphReader(const char *fn, Digraph& digraph);
401 /// \ingroup lemon_io
403 /// \brief LGF reader for directed graphs
405 /// This utility reads an \ref lgf-format "LGF" file.
407 /// The reading method does a batch processing. The user creates a
408 /// reader object, then various reading rules can be added to the
409 /// reader, and eventually the reading is executed with the \c run()
410 /// member function. A map reading rule can be added to the reader
411 /// with the \c nodeMap() or \c arcMap() members. An optional
412 /// converter parameter can also be added as a standard functor
413 /// converting from std::string to the value type of the map. If it
414 /// is set, it will determine how the tokens in the file should be
415 /// is converted to the map's value type. If the functor is not set,
416 /// then a default conversion will be used. One map can be read into
417 /// multiple map objects at the same time. The \c attribute(), \c
418 /// node() and \c arc() functions are used to add attribute reading
422 /// DigraphReader<Digraph>(std::cin, digraph).
423 /// nodeMap("coordinates", coord_map).
424 /// arcMap("capacity", cap_map).
425 /// node("source", src).
426 /// node("target", trg).
427 /// attribute("caption", caption).
431 /// By default the reader uses the first section in the file of the
432 /// proper type. If a section has an optional name, then it can be
433 /// selected for reading by giving an optional name parameter to the
434 /// \c nodes(), \c arcs() or \c attributes() functions.
436 /// The \c useNodes() and \c useArcs() functions are used to tell the reader
437 /// that the nodes or arcs should not be constructed (added to the
438 /// graph) during the reading, but instead the label map of the items
439 /// are given as a parameter of these functions. An
440 /// application of these function is multipass reading, which is
441 /// important if two \e \@arcs sections must be read from the
442 /// file. In this example the first phase would read the node set and one
443 /// of the arc sets, while the second phase would read the second arc
444 /// set into an \e ArcSet class (\c SmartArcSet or \c ListArcSet).
445 /// The previously read label node map should be passed to the \c
446 /// useNodes() functions. Another application of multipass reading when
447 /// paths are given as a node map or an arc map. It is impossible read this in
448 /// a single pass, because the arcs are not constructed when the node
450 template <typename _Digraph>
451 class DigraphReader {
454 typedef _Digraph Digraph;
455 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
465 std::string _nodes_caption;
466 std::string _arcs_caption;
467 std::string _attributes_caption;
469 typedef std::map<std::string, Node> NodeIndex;
470 NodeIndex _node_index;
471 typedef std::map<std::string, Arc> ArcIndex;
474 typedef std::vector<std::pair<std::string,
475 _reader_bits::MapStorageBase<Node>*> > NodeMaps;
478 typedef std::vector<std::pair<std::string,
479 _reader_bits::MapStorageBase<Arc>*> >ArcMaps;
482 typedef std::multimap<std::string, _reader_bits::ValueStorageBase*>
484 Attributes _attributes;
493 std::istringstream line;
497 /// \brief Constructor
499 /// Construct a directed graph reader, which reads from the given
501 DigraphReader(std::istream& is, Digraph& digraph)
502 : _is(&is), local_is(false), _digraph(digraph),
503 _use_nodes(false), _use_arcs(false),
504 _skip_nodes(false), _skip_arcs(false) {}
506 /// \brief Constructor
508 /// Construct a directed graph reader, which reads from the given
510 DigraphReader(const std::string& fn, Digraph& digraph)
511 : _is(new std::ifstream(fn.c_str())), local_is(true), _digraph(digraph),
512 _use_nodes(false), _use_arcs(false),
513 _skip_nodes(false), _skip_arcs(false) {}
515 /// \brief Constructor
517 /// Construct a directed graph reader, which reads from the given
519 DigraphReader(const char* fn, Digraph& digraph)
520 : _is(new std::ifstream(fn)), local_is(true), _digraph(digraph),
521 _use_nodes(false), _use_arcs(false),
522 _skip_nodes(false), _skip_arcs(false) {}
524 /// \brief Destructor
526 for (typename NodeMaps::iterator it = _node_maps.begin();
527 it != _node_maps.end(); ++it) {
531 for (typename ArcMaps::iterator it = _arc_maps.begin();
532 it != _arc_maps.end(); ++it) {
536 for (typename Attributes::iterator it = _attributes.begin();
537 it != _attributes.end(); ++it) {
549 friend DigraphReader<Digraph> digraphReader<>(std::istream& is,
551 friend DigraphReader<Digraph> digraphReader<>(const std::string& fn,
553 friend DigraphReader<Digraph> digraphReader<>(const char *fn,
556 DigraphReader(DigraphReader& other)
557 : _is(other._is), local_is(other.local_is), _digraph(other._digraph),
558 _use_nodes(other._use_nodes), _use_arcs(other._use_arcs),
559 _skip_nodes(other._skip_nodes), _skip_arcs(other._skip_arcs) {
562 other.local_is = false;
564 _node_index.swap(other._node_index);
565 _arc_index.swap(other._arc_index);
567 _node_maps.swap(other._node_maps);
568 _arc_maps.swap(other._arc_maps);
569 _attributes.swap(other._attributes);
571 _nodes_caption = other._nodes_caption;
572 _arcs_caption = other._arcs_caption;
573 _attributes_caption = other._attributes_caption;
577 DigraphReader& operator=(const DigraphReader&);
581 /// \name Reading rules
584 /// \brief Node map reading rule
586 /// Add a node map reading rule to the reader.
587 template <typename Map>
588 DigraphReader& nodeMap(const std::string& caption, Map& map) {
589 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
590 _reader_bits::MapStorageBase<Node>* storage =
591 new _reader_bits::MapStorage<Node, Map>(map);
592 _node_maps.push_back(std::make_pair(caption, storage));
596 /// \brief Node map reading rule
598 /// Add a node map reading rule with specialized converter to the
600 template <typename Map, typename Converter>
601 DigraphReader& nodeMap(const std::string& caption, Map& map,
602 const Converter& converter = Converter()) {
603 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
604 _reader_bits::MapStorageBase<Node>* storage =
605 new _reader_bits::MapStorage<Node, Map, Converter>(map, converter);
606 _node_maps.push_back(std::make_pair(caption, storage));
610 /// \brief Arc map reading rule
612 /// Add an arc map reading rule to the reader.
613 template <typename Map>
614 DigraphReader& arcMap(const std::string& caption, Map& map) {
615 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
616 _reader_bits::MapStorageBase<Arc>* storage =
617 new _reader_bits::MapStorage<Arc, Map>(map);
618 _arc_maps.push_back(std::make_pair(caption, storage));
622 /// \brief Arc map reading rule
624 /// Add an arc map reading rule with specialized converter to the
626 template <typename Map, typename Converter>
627 DigraphReader& arcMap(const std::string& caption, Map& map,
628 const Converter& converter = Converter()) {
629 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
630 _reader_bits::MapStorageBase<Arc>* storage =
631 new _reader_bits::MapStorage<Arc, Map, Converter>(map, converter);
632 _arc_maps.push_back(std::make_pair(caption, storage));
636 /// \brief Attribute reading rule
638 /// Add an attribute reading rule to the reader.
639 template <typename Value>
640 DigraphReader& attribute(const std::string& caption, Value& value) {
641 _reader_bits::ValueStorageBase* storage =
642 new _reader_bits::ValueStorage<Value>(value);
643 _attributes.insert(std::make_pair(caption, storage));
647 /// \brief Attribute reading rule
649 /// Add an attribute reading rule with specialized converter to the
651 template <typename Value, typename Converter>
652 DigraphReader& attribute(const std::string& caption, Value& value,
653 const Converter& converter = Converter()) {
654 _reader_bits::ValueStorageBase* storage =
655 new _reader_bits::ValueStorage<Value, Converter>(value, converter);
656 _attributes.insert(std::make_pair(caption, storage));
660 /// \brief Node reading rule
662 /// Add a node reading rule to reader.
663 DigraphReader& node(const std::string& caption, Node& node) {
664 typedef _reader_bits::MapLookUpConverter<Node> Converter;
665 Converter converter(_node_index);
666 _reader_bits::ValueStorageBase* storage =
667 new _reader_bits::ValueStorage<Node, Converter>(node, converter);
668 _attributes.insert(std::make_pair(caption, storage));
672 /// \brief Arc reading rule
674 /// Add an arc reading rule to reader.
675 DigraphReader& arc(const std::string& caption, Arc& arc) {
676 typedef _reader_bits::MapLookUpConverter<Arc> Converter;
677 Converter converter(_arc_index);
678 _reader_bits::ValueStorageBase* storage =
679 new _reader_bits::ValueStorage<Arc, Converter>(arc, converter);
680 _attributes.insert(std::make_pair(caption, storage));
686 /// \name Select section by name
689 /// \brief Set \c \@nodes section to be read
691 /// Set \c \@nodes section to be read
692 DigraphReader& nodes(const std::string& caption) {
693 _nodes_caption = caption;
697 /// \brief Set \c \@arcs section to be read
699 /// Set \c \@arcs section to be read
700 DigraphReader& arcs(const std::string& caption) {
701 _arcs_caption = caption;
705 /// \brief Set \c \@attributes section to be read
707 /// Set \c \@attributes section to be read
708 DigraphReader& attributes(const std::string& caption) {
709 _attributes_caption = caption;
715 /// \name Using previously constructed node or arc set
718 /// \brief Use previously constructed node set
720 /// Use previously constructed node set, and specify the node
722 template <typename Map>
723 DigraphReader& useNodes(const Map& map) {
724 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
725 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
727 _writer_bits::DefaultConverter<typename Map::Value> converter;
728 for (NodeIt n(_digraph); n != INVALID; ++n) {
729 _node_index.insert(std::make_pair(converter(map[n]), n));
734 /// \brief Use previously constructed node set
736 /// Use previously constructed node set, and specify the node
737 /// label map and a functor which converts the label map values to
739 template <typename Map, typename Converter>
740 DigraphReader& useNodes(const Map& map,
741 const Converter& converter = Converter()) {
742 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
743 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
745 for (NodeIt n(_digraph); n != INVALID; ++n) {
746 _node_index.insert(std::make_pair(converter(map[n]), n));
751 /// \brief Use previously constructed arc set
753 /// Use previously constructed arc set, and specify the arc
755 template <typename Map>
756 DigraphReader& useArcs(const Map& map) {
757 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
758 LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member");
760 _writer_bits::DefaultConverter<typename Map::Value> converter;
761 for (ArcIt a(_digraph); a != INVALID; ++a) {
762 _arc_index.insert(std::make_pair(converter(map[a]), a));
767 /// \brief Use previously constructed arc set
769 /// Use previously constructed arc set, and specify the arc
770 /// label map and a functor which converts the label map values to
772 template <typename Map, typename Converter>
773 DigraphReader& useArcs(const Map& map,
774 const Converter& converter = Converter()) {
775 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
776 LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member");
778 for (ArcIt a(_digraph); a != INVALID; ++a) {
779 _arc_index.insert(std::make_pair(converter(map[a]), a));
784 /// \brief Skips the reading of node section
786 /// Omit the reading of the node section. This implies that each node
787 /// map reading rule will be abanoned, and the nodes of the graph
788 /// will not be constructed, which usually cause that the arc set
789 /// could not be read due to lack of node name
790 /// resolving. Therefore, the \c skipArcs() should be used too, or
791 /// the useNodes() member function should be used to specify the
792 /// label of the nodes.
793 DigraphReader& skipNodes() {
794 LEMON_ASSERT(!_skip_nodes, "Skip nodes already set");
799 /// \brief Skips the reading of arc section
801 /// Omit the reading of the arc section. This implies that each arc
802 /// map reading rule will be abanoned, and the arcs of the graph
803 /// will not be constructed.
804 DigraphReader& skipArcs() {
805 LEMON_ASSERT(!_skip_arcs, "Skip arcs already set");
816 while(++line_num, std::getline(*_is, str)) {
817 line.clear(); line.str(str);
819 if (line >> std::ws >> c && c != '#') {
828 return static_cast<bool>(*_is);
833 while (readSuccess() && line >> c && c != '@') {
841 std::vector<int> map_index(_node_maps.size());
842 int map_num, label_index;
845 if (!readLine() || !(line >> c) || c == '@') {
846 if (readSuccess() && line) line.putback(c);
847 if (!_node_maps.empty())
848 throw DataFormatError("Cannot find map names");
854 std::map<std::string, int> maps;
858 while (_reader_bits::readToken(line, map)) {
859 if (maps.find(map) != maps.end()) {
860 std::ostringstream msg;
861 msg << "Multiple occurence of node map: " << map;
862 throw DataFormatError(msg.str().c_str());
864 maps.insert(std::make_pair(map, index));
868 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
869 std::map<std::string, int>::iterator jt =
870 maps.find(_node_maps[i].first);
871 if (jt == maps.end()) {
872 std::ostringstream msg;
873 msg << "Map not found in file: " << _node_maps[i].first;
874 throw DataFormatError(msg.str().c_str());
876 map_index[i] = jt->second;
880 std::map<std::string, int>::iterator jt = maps.find("label");
881 if (jt != maps.end()) {
882 label_index = jt->second;
887 map_num = maps.size();
890 while (readLine() && line >> c && c != '@') {
893 std::vector<std::string> tokens(map_num);
894 for (int i = 0; i < map_num; ++i) {
895 if (!_reader_bits::readToken(line, tokens[i])) {
896 std::ostringstream msg;
897 msg << "Column not found (" << i + 1 << ")";
898 throw DataFormatError(msg.str().c_str());
901 if (line >> std::ws >> c)
902 throw DataFormatError("Extra character on the end of line");
906 n = _digraph.addNode();
907 if (label_index != -1)
908 _node_index.insert(std::make_pair(tokens[label_index], n));
910 if (label_index == -1)
911 throw DataFormatError("Label map not found in file");
912 typename std::map<std::string, Node>::iterator it =
913 _node_index.find(tokens[label_index]);
914 if (it == _node_index.end()) {
915 std::ostringstream msg;
916 msg << "Node with label not found: " << tokens[label_index];
917 throw DataFormatError(msg.str().c_str());
922 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
923 _node_maps[i].second->set(n, tokens[map_index[i]]);
934 std::vector<int> map_index(_arc_maps.size());
935 int map_num, label_index;
938 if (!readLine() || !(line >> c) || c == '@') {
939 if (readSuccess() && line) line.putback(c);
940 if (!_arc_maps.empty())
941 throw DataFormatError("Cannot find map names");
947 std::map<std::string, int> maps;
951 while (_reader_bits::readToken(line, map)) {
952 if (maps.find(map) != maps.end()) {
953 std::ostringstream msg;
954 msg << "Multiple occurence of arc map: " << map;
955 throw DataFormatError(msg.str().c_str());
957 maps.insert(std::make_pair(map, index));
961 for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) {
962 std::map<std::string, int>::iterator jt =
963 maps.find(_arc_maps[i].first);
964 if (jt == maps.end()) {
965 std::ostringstream msg;
966 msg << "Map not found in file: " << _arc_maps[i].first;
967 throw DataFormatError(msg.str().c_str());
969 map_index[i] = jt->second;
973 std::map<std::string, int>::iterator jt = maps.find("label");
974 if (jt != maps.end()) {
975 label_index = jt->second;
980 map_num = maps.size();
983 while (readLine() && line >> c && c != '@') {
986 std::string source_token;
987 std::string target_token;
989 if (!_reader_bits::readToken(line, source_token))
990 throw DataFormatError("Source not found");
992 if (!_reader_bits::readToken(line, target_token))
993 throw DataFormatError("Target not found");
995 std::vector<std::string> tokens(map_num);
996 for (int i = 0; i < map_num; ++i) {
997 if (!_reader_bits::readToken(line, tokens[i])) {
998 std::ostringstream msg;
999 msg << "Column not found (" << i + 1 << ")";
1000 throw DataFormatError(msg.str().c_str());
1003 if (line >> std::ws >> c)
1004 throw DataFormatError("Extra character on the end of line");
1009 typename NodeIndex::iterator it;
1011 it = _node_index.find(source_token);
1012 if (it == _node_index.end()) {
1013 std::ostringstream msg;
1014 msg << "Item not found: " << source_token;
1015 throw DataFormatError(msg.str().c_str());
1017 Node source = it->second;
1019 it = _node_index.find(target_token);
1020 if (it == _node_index.end()) {
1021 std::ostringstream msg;
1022 msg << "Item not found: " << target_token;
1023 throw DataFormatError(msg.str().c_str());
1025 Node target = it->second;
1027 a = _digraph.addArc(source, target);
1028 if (label_index != -1)
1029 _arc_index.insert(std::make_pair(tokens[label_index], a));
1031 if (label_index == -1)
1032 throw DataFormatError("Label map not found in file");
1033 typename std::map<std::string, Arc>::iterator it =
1034 _arc_index.find(tokens[label_index]);
1035 if (it == _arc_index.end()) {
1036 std::ostringstream msg;
1037 msg << "Arc with label not found: " << tokens[label_index];
1038 throw DataFormatError(msg.str().c_str());
1043 for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) {
1044 _arc_maps[i].second->set(a, tokens[map_index[i]]);
1048 if (readSuccess()) {
1053 void readAttributes() {
1055 std::set<std::string> read_attr;
1058 while (readLine() && line >> c && c != '@') {
1061 std::string attr, token;
1062 if (!_reader_bits::readToken(line, attr))
1063 throw DataFormatError("Attribute name not found");
1064 if (!_reader_bits::readToken(line, token))
1065 throw DataFormatError("Attribute value not found");
1067 throw DataFormatError("Extra character on the end of line");
1070 std::set<std::string>::iterator it = read_attr.find(attr);
1071 if (it != read_attr.end()) {
1072 std::ostringstream msg;
1073 msg << "Multiple occurence of attribute " << attr;
1074 throw DataFormatError(msg.str().c_str());
1076 read_attr.insert(attr);
1080 typename Attributes::iterator it = _attributes.lower_bound(attr);
1081 while (it != _attributes.end() && it->first == attr) {
1082 it->second->set(token);
1088 if (readSuccess()) {
1091 for (typename Attributes::iterator it = _attributes.begin();
1092 it != _attributes.end(); ++it) {
1093 if (read_attr.find(it->first) == read_attr.end()) {
1094 std::ostringstream msg;
1095 msg << "Attribute not found in file: " << it->first;
1096 throw DataFormatError(msg.str().c_str());
1103 /// \name Execution of the reader
1106 /// \brief Start the batch processing
1108 /// This function starts the batch processing
1110 LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
1112 throw DataFormatError("Cannot find file");
1115 bool nodes_done = _skip_nodes;
1116 bool arcs_done = _skip_arcs;
1117 bool attributes_done = false;
1123 while (readSuccess()) {
1126 std::string section, caption;
1128 _reader_bits::readToken(line, section);
1129 _reader_bits::readToken(line, caption);
1132 throw DataFormatError("Extra character on the end of line");
1134 if (section == "nodes" && !nodes_done) {
1135 if (_nodes_caption.empty() || _nodes_caption == caption) {
1139 } else if ((section == "arcs" || section == "edges") &&
1141 if (_arcs_caption.empty() || _arcs_caption == caption) {
1145 } else if (section == "attributes" && !attributes_done) {
1146 if (_attributes_caption.empty() || _attributes_caption == caption) {
1148 attributes_done = true;
1154 } catch (DataFormatError& error) {
1155 error.line(line_num);
1161 throw DataFormatError("Section @nodes not found");
1165 throw DataFormatError("Section @arcs not found");
1168 if (!attributes_done && !_attributes.empty()) {
1169 throw DataFormatError("Section @attributes not found");
1178 /// \relates DigraphReader
1179 template <typename Digraph>
1180 DigraphReader<Digraph> digraphReader(std::istream& is, Digraph& digraph) {
1181 DigraphReader<Digraph> tmp(is, digraph);
1185 /// \relates DigraphReader
1186 template <typename Digraph>
1187 DigraphReader<Digraph> digraphReader(const std::string& fn,
1189 DigraphReader<Digraph> tmp(fn, digraph);
1193 /// \relates DigraphReader
1194 template <typename Digraph>
1195 DigraphReader<Digraph> digraphReader(const char* fn, Digraph& digraph) {
1196 DigraphReader<Digraph> tmp(fn, digraph);
1200 template <typename Graph>
1203 template <typename Graph>
1204 GraphReader<Graph> graphReader(std::istream& is, Graph& graph);
1206 template <typename Graph>
1207 GraphReader<Graph> graphReader(const std::string& fn, Graph& graph);
1209 template <typename Graph>
1210 GraphReader<Graph> graphReader(const char *fn, Graph& graph);
1212 /// \ingroup lemon_io
1214 /// \brief LGF reader for undirected graphs
1216 /// This utility reads an \ref lgf-format "LGF" file.
1217 template <typename _Graph>
1221 typedef _Graph Graph;
1222 TEMPLATE_GRAPH_TYPEDEFS(Graph);
1231 std::string _nodes_caption;
1232 std::string _edges_caption;
1233 std::string _attributes_caption;
1235 typedef std::map<std::string, Node> NodeIndex;
1236 NodeIndex _node_index;
1237 typedef std::map<std::string, Edge> EdgeIndex;
1238 EdgeIndex _edge_index;
1240 typedef std::vector<std::pair<std::string,
1241 _reader_bits::MapStorageBase<Node>*> > NodeMaps;
1242 NodeMaps _node_maps;
1244 typedef std::vector<std::pair<std::string,
1245 _reader_bits::MapStorageBase<Edge>*> > EdgeMaps;
1246 EdgeMaps _edge_maps;
1248 typedef std::multimap<std::string, _reader_bits::ValueStorageBase*>
1250 Attributes _attributes;
1259 std::istringstream line;
1263 /// \brief Constructor
1265 /// Construct a undirected graph reader, which reads from the given
1267 GraphReader(std::istream& is, Graph& graph)
1268 : _is(&is), local_is(false), _graph(graph),
1269 _use_nodes(false), _use_edges(false),
1270 _skip_nodes(false), _skip_edges(false) {}
1272 /// \brief Constructor
1274 /// Construct a undirected graph reader, which reads from the given
1276 GraphReader(const std::string& fn, Graph& graph)
1277 : _is(new std::ifstream(fn.c_str())), local_is(true), _graph(graph),
1278 _use_nodes(false), _use_edges(false),
1279 _skip_nodes(false), _skip_edges(false) {}
1281 /// \brief Constructor
1283 /// Construct a undirected graph reader, which reads from the given
1285 GraphReader(const char* fn, Graph& graph)
1286 : _is(new std::ifstream(fn)), local_is(true), _graph(graph),
1287 _use_nodes(false), _use_edges(false),
1288 _skip_nodes(false), _skip_edges(false) {}
1290 /// \brief Destructor
1292 for (typename NodeMaps::iterator it = _node_maps.begin();
1293 it != _node_maps.end(); ++it) {
1297 for (typename EdgeMaps::iterator it = _edge_maps.begin();
1298 it != _edge_maps.end(); ++it) {
1302 for (typename Attributes::iterator it = _attributes.begin();
1303 it != _attributes.end(); ++it) {
1314 friend GraphReader<Graph> graphReader<>(std::istream& is, Graph& graph);
1315 friend GraphReader<Graph> graphReader<>(const std::string& fn,
1317 friend GraphReader<Graph> graphReader<>(const char *fn, Graph& graph);
1319 GraphReader(GraphReader& other)
1320 : _is(other._is), local_is(other.local_is), _graph(other._graph),
1321 _use_nodes(other._use_nodes), _use_edges(other._use_edges),
1322 _skip_nodes(other._skip_nodes), _skip_edges(other._skip_edges) {
1325 other.local_is = false;
1327 _node_index.swap(other._node_index);
1328 _edge_index.swap(other._edge_index);
1330 _node_maps.swap(other._node_maps);
1331 _edge_maps.swap(other._edge_maps);
1332 _attributes.swap(other._attributes);
1334 _nodes_caption = other._nodes_caption;
1335 _edges_caption = other._edges_caption;
1336 _attributes_caption = other._attributes_caption;
1340 GraphReader& operator=(const GraphReader&);
1344 /// \name Reading rules
1347 /// \brief Node map reading rule
1349 /// Add a node map reading rule to the reader.
1350 template <typename Map>
1351 GraphReader& nodeMap(const std::string& caption, Map& map) {
1352 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
1353 _reader_bits::MapStorageBase<Node>* storage =
1354 new _reader_bits::MapStorage<Node, Map>(map);
1355 _node_maps.push_back(std::make_pair(caption, storage));
1359 /// \brief Node map reading rule
1361 /// Add a node map reading rule with specialized converter to the
1363 template <typename Map, typename Converter>
1364 GraphReader& nodeMap(const std::string& caption, Map& map,
1365 const Converter& converter = Converter()) {
1366 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
1367 _reader_bits::MapStorageBase<Node>* storage =
1368 new _reader_bits::MapStorage<Node, Map, Converter>(map, converter);
1369 _node_maps.push_back(std::make_pair(caption, storage));
1373 /// \brief Edge map reading rule
1375 /// Add an edge map reading rule to the reader.
1376 template <typename Map>
1377 GraphReader& edgeMap(const std::string& caption, Map& map) {
1378 checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>();
1379 _reader_bits::MapStorageBase<Edge>* storage =
1380 new _reader_bits::MapStorage<Edge, Map>(map);
1381 _edge_maps.push_back(std::make_pair(caption, storage));
1385 /// \brief Edge map reading rule
1387 /// Add an edge map reading rule with specialized converter to the
1389 template <typename Map, typename Converter>
1390 GraphReader& edgeMap(const std::string& caption, Map& map,
1391 const Converter& converter = Converter()) {
1392 checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>();
1393 _reader_bits::MapStorageBase<Edge>* storage =
1394 new _reader_bits::MapStorage<Edge, Map, Converter>(map, converter);
1395 _edge_maps.push_back(std::make_pair(caption, storage));
1399 /// \brief Arc map reading rule
1401 /// Add an arc map reading rule to the reader.
1402 template <typename Map>
1403 GraphReader& arcMap(const std::string& caption, Map& map) {
1404 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
1405 _reader_bits::MapStorageBase<Edge>* forward_storage =
1406 new _reader_bits::GraphArcMapStorage<Graph, true, Map>(_graph, map);
1407 _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
1408 _reader_bits::MapStorageBase<Edge>* backward_storage =
1409 new _reader_bits::GraphArcMapStorage<Graph, false, Map>(_graph, map);
1410 _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
1414 /// \brief Arc map reading rule
1416 /// Add an arc map reading rule with specialized converter to the
1418 template <typename Map, typename Converter>
1419 GraphReader& arcMap(const std::string& caption, Map& map,
1420 const Converter& converter = Converter()) {
1421 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
1422 _reader_bits::MapStorageBase<Edge>* forward_storage =
1423 new _reader_bits::GraphArcMapStorage<Graph, true, Map, Converter>
1424 (_graph, map, converter);
1425 _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
1426 _reader_bits::MapStorageBase<Edge>* backward_storage =
1427 new _reader_bits::GraphArcMapStorage<Graph, false, Map, Converter>
1428 (_graph, map, converter);
1429 _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
1433 /// \brief Attribute reading rule
1435 /// Add an attribute reading rule to the reader.
1436 template <typename Value>
1437 GraphReader& attribute(const std::string& caption, Value& value) {
1438 _reader_bits::ValueStorageBase* storage =
1439 new _reader_bits::ValueStorage<Value>(value);
1440 _attributes.insert(std::make_pair(caption, storage));
1444 /// \brief Attribute reading rule
1446 /// Add an attribute reading rule with specialized converter to the
1448 template <typename Value, typename Converter>
1449 GraphReader& attribute(const std::string& caption, Value& value,
1450 const Converter& converter = Converter()) {
1451 _reader_bits::ValueStorageBase* storage =
1452 new _reader_bits::ValueStorage<Value, Converter>(value, converter);
1453 _attributes.insert(std::make_pair(caption, storage));
1457 /// \brief Node reading rule
1459 /// Add a node reading rule to reader.
1460 GraphReader& node(const std::string& caption, Node& node) {
1461 typedef _reader_bits::MapLookUpConverter<Node> Converter;
1462 Converter converter(_node_index);
1463 _reader_bits::ValueStorageBase* storage =
1464 new _reader_bits::ValueStorage<Node, Converter>(node, converter);
1465 _attributes.insert(std::make_pair(caption, storage));
1469 /// \brief Edge reading rule
1471 /// Add an edge reading rule to reader.
1472 GraphReader& edge(const std::string& caption, Edge& edge) {
1473 typedef _reader_bits::MapLookUpConverter<Edge> Converter;
1474 Converter converter(_edge_index);
1475 _reader_bits::ValueStorageBase* storage =
1476 new _reader_bits::ValueStorage<Edge, Converter>(edge, converter);
1477 _attributes.insert(std::make_pair(caption, storage));
1481 /// \brief Arc reading rule
1483 /// Add an arc reading rule to reader.
1484 GraphReader& arc(const std::string& caption, Arc& arc) {
1485 typedef _reader_bits::GraphArcLookUpConverter<Graph> Converter;
1486 Converter converter(_graph, _edge_index);
1487 _reader_bits::ValueStorageBase* storage =
1488 new _reader_bits::ValueStorage<Arc, Converter>(arc, converter);
1489 _attributes.insert(std::make_pair(caption, storage));
1495 /// \name Select section by name
1498 /// \brief Set \c \@nodes section to be read
1500 /// Set \c \@nodes section to be read
1501 GraphReader& nodes(const std::string& caption) {
1502 _nodes_caption = caption;
1506 /// \brief Set \c \@edges section to be read
1508 /// Set \c \@edges section to be read
1509 GraphReader& edges(const std::string& caption) {
1510 _edges_caption = caption;
1514 /// \brief Set \c \@attributes section to be read
1516 /// Set \c \@attributes section to be read
1517 GraphReader& attributes(const std::string& caption) {
1518 _attributes_caption = caption;
1524 /// \name Using previously constructed node or edge set
1527 /// \brief Use previously constructed node set
1529 /// Use previously constructed node set, and specify the node
1531 template <typename Map>
1532 GraphReader& useNodes(const Map& map) {
1533 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
1534 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
1536 _writer_bits::DefaultConverter<typename Map::Value> converter;
1537 for (NodeIt n(_graph); n != INVALID; ++n) {
1538 _node_index.insert(std::make_pair(converter(map[n]), n));
1543 /// \brief Use previously constructed node set
1545 /// Use previously constructed node set, and specify the node
1546 /// label map and a functor which converts the label map values to
1548 template <typename Map, typename Converter>
1549 GraphReader& useNodes(const Map& map,
1550 const Converter& converter = Converter()) {
1551 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
1552 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
1554 for (NodeIt n(_graph); n != INVALID; ++n) {
1555 _node_index.insert(std::make_pair(converter(map[n]), n));
1560 /// \brief Use previously constructed edge set
1562 /// Use previously constructed edge set, and specify the edge
1564 template <typename Map>
1565 GraphReader& useEdges(const Map& map) {
1566 checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
1567 LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member");
1569 _writer_bits::DefaultConverter<typename Map::Value> converter;
1570 for (EdgeIt a(_graph); a != INVALID; ++a) {
1571 _edge_index.insert(std::make_pair(converter(map[a]), a));
1576 /// \brief Use previously constructed edge set
1578 /// Use previously constructed edge set, and specify the edge
1579 /// label map and a functor which converts the label map values to
1581 template <typename Map, typename Converter>
1582 GraphReader& useEdges(const Map& map,
1583 const Converter& converter = Converter()) {
1584 checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
1585 LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member");
1587 for (EdgeIt a(_graph); a != INVALID; ++a) {
1588 _edge_index.insert(std::make_pair(converter(map[a]), a));
1593 /// \brief Skips the reading of node section
1595 /// Omit the reading of the node section. This implies that each node
1596 /// map reading rule will be abanoned, and the nodes of the graph
1597 /// will not be constructed, which usually cause that the edge set
1598 /// could not be read due to lack of node name
1599 /// resolving. Therefore, the \c skipEdges() should be used too, or
1600 /// the useNodes() member function should be used to specify the
1601 /// label of the nodes.
1602 GraphReader& skipNodes() {
1603 LEMON_ASSERT(!_skip_nodes, "Skip nodes already set");
1608 /// \brief Skips the reading of edge section
1610 /// Omit the reading of the edge section. This implies that each edge
1611 /// map reading rule will be abanoned, and the edges of the graph
1612 /// will not be constructed.
1613 GraphReader& skipEdges() {
1614 LEMON_ASSERT(!_skip_edges, "Skip edges already set");
1625 while(++line_num, std::getline(*_is, str)) {
1626 line.clear(); line.str(str);
1628 if (line >> std::ws >> c && c != '#') {
1636 bool readSuccess() {
1637 return static_cast<bool>(*_is);
1640 void skipSection() {
1642 while (readSuccess() && line >> c && c != '@') {
1650 std::vector<int> map_index(_node_maps.size());
1651 int map_num, label_index;
1654 if (!readLine() || !(line >> c) || c == '@') {
1655 if (readSuccess() && line) line.putback(c);
1656 if (!_node_maps.empty())
1657 throw DataFormatError("Cannot find map names");
1663 std::map<std::string, int> maps;
1667 while (_reader_bits::readToken(line, map)) {
1668 if (maps.find(map) != maps.end()) {
1669 std::ostringstream msg;
1670 msg << "Multiple occurence of node map: " << map;
1671 throw DataFormatError(msg.str().c_str());
1673 maps.insert(std::make_pair(map, index));
1677 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
1678 std::map<std::string, int>::iterator jt =
1679 maps.find(_node_maps[i].first);
1680 if (jt == maps.end()) {
1681 std::ostringstream msg;
1682 msg << "Map not found in file: " << _node_maps[i].first;
1683 throw DataFormatError(msg.str().c_str());
1685 map_index[i] = jt->second;
1689 std::map<std::string, int>::iterator jt = maps.find("label");
1690 if (jt != maps.end()) {
1691 label_index = jt->second;
1696 map_num = maps.size();
1699 while (readLine() && line >> c && c != '@') {
1702 std::vector<std::string> tokens(map_num);
1703 for (int i = 0; i < map_num; ++i) {
1704 if (!_reader_bits::readToken(line, tokens[i])) {
1705 std::ostringstream msg;
1706 msg << "Column not found (" << i + 1 << ")";
1707 throw DataFormatError(msg.str().c_str());
1710 if (line >> std::ws >> c)
1711 throw DataFormatError("Extra character on the end of line");
1715 n = _graph.addNode();
1716 if (label_index != -1)
1717 _node_index.insert(std::make_pair(tokens[label_index], n));
1719 if (label_index == -1)
1720 throw DataFormatError("Label map not found in file");
1721 typename std::map<std::string, Node>::iterator it =
1722 _node_index.find(tokens[label_index]);
1723 if (it == _node_index.end()) {
1724 std::ostringstream msg;
1725 msg << "Node with label not found: " << tokens[label_index];
1726 throw DataFormatError(msg.str().c_str());
1731 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
1732 _node_maps[i].second->set(n, tokens[map_index[i]]);
1736 if (readSuccess()) {
1743 std::vector<int> map_index(_edge_maps.size());
1744 int map_num, label_index;
1747 if (!readLine() || !(line >> c) || c == '@') {
1748 if (readSuccess() && line) line.putback(c);
1749 if (!_edge_maps.empty())
1750 throw DataFormatError("Cannot find map names");
1756 std::map<std::string, int> maps;
1760 while (_reader_bits::readToken(line, map)) {
1761 if (maps.find(map) != maps.end()) {
1762 std::ostringstream msg;
1763 msg << "Multiple occurence of edge map: " << map;
1764 throw DataFormatError(msg.str().c_str());
1766 maps.insert(std::make_pair(map, index));
1770 for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) {
1771 std::map<std::string, int>::iterator jt =
1772 maps.find(_edge_maps[i].first);
1773 if (jt == maps.end()) {
1774 std::ostringstream msg;
1775 msg << "Map not found in file: " << _edge_maps[i].first;
1776 throw DataFormatError(msg.str().c_str());
1778 map_index[i] = jt->second;
1782 std::map<std::string, int>::iterator jt = maps.find("label");
1783 if (jt != maps.end()) {
1784 label_index = jt->second;
1789 map_num = maps.size();
1792 while (readLine() && line >> c && c != '@') {
1795 std::string source_token;
1796 std::string target_token;
1798 if (!_reader_bits::readToken(line, source_token))
1799 throw DataFormatError("Node u not found");
1801 if (!_reader_bits::readToken(line, target_token))
1802 throw DataFormatError("Node v not found");
1804 std::vector<std::string> tokens(map_num);
1805 for (int i = 0; i < map_num; ++i) {
1806 if (!_reader_bits::readToken(line, tokens[i])) {
1807 std::ostringstream msg;
1808 msg << "Column not found (" << i + 1 << ")";
1809 throw DataFormatError(msg.str().c_str());
1812 if (line >> std::ws >> c)
1813 throw DataFormatError("Extra character on the end of line");
1818 typename NodeIndex::iterator it;
1820 it = _node_index.find(source_token);
1821 if (it == _node_index.end()) {
1822 std::ostringstream msg;
1823 msg << "Item not found: " << source_token;
1824 throw DataFormatError(msg.str().c_str());
1826 Node source = it->second;
1828 it = _node_index.find(target_token);
1829 if (it == _node_index.end()) {
1830 std::ostringstream msg;
1831 msg << "Item not found: " << target_token;
1832 throw DataFormatError(msg.str().c_str());
1834 Node target = it->second;
1836 e = _graph.addEdge(source, target);
1837 if (label_index != -1)
1838 _edge_index.insert(std::make_pair(tokens[label_index], e));
1840 if (label_index == -1)
1841 throw DataFormatError("Label map not found in file");
1842 typename std::map<std::string, Edge>::iterator it =
1843 _edge_index.find(tokens[label_index]);
1844 if (it == _edge_index.end()) {
1845 std::ostringstream msg;
1846 msg << "Edge with label not found: " << tokens[label_index];
1847 throw DataFormatError(msg.str().c_str());
1852 for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) {
1853 _edge_maps[i].second->set(e, tokens[map_index[i]]);
1857 if (readSuccess()) {
1862 void readAttributes() {
1864 std::set<std::string> read_attr;
1867 while (readLine() && line >> c && c != '@') {
1870 std::string attr, token;
1871 if (!_reader_bits::readToken(line, attr))
1872 throw DataFormatError("Attribute name not found");
1873 if (!_reader_bits::readToken(line, token))
1874 throw DataFormatError("Attribute value not found");
1876 throw DataFormatError("Extra character on the end of line");
1879 std::set<std::string>::iterator it = read_attr.find(attr);
1880 if (it != read_attr.end()) {
1881 std::ostringstream msg;
1882 msg << "Multiple occurence of attribute " << attr;
1883 throw DataFormatError(msg.str().c_str());
1885 read_attr.insert(attr);
1889 typename Attributes::iterator it = _attributes.lower_bound(attr);
1890 while (it != _attributes.end() && it->first == attr) {
1891 it->second->set(token);
1897 if (readSuccess()) {
1900 for (typename Attributes::iterator it = _attributes.begin();
1901 it != _attributes.end(); ++it) {
1902 if (read_attr.find(it->first) == read_attr.end()) {
1903 std::ostringstream msg;
1904 msg << "Attribute not found in file: " << it->first;
1905 throw DataFormatError(msg.str().c_str());
1912 /// \name Execution of the reader
1915 /// \brief Start the batch processing
1917 /// This function starts the batch processing
1920 LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
1922 bool nodes_done = _skip_nodes;
1923 bool edges_done = _skip_edges;
1924 bool attributes_done = false;
1930 while (readSuccess()) {
1933 std::string section, caption;
1935 _reader_bits::readToken(line, section);
1936 _reader_bits::readToken(line, caption);
1939 throw DataFormatError("Extra character on the end of line");
1941 if (section == "nodes" && !nodes_done) {
1942 if (_nodes_caption.empty() || _nodes_caption == caption) {
1946 } else if ((section == "edges" || section == "arcs") &&
1948 if (_edges_caption.empty() || _edges_caption == caption) {
1952 } else if (section == "attributes" && !attributes_done) {
1953 if (_attributes_caption.empty() || _attributes_caption == caption) {
1955 attributes_done = true;
1961 } catch (DataFormatError& error) {
1962 error.line(line_num);
1968 throw DataFormatError("Section @nodes not found");
1972 throw DataFormatError("Section @edges not found");
1975 if (!attributes_done && !_attributes.empty()) {
1976 throw DataFormatError("Section @attributes not found");
1985 /// \relates GraphReader
1986 template <typename Graph>
1987 GraphReader<Graph> graphReader(std::istream& is, Graph& graph) {
1988 GraphReader<Graph> tmp(is, graph);
1992 /// \relates GraphReader
1993 template <typename Graph>
1994 GraphReader<Graph> graphReader(const std::string& fn,
1996 GraphReader<Graph> tmp(fn, graph);
2000 /// \relates GraphReader
2001 template <typename Graph>
2002 GraphReader<Graph> graphReader(const char* fn, Graph& graph) {
2003 GraphReader<Graph> tmp(fn, graph);
2007 class SectionReader;
2009 SectionReader sectionReader(std::istream& is);
2010 SectionReader sectionReader(const std::string& fn);
2011 SectionReader sectionReader(const char* fn);
2013 /// \brief Section reader class
2015 /// In the \e LGF file extra sections can be placed, which contain
2016 /// any data in arbitrary format. Such sections can be read with
2017 /// this class. A reading rule can be added with two different
2018 /// functions, with the \c sectionLines() function a functor can
2019 /// process the section line-by-line. While with the \c
2020 /// sectionStream() member the section can be read from an input
2022 class SectionReader {
2028 typedef std::map<std::string, _reader_bits::Section*> Sections;
2032 std::istringstream line;
2036 /// \brief Constructor
2038 /// Construct a section reader, which reads from the given input
2040 SectionReader(std::istream& is)
2041 : _is(&is), local_is(false) {}
2043 /// \brief Constructor
2045 /// Construct a section reader, which reads from the given file.
2046 SectionReader(const std::string& fn)
2047 : _is(new std::ifstream(fn.c_str())), local_is(true) {}
2049 /// \brief Constructor
2051 /// Construct a section reader, which reads from the given file.
2052 SectionReader(const char* fn)
2053 : _is(new std::ifstream(fn)), local_is(true) {}
2055 /// \brief Destructor
2057 for (Sections::iterator it = _sections.begin();
2058 it != _sections.end(); ++it) {
2070 friend SectionReader sectionReader(std::istream& is);
2071 friend SectionReader sectionReader(const std::string& fn);
2072 friend SectionReader sectionReader(const char* fn);
2074 SectionReader(SectionReader& other)
2075 : _is(other._is), local_is(other.local_is) {
2078 other.local_is = false;
2080 _sections.swap(other._sections);
2083 SectionReader& operator=(const SectionReader&);
2087 /// \name Section readers
2090 /// \brief Add a section processor with line oriented reading
2092 /// The first parameter is the type descriptor of the section, the
2093 /// second is a functor, which takes just one \c std::string
2094 /// parameter. At the reading process, each line of the section
2095 /// will be given to the functor object. However, the empty lines
2096 /// and the comment lines are filtered out, and the leading
2097 /// whitespaces are trimmed from each processed string.
2099 /// For example let's see a section, which contain several
2100 /// integers, which should be inserted into a vector.
2108 /// The functor is implemented as an struct:
2110 /// struct NumberSection {
2111 /// std::vector<int>& _data;
2112 /// NumberSection(std::vector<int>& data) : _data(data) {}
2113 /// void operator()(const std::string& line) {
2114 /// std::istringstream ls(line);
2116 /// while (ls >> value) _data.push_back(value);
2122 /// reader.sectionLines("numbers", NumberSection(vec));
2124 template <typename Functor>
2125 SectionReader& sectionLines(const std::string& type, Functor functor) {
2126 LEMON_ASSERT(!type.empty(), "Type is not empty.");
2127 LEMON_ASSERT(_sections.find(type) == _sections.end(),
2128 "Multiple reading of section.");
2129 _sections.insert(std::make_pair(type,
2130 new _reader_bits::LineSection<Functor>(functor)));
2135 /// \brief Add a section processor with stream oriented reading
2137 /// The first parameter is the type of the section, the second is
2138 /// a functor, which takes an \c std::istream& and an int&
2139 /// parameter, the latter regard to the line number of stream. The
2140 /// functor can read the input while the section go on, and the
2141 /// line number should be modified accordingly.
2142 template <typename Functor>
2143 SectionReader& sectionStream(const std::string& type, Functor functor) {
2144 LEMON_ASSERT(!type.empty(), "Type is not empty.");
2145 LEMON_ASSERT(_sections.find(type) == _sections.end(),
2146 "Multiple reading of section.");
2147 _sections.insert(std::make_pair(type,
2148 new _reader_bits::StreamSection<Functor>(functor)));
2158 while(++line_num, std::getline(*_is, str)) {
2159 line.clear(); line.str(str);
2161 if (line >> std::ws >> c && c != '#') {
2169 bool readSuccess() {
2170 return static_cast<bool>(*_is);
2173 void skipSection() {
2175 while (readSuccess() && line >> c && c != '@') {
2184 /// \name Execution of the reader
2187 /// \brief Start the batch processing
2189 /// This function starts the batch processing
2192 LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
2194 std::set<std::string> extra_sections;
2200 while (readSuccess()) {
2203 std::string section, caption;
2205 _reader_bits::readToken(line, section);
2206 _reader_bits::readToken(line, caption);
2209 throw DataFormatError("Extra character on the end of line");
2211 if (extra_sections.find(section) != extra_sections.end()) {
2212 std::ostringstream msg;
2213 msg << "Multiple occurence of section " << section;
2214 throw DataFormatError(msg.str().c_str());
2216 Sections::iterator it = _sections.find(section);
2217 if (it != _sections.end()) {
2218 extra_sections.insert(section);
2219 it->second->process(*_is, line_num);
2223 } catch (DataFormatError& error) {
2224 error.line(line_num);
2228 for (Sections::iterator it = _sections.begin();
2229 it != _sections.end(); ++it) {
2230 if (extra_sections.find(it->first) == extra_sections.end()) {
2231 std::ostringstream os;
2232 os << "Cannot find section: " << it->first;
2233 throw DataFormatError(os.str().c_str());
2242 /// \relates SectionReader
2243 inline SectionReader sectionReader(std::istream& is) {
2244 SectionReader tmp(is);
2248 /// \relates SectionReader
2249 inline SectionReader sectionReader(const std::string& fn) {
2250 SectionReader tmp(fn);
2254 /// \relates SectionReader
2255 inline SectionReader sectionReader(const char* fn) {
2256 SectionReader tmp(fn);
2260 /// \ingroup lemon_io
2262 /// \brief Reader for the contents of the \ref lgf-format "LGF" file
2264 /// This class can be used to read the sections, the map names and
2265 /// the attributes from a file. Usually, the Lemon programs know
2266 /// that, which type of graph, which maps and which attributes
2267 /// should be read from a file, but in general tools (like glemon)
2268 /// the contents of an LGF file should be guessed somehow. This class
2269 /// reads the graph and stores the appropriate information for
2270 /// reading the graph.
2272 ///\code LgfContents contents("graph.lgf");
2275 /// // does it contain any node section and arc section
2276 /// if (contents.nodeSectionNum() == 0 || contents.arcSectionNum()) {
2277 /// std::cerr << "Failure, cannot find graph" << std::endl;
2280 /// std::cout << "The name of the default node section : "
2281 /// << contents.nodeSection(0) << std::endl;
2282 /// std::cout << "The number of the arc maps : "
2283 /// << contents.arcMaps(0).size() << std::endl;
2284 /// std::cout << "The name of second arc map : "
2285 /// << contents.arcMaps(0)[1] << std::endl;
2293 std::vector<std::string> _node_sections;
2294 std::vector<std::string> _edge_sections;
2295 std::vector<std::string> _attribute_sections;
2296 std::vector<std::string> _extra_sections;
2298 std::vector<bool> _arc_sections;
2300 std::vector<std::vector<std::string> > _node_maps;
2301 std::vector<std::vector<std::string> > _edge_maps;
2303 std::vector<std::vector<std::string> > _attributes;
2307 std::istringstream line;
2311 /// \brief Constructor
2313 /// Construct an \e LGF contents reader, which reads from the given
2315 LgfContents(std::istream& is)
2316 : _is(&is), local_is(false) {}
2318 /// \brief Constructor
2320 /// Construct an \e LGF contents reader, which reads from the given
2322 LgfContents(const std::string& fn)
2323 : _is(new std::ifstream(fn.c_str())), local_is(true) {}
2325 /// \brief Constructor
2327 /// Construct an \e LGF contents reader, which reads from the given
2329 LgfContents(const char* fn)
2330 : _is(new std::ifstream(fn)), local_is(true) {}
2332 /// \brief Destructor
2334 if (local_is) delete _is;
2339 LgfContents(const LgfContents&);
2340 LgfContents& operator=(const LgfContents&);
2345 /// \name Node sections
2348 /// \brief Gives back the number of node sections in the file.
2350 /// Gives back the number of node sections in the file.
2351 int nodeSectionNum() const {
2352 return _node_sections.size();
2355 /// \brief Returns the section name at the given position.
2357 /// Returns the section name at the given position.
2358 const std::string& nodeSection(int i) const {
2359 return _node_sections[i];
2362 /// \brief Gives back the node maps for the given section.
2364 /// Gives back the node maps for the given section.
2365 const std::vector<std::string>& nodeMapNames(int i) const {
2366 return _node_maps[i];
2371 /// \name Arc/Edge sections
2374 /// \brief Gives back the number of arc/edge sections in the file.
2376 /// Gives back the number of arc/edge sections in the file.
2377 /// \note It is synonym of \c edgeSectionNum().
2378 int arcSectionNum() const {
2379 return _edge_sections.size();
2382 /// \brief Returns the section name at the given position.
2384 /// Returns the section name at the given position.
2385 /// \note It is synonym of \c edgeSection().
2386 const std::string& arcSection(int i) const {
2387 return _edge_sections[i];
2390 /// \brief Gives back the arc/edge maps for the given section.
2392 /// Gives back the arc/edge maps for the given section.
2393 /// \note It is synonym of \c edgeMapNames().
2394 const std::vector<std::string>& arcMapNames(int i) const {
2395 return _edge_maps[i];
2403 /// \brief Gives back the number of arc/edge sections in the file.
2405 /// Gives back the number of arc/edge sections in the file.
2406 /// \note It is synonym of \c arcSectionNum().
2407 int edgeSectionNum() const {
2408 return _edge_sections.size();
2411 /// \brief Returns the section name at the given position.
2413 /// Returns the section name at the given position.
2414 /// \note It is synonym of \c arcSection().
2415 const std::string& edgeSection(int i) const {
2416 return _edge_sections[i];
2419 /// \brief Gives back the edge maps for the given section.
2421 /// Gives back the edge maps for the given section.
2422 /// \note It is synonym of \c arcMapNames().
2423 const std::vector<std::string>& edgeMapNames(int i) const {
2424 return _edge_maps[i];
2429 /// \name Attribute sections
2432 /// \brief Gives back the number of attribute sections in the file.
2434 /// Gives back the number of attribute sections in the file.
2435 int attributeSectionNum() const {
2436 return _attribute_sections.size();
2439 /// \brief Returns the section name at the given position.
2441 /// Returns the section name at the given position.
2442 const std::string& attributeSectionNames(int i) const {
2443 return _attribute_sections[i];
2446 /// \brief Gives back the attributes for the given section.
2448 /// Gives back the attributes for the given section.
2449 const std::vector<std::string>& attributes(int i) const {
2450 return _attributes[i];
2455 /// \name Extra sections
2458 /// \brief Gives back the number of extra sections in the file.
2460 /// Gives back the number of extra sections in the file.
2461 int extraSectionNum() const {
2462 return _extra_sections.size();
2465 /// \brief Returns the extra section type at the given position.
2467 /// Returns the section type at the given position.
2468 const std::string& extraSection(int i) const {
2469 return _extra_sections[i];
2478 while(++line_num, std::getline(*_is, str)) {
2479 line.clear(); line.str(str);
2481 if (line >> std::ws >> c && c != '#') {
2489 bool readSuccess() {
2490 return static_cast<bool>(*_is);
2493 void skipSection() {
2495 while (readSuccess() && line >> c && c != '@') {
2501 void readMaps(std::vector<std::string>& maps) {
2503 if (!readLine() || !(line >> c) || c == '@') {
2504 if (readSuccess() && line) line.putback(c);
2509 while (_reader_bits::readToken(line, map)) {
2510 maps.push_back(map);
2514 void readAttributes(std::vector<std::string>& attrs) {
2517 while (readSuccess() && line >> c && c != '@') {
2520 _reader_bits::readToken(line, attr);
2521 attrs.push_back(attr);
2529 /// \name Execution of the contents reader
2532 /// \brief Start the reading
2534 /// This function starts the reading
2540 while (readSuccess()) {
2545 std::string section, caption;
2546 _reader_bits::readToken(line, section);
2547 _reader_bits::readToken(line, caption);
2549 if (section == "nodes") {
2550 _node_sections.push_back(caption);
2551 _node_maps.push_back(std::vector<std::string>());
2552 readMaps(_node_maps.back());
2553 readLine(); skipSection();
2554 } else if (section == "arcs" || section == "edges") {
2555 _edge_sections.push_back(caption);
2556 _arc_sections.push_back(section == "arcs");
2557 _edge_maps.push_back(std::vector<std::string>());
2558 readMaps(_edge_maps.back());
2559 readLine(); skipSection();
2560 } else if (section == "attributes") {
2561 _attribute_sections.push_back(caption);
2562 _attributes.push_back(std::vector<std::string>());
2563 readAttributes(_attributes.back());
2565 _extra_sections.push_back(section);
2566 readLine(); skipSection();