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" 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 \ref lgf-format "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 \c 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 /// converted to the value type of the map. 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 functions is multipass reading, which is
441 /// important if two \c \@arcs sections must be read from the
442 /// file. In this case 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 to 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 abandoned, 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 resolving.
790 /// Therefore \c skipArcs() function should also be used, or
791 /// \c useNodes() should be used to specify the label of the nodes.
792 DigraphReader& skipNodes() {
793 LEMON_ASSERT(!_skip_nodes, "Skip nodes already set");
798 /// \brief Skips the reading of arc section
800 /// Omit the reading of the arc section. This implies that each arc
801 /// map reading rule will be abandoned, and the arcs of the graph
802 /// will not be constructed.
803 DigraphReader& skipArcs() {
804 LEMON_ASSERT(!_skip_arcs, "Skip arcs already set");
815 while(++line_num, std::getline(*_is, str)) {
816 line.clear(); line.str(str);
818 if (line >> std::ws >> c && c != '#') {
827 return static_cast<bool>(*_is);
832 while (readSuccess() && line >> c && c != '@') {
840 std::vector<int> map_index(_node_maps.size());
841 int map_num, label_index;
844 if (!readLine() || !(line >> c) || c == '@') {
845 if (readSuccess() && line) line.putback(c);
846 if (!_node_maps.empty())
847 throw DataFormatError("Cannot find map names");
853 std::map<std::string, int> maps;
857 while (_reader_bits::readToken(line, map)) {
858 if (maps.find(map) != maps.end()) {
859 std::ostringstream msg;
860 msg << "Multiple occurence of node map: " << map;
861 throw DataFormatError(msg.str().c_str());
863 maps.insert(std::make_pair(map, index));
867 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
868 std::map<std::string, int>::iterator jt =
869 maps.find(_node_maps[i].first);
870 if (jt == maps.end()) {
871 std::ostringstream msg;
872 msg << "Map not found in file: " << _node_maps[i].first;
873 throw DataFormatError(msg.str().c_str());
875 map_index[i] = jt->second;
879 std::map<std::string, int>::iterator jt = maps.find("label");
880 if (jt != maps.end()) {
881 label_index = jt->second;
886 map_num = maps.size();
889 while (readLine() && line >> c && c != '@') {
892 std::vector<std::string> tokens(map_num);
893 for (int i = 0; i < map_num; ++i) {
894 if (!_reader_bits::readToken(line, tokens[i])) {
895 std::ostringstream msg;
896 msg << "Column not found (" << i + 1 << ")";
897 throw DataFormatError(msg.str().c_str());
900 if (line >> std::ws >> c)
901 throw DataFormatError("Extra character on the end of line");
905 n = _digraph.addNode();
906 if (label_index != -1)
907 _node_index.insert(std::make_pair(tokens[label_index], n));
909 if (label_index == -1)
910 throw DataFormatError("Label map not found in file");
911 typename std::map<std::string, Node>::iterator it =
912 _node_index.find(tokens[label_index]);
913 if (it == _node_index.end()) {
914 std::ostringstream msg;
915 msg << "Node with label not found: " << tokens[label_index];
916 throw DataFormatError(msg.str().c_str());
921 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
922 _node_maps[i].second->set(n, tokens[map_index[i]]);
933 std::vector<int> map_index(_arc_maps.size());
934 int map_num, label_index;
937 if (!readLine() || !(line >> c) || c == '@') {
938 if (readSuccess() && line) line.putback(c);
939 if (!_arc_maps.empty())
940 throw DataFormatError("Cannot find map names");
946 std::map<std::string, int> maps;
950 while (_reader_bits::readToken(line, map)) {
951 if (maps.find(map) != maps.end()) {
952 std::ostringstream msg;
953 msg << "Multiple occurence of arc map: " << map;
954 throw DataFormatError(msg.str().c_str());
956 maps.insert(std::make_pair(map, index));
960 for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) {
961 std::map<std::string, int>::iterator jt =
962 maps.find(_arc_maps[i].first);
963 if (jt == maps.end()) {
964 std::ostringstream msg;
965 msg << "Map not found in file: " << _arc_maps[i].first;
966 throw DataFormatError(msg.str().c_str());
968 map_index[i] = jt->second;
972 std::map<std::string, int>::iterator jt = maps.find("label");
973 if (jt != maps.end()) {
974 label_index = jt->second;
979 map_num = maps.size();
982 while (readLine() && line >> c && c != '@') {
985 std::string source_token;
986 std::string target_token;
988 if (!_reader_bits::readToken(line, source_token))
989 throw DataFormatError("Source not found");
991 if (!_reader_bits::readToken(line, target_token))
992 throw DataFormatError("Target not found");
994 std::vector<std::string> tokens(map_num);
995 for (int i = 0; i < map_num; ++i) {
996 if (!_reader_bits::readToken(line, tokens[i])) {
997 std::ostringstream msg;
998 msg << "Column not found (" << i + 1 << ")";
999 throw DataFormatError(msg.str().c_str());
1002 if (line >> std::ws >> c)
1003 throw DataFormatError("Extra character on the end of line");
1008 typename NodeIndex::iterator it;
1010 it = _node_index.find(source_token);
1011 if (it == _node_index.end()) {
1012 std::ostringstream msg;
1013 msg << "Item not found: " << source_token;
1014 throw DataFormatError(msg.str().c_str());
1016 Node source = it->second;
1018 it = _node_index.find(target_token);
1019 if (it == _node_index.end()) {
1020 std::ostringstream msg;
1021 msg << "Item not found: " << target_token;
1022 throw DataFormatError(msg.str().c_str());
1024 Node target = it->second;
1026 a = _digraph.addArc(source, target);
1027 if (label_index != -1)
1028 _arc_index.insert(std::make_pair(tokens[label_index], a));
1030 if (label_index == -1)
1031 throw DataFormatError("Label map not found in file");
1032 typename std::map<std::string, Arc>::iterator it =
1033 _arc_index.find(tokens[label_index]);
1034 if (it == _arc_index.end()) {
1035 std::ostringstream msg;
1036 msg << "Arc with label not found: " << tokens[label_index];
1037 throw DataFormatError(msg.str().c_str());
1042 for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) {
1043 _arc_maps[i].second->set(a, tokens[map_index[i]]);
1047 if (readSuccess()) {
1052 void readAttributes() {
1054 std::set<std::string> read_attr;
1057 while (readLine() && line >> c && c != '@') {
1060 std::string attr, token;
1061 if (!_reader_bits::readToken(line, attr))
1062 throw DataFormatError("Attribute name not found");
1063 if (!_reader_bits::readToken(line, token))
1064 throw DataFormatError("Attribute value not found");
1066 throw DataFormatError("Extra character on the end of line");
1069 std::set<std::string>::iterator it = read_attr.find(attr);
1070 if (it != read_attr.end()) {
1071 std::ostringstream msg;
1072 msg << "Multiple occurence of attribute " << attr;
1073 throw DataFormatError(msg.str().c_str());
1075 read_attr.insert(attr);
1079 typename Attributes::iterator it = _attributes.lower_bound(attr);
1080 while (it != _attributes.end() && it->first == attr) {
1081 it->second->set(token);
1087 if (readSuccess()) {
1090 for (typename Attributes::iterator it = _attributes.begin();
1091 it != _attributes.end(); ++it) {
1092 if (read_attr.find(it->first) == read_attr.end()) {
1093 std::ostringstream msg;
1094 msg << "Attribute not found in file: " << it->first;
1095 throw DataFormatError(msg.str().c_str());
1102 /// \name Execution of the reader
1105 /// \brief Start the batch processing
1107 /// This function starts the batch processing
1109 LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
1111 throw DataFormatError("Cannot find file");
1114 bool nodes_done = _skip_nodes;
1115 bool arcs_done = _skip_arcs;
1116 bool attributes_done = false;
1122 while (readSuccess()) {
1125 std::string section, caption;
1127 _reader_bits::readToken(line, section);
1128 _reader_bits::readToken(line, caption);
1131 throw DataFormatError("Extra character on the end of line");
1133 if (section == "nodes" && !nodes_done) {
1134 if (_nodes_caption.empty() || _nodes_caption == caption) {
1138 } else if ((section == "arcs" || section == "edges") &&
1140 if (_arcs_caption.empty() || _arcs_caption == caption) {
1144 } else if (section == "attributes" && !attributes_done) {
1145 if (_attributes_caption.empty() || _attributes_caption == caption) {
1147 attributes_done = true;
1153 } catch (DataFormatError& error) {
1154 error.line(line_num);
1160 throw DataFormatError("Section @nodes not found");
1164 throw DataFormatError("Section @arcs not found");
1167 if (!attributes_done && !_attributes.empty()) {
1168 throw DataFormatError("Section @attributes not found");
1177 /// \brief Return a \ref DigraphReader class
1179 /// This function just returns a \ref DigraphReader class.
1180 /// \relates DigraphReader
1181 template <typename Digraph>
1182 DigraphReader<Digraph> digraphReader(std::istream& is, Digraph& digraph) {
1183 DigraphReader<Digraph> tmp(is, digraph);
1187 /// \brief Return a \ref DigraphReader class
1189 /// This function just returns a \ref DigraphReader class.
1190 /// \relates DigraphReader
1191 template <typename Digraph>
1192 DigraphReader<Digraph> digraphReader(const std::string& fn,
1194 DigraphReader<Digraph> tmp(fn, digraph);
1198 /// \brief Return a \ref DigraphReader class
1200 /// This function just returns a \ref DigraphReader class.
1201 /// \relates DigraphReader
1202 template <typename Digraph>
1203 DigraphReader<Digraph> digraphReader(const char* fn, Digraph& digraph) {
1204 DigraphReader<Digraph> tmp(fn, digraph);
1208 template <typename Graph>
1211 template <typename Graph>
1212 GraphReader<Graph> graphReader(std::istream& is, Graph& graph);
1214 template <typename Graph>
1215 GraphReader<Graph> graphReader(const std::string& fn, Graph& graph);
1217 template <typename Graph>
1218 GraphReader<Graph> graphReader(const char *fn, Graph& graph);
1220 /// \ingroup lemon_io
1222 /// \brief \ref lgf-format "LGF" reader for undirected graphs
1224 /// This utility reads an \ref lgf-format "LGF" file.
1226 /// It can be used almost the same way as \c DigraphReader.
1227 /// The only difference is that this class can handle edges and
1228 /// edge maps as well as arcs and arc maps.
1229 template <typename _Graph>
1233 typedef _Graph Graph;
1234 TEMPLATE_GRAPH_TYPEDEFS(Graph);
1243 std::string _nodes_caption;
1244 std::string _edges_caption;
1245 std::string _attributes_caption;
1247 typedef std::map<std::string, Node> NodeIndex;
1248 NodeIndex _node_index;
1249 typedef std::map<std::string, Edge> EdgeIndex;
1250 EdgeIndex _edge_index;
1252 typedef std::vector<std::pair<std::string,
1253 _reader_bits::MapStorageBase<Node>*> > NodeMaps;
1254 NodeMaps _node_maps;
1256 typedef std::vector<std::pair<std::string,
1257 _reader_bits::MapStorageBase<Edge>*> > EdgeMaps;
1258 EdgeMaps _edge_maps;
1260 typedef std::multimap<std::string, _reader_bits::ValueStorageBase*>
1262 Attributes _attributes;
1271 std::istringstream line;
1275 /// \brief Constructor
1277 /// Construct an undirected graph reader, which reads from the given
1279 GraphReader(std::istream& is, Graph& graph)
1280 : _is(&is), local_is(false), _graph(graph),
1281 _use_nodes(false), _use_edges(false),
1282 _skip_nodes(false), _skip_edges(false) {}
1284 /// \brief Constructor
1286 /// Construct an undirected graph reader, which reads from the given
1288 GraphReader(const std::string& fn, Graph& graph)
1289 : _is(new std::ifstream(fn.c_str())), local_is(true), _graph(graph),
1290 _use_nodes(false), _use_edges(false),
1291 _skip_nodes(false), _skip_edges(false) {}
1293 /// \brief Constructor
1295 /// Construct an undirected graph reader, which reads from the given
1297 GraphReader(const char* fn, Graph& graph)
1298 : _is(new std::ifstream(fn)), local_is(true), _graph(graph),
1299 _use_nodes(false), _use_edges(false),
1300 _skip_nodes(false), _skip_edges(false) {}
1302 /// \brief Destructor
1304 for (typename NodeMaps::iterator it = _node_maps.begin();
1305 it != _node_maps.end(); ++it) {
1309 for (typename EdgeMaps::iterator it = _edge_maps.begin();
1310 it != _edge_maps.end(); ++it) {
1314 for (typename Attributes::iterator it = _attributes.begin();
1315 it != _attributes.end(); ++it) {
1326 friend GraphReader<Graph> graphReader<>(std::istream& is, Graph& graph);
1327 friend GraphReader<Graph> graphReader<>(const std::string& fn,
1329 friend GraphReader<Graph> graphReader<>(const char *fn, Graph& graph);
1331 GraphReader(GraphReader& other)
1332 : _is(other._is), local_is(other.local_is), _graph(other._graph),
1333 _use_nodes(other._use_nodes), _use_edges(other._use_edges),
1334 _skip_nodes(other._skip_nodes), _skip_edges(other._skip_edges) {
1337 other.local_is = false;
1339 _node_index.swap(other._node_index);
1340 _edge_index.swap(other._edge_index);
1342 _node_maps.swap(other._node_maps);
1343 _edge_maps.swap(other._edge_maps);
1344 _attributes.swap(other._attributes);
1346 _nodes_caption = other._nodes_caption;
1347 _edges_caption = other._edges_caption;
1348 _attributes_caption = other._attributes_caption;
1352 GraphReader& operator=(const GraphReader&);
1356 /// \name Reading rules
1359 /// \brief Node map reading rule
1361 /// Add a node map reading rule to the reader.
1362 template <typename Map>
1363 GraphReader& nodeMap(const std::string& caption, Map& map) {
1364 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
1365 _reader_bits::MapStorageBase<Node>* storage =
1366 new _reader_bits::MapStorage<Node, Map>(map);
1367 _node_maps.push_back(std::make_pair(caption, storage));
1371 /// \brief Node map reading rule
1373 /// Add a node map reading rule with specialized converter to the
1375 template <typename Map, typename Converter>
1376 GraphReader& nodeMap(const std::string& caption, Map& map,
1377 const Converter& converter = Converter()) {
1378 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
1379 _reader_bits::MapStorageBase<Node>* storage =
1380 new _reader_bits::MapStorage<Node, Map, Converter>(map, converter);
1381 _node_maps.push_back(std::make_pair(caption, storage));
1385 /// \brief Edge map reading rule
1387 /// Add an edge map reading rule to the reader.
1388 template <typename Map>
1389 GraphReader& edgeMap(const std::string& caption, Map& map) {
1390 checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>();
1391 _reader_bits::MapStorageBase<Edge>* storage =
1392 new _reader_bits::MapStorage<Edge, Map>(map);
1393 _edge_maps.push_back(std::make_pair(caption, storage));
1397 /// \brief Edge map reading rule
1399 /// Add an edge map reading rule with specialized converter to the
1401 template <typename Map, typename Converter>
1402 GraphReader& edgeMap(const std::string& caption, Map& map,
1403 const Converter& converter = Converter()) {
1404 checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>();
1405 _reader_bits::MapStorageBase<Edge>* storage =
1406 new _reader_bits::MapStorage<Edge, Map, Converter>(map, converter);
1407 _edge_maps.push_back(std::make_pair(caption, storage));
1411 /// \brief Arc map reading rule
1413 /// Add an arc map reading rule to the reader.
1414 template <typename Map>
1415 GraphReader& arcMap(const std::string& caption, Map& map) {
1416 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
1417 _reader_bits::MapStorageBase<Edge>* forward_storage =
1418 new _reader_bits::GraphArcMapStorage<Graph, true, Map>(_graph, map);
1419 _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
1420 _reader_bits::MapStorageBase<Edge>* backward_storage =
1421 new _reader_bits::GraphArcMapStorage<Graph, false, Map>(_graph, map);
1422 _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
1426 /// \brief Arc map reading rule
1428 /// Add an arc map reading rule with specialized converter to the
1430 template <typename Map, typename Converter>
1431 GraphReader& arcMap(const std::string& caption, Map& map,
1432 const Converter& converter = Converter()) {
1433 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
1434 _reader_bits::MapStorageBase<Edge>* forward_storage =
1435 new _reader_bits::GraphArcMapStorage<Graph, true, Map, Converter>
1436 (_graph, map, converter);
1437 _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
1438 _reader_bits::MapStorageBase<Edge>* backward_storage =
1439 new _reader_bits::GraphArcMapStorage<Graph, false, Map, Converter>
1440 (_graph, map, converter);
1441 _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
1445 /// \brief Attribute reading rule
1447 /// Add an attribute reading rule to the reader.
1448 template <typename Value>
1449 GraphReader& attribute(const std::string& caption, Value& value) {
1450 _reader_bits::ValueStorageBase* storage =
1451 new _reader_bits::ValueStorage<Value>(value);
1452 _attributes.insert(std::make_pair(caption, storage));
1456 /// \brief Attribute reading rule
1458 /// Add an attribute reading rule with specialized converter to the
1460 template <typename Value, typename Converter>
1461 GraphReader& attribute(const std::string& caption, Value& value,
1462 const Converter& converter = Converter()) {
1463 _reader_bits::ValueStorageBase* storage =
1464 new _reader_bits::ValueStorage<Value, Converter>(value, converter);
1465 _attributes.insert(std::make_pair(caption, storage));
1469 /// \brief Node reading rule
1471 /// Add a node reading rule to reader.
1472 GraphReader& node(const std::string& caption, Node& node) {
1473 typedef _reader_bits::MapLookUpConverter<Node> Converter;
1474 Converter converter(_node_index);
1475 _reader_bits::ValueStorageBase* storage =
1476 new _reader_bits::ValueStorage<Node, Converter>(node, converter);
1477 _attributes.insert(std::make_pair(caption, storage));
1481 /// \brief Edge reading rule
1483 /// Add an edge reading rule to reader.
1484 GraphReader& edge(const std::string& caption, Edge& edge) {
1485 typedef _reader_bits::MapLookUpConverter<Edge> Converter;
1486 Converter converter(_edge_index);
1487 _reader_bits::ValueStorageBase* storage =
1488 new _reader_bits::ValueStorage<Edge, Converter>(edge, converter);
1489 _attributes.insert(std::make_pair(caption, storage));
1493 /// \brief Arc reading rule
1495 /// Add an arc reading rule to reader.
1496 GraphReader& arc(const std::string& caption, Arc& arc) {
1497 typedef _reader_bits::GraphArcLookUpConverter<Graph> Converter;
1498 Converter converter(_graph, _edge_index);
1499 _reader_bits::ValueStorageBase* storage =
1500 new _reader_bits::ValueStorage<Arc, Converter>(arc, converter);
1501 _attributes.insert(std::make_pair(caption, storage));
1507 /// \name Select section by name
1510 /// \brief Set \c \@nodes section to be read
1512 /// Set \c \@nodes section to be read.
1513 GraphReader& nodes(const std::string& caption) {
1514 _nodes_caption = caption;
1518 /// \brief Set \c \@edges section to be read
1520 /// Set \c \@edges section to be read.
1521 GraphReader& edges(const std::string& caption) {
1522 _edges_caption = caption;
1526 /// \brief Set \c \@attributes section to be read
1528 /// Set \c \@attributes section to be read.
1529 GraphReader& attributes(const std::string& caption) {
1530 _attributes_caption = caption;
1536 /// \name Using previously constructed node or edge set
1539 /// \brief Use previously constructed node set
1541 /// Use previously constructed node set, and specify the node
1543 template <typename Map>
1544 GraphReader& useNodes(const Map& map) {
1545 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
1546 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
1548 _writer_bits::DefaultConverter<typename Map::Value> converter;
1549 for (NodeIt n(_graph); n != INVALID; ++n) {
1550 _node_index.insert(std::make_pair(converter(map[n]), n));
1555 /// \brief Use previously constructed node set
1557 /// Use previously constructed node set, and specify the node
1558 /// label map and a functor which converts the label map values to
1560 template <typename Map, typename Converter>
1561 GraphReader& useNodes(const Map& map,
1562 const Converter& converter = Converter()) {
1563 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
1564 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
1566 for (NodeIt n(_graph); n != INVALID; ++n) {
1567 _node_index.insert(std::make_pair(converter(map[n]), n));
1572 /// \brief Use previously constructed edge set
1574 /// Use previously constructed edge set, and specify the edge
1576 template <typename Map>
1577 GraphReader& useEdges(const Map& map) {
1578 checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
1579 LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member");
1581 _writer_bits::DefaultConverter<typename Map::Value> converter;
1582 for (EdgeIt a(_graph); a != INVALID; ++a) {
1583 _edge_index.insert(std::make_pair(converter(map[a]), a));
1588 /// \brief Use previously constructed edge set
1590 /// Use previously constructed edge set, and specify the edge
1591 /// label map and a functor which converts the label map values to
1593 template <typename Map, typename Converter>
1594 GraphReader& useEdges(const Map& map,
1595 const Converter& converter = Converter()) {
1596 checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
1597 LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member");
1599 for (EdgeIt a(_graph); a != INVALID; ++a) {
1600 _edge_index.insert(std::make_pair(converter(map[a]), a));
1605 /// \brief Skip the reading of node section
1607 /// Omit the reading of the node section. This implies that each node
1608 /// map reading rule will be abandoned, and the nodes of the graph
1609 /// will not be constructed, which usually cause that the edge set
1610 /// could not be read due to lack of node name
1611 /// could not be read due to lack of node name resolving.
1612 /// Therefore \c skipEdges() function should also be used, or
1613 /// \c useNodes() should be used to specify the label of the nodes.
1614 GraphReader& skipNodes() {
1615 LEMON_ASSERT(!_skip_nodes, "Skip nodes already set");
1620 /// \brief Skip the reading of edge section
1622 /// Omit the reading of the edge section. This implies that each edge
1623 /// map reading rule will be abandoned, and the edges of the graph
1624 /// will not be constructed.
1625 GraphReader& skipEdges() {
1626 LEMON_ASSERT(!_skip_edges, "Skip edges already set");
1637 while(++line_num, std::getline(*_is, str)) {
1638 line.clear(); line.str(str);
1640 if (line >> std::ws >> c && c != '#') {
1648 bool readSuccess() {
1649 return static_cast<bool>(*_is);
1652 void skipSection() {
1654 while (readSuccess() && line >> c && c != '@') {
1662 std::vector<int> map_index(_node_maps.size());
1663 int map_num, label_index;
1666 if (!readLine() || !(line >> c) || c == '@') {
1667 if (readSuccess() && line) line.putback(c);
1668 if (!_node_maps.empty())
1669 throw DataFormatError("Cannot find map names");
1675 std::map<std::string, int> maps;
1679 while (_reader_bits::readToken(line, map)) {
1680 if (maps.find(map) != maps.end()) {
1681 std::ostringstream msg;
1682 msg << "Multiple occurence of node map: " << map;
1683 throw DataFormatError(msg.str().c_str());
1685 maps.insert(std::make_pair(map, index));
1689 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
1690 std::map<std::string, int>::iterator jt =
1691 maps.find(_node_maps[i].first);
1692 if (jt == maps.end()) {
1693 std::ostringstream msg;
1694 msg << "Map not found in file: " << _node_maps[i].first;
1695 throw DataFormatError(msg.str().c_str());
1697 map_index[i] = jt->second;
1701 std::map<std::string, int>::iterator jt = maps.find("label");
1702 if (jt != maps.end()) {
1703 label_index = jt->second;
1708 map_num = maps.size();
1711 while (readLine() && line >> c && c != '@') {
1714 std::vector<std::string> tokens(map_num);
1715 for (int i = 0; i < map_num; ++i) {
1716 if (!_reader_bits::readToken(line, tokens[i])) {
1717 std::ostringstream msg;
1718 msg << "Column not found (" << i + 1 << ")";
1719 throw DataFormatError(msg.str().c_str());
1722 if (line >> std::ws >> c)
1723 throw DataFormatError("Extra character on the end of line");
1727 n = _graph.addNode();
1728 if (label_index != -1)
1729 _node_index.insert(std::make_pair(tokens[label_index], n));
1731 if (label_index == -1)
1732 throw DataFormatError("Label map not found in file");
1733 typename std::map<std::string, Node>::iterator it =
1734 _node_index.find(tokens[label_index]);
1735 if (it == _node_index.end()) {
1736 std::ostringstream msg;
1737 msg << "Node with label not found: " << tokens[label_index];
1738 throw DataFormatError(msg.str().c_str());
1743 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
1744 _node_maps[i].second->set(n, tokens[map_index[i]]);
1748 if (readSuccess()) {
1755 std::vector<int> map_index(_edge_maps.size());
1756 int map_num, label_index;
1759 if (!readLine() || !(line >> c) || c == '@') {
1760 if (readSuccess() && line) line.putback(c);
1761 if (!_edge_maps.empty())
1762 throw DataFormatError("Cannot find map names");
1768 std::map<std::string, int> maps;
1772 while (_reader_bits::readToken(line, map)) {
1773 if (maps.find(map) != maps.end()) {
1774 std::ostringstream msg;
1775 msg << "Multiple occurence of edge map: " << map;
1776 throw DataFormatError(msg.str().c_str());
1778 maps.insert(std::make_pair(map, index));
1782 for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) {
1783 std::map<std::string, int>::iterator jt =
1784 maps.find(_edge_maps[i].first);
1785 if (jt == maps.end()) {
1786 std::ostringstream msg;
1787 msg << "Map not found in file: " << _edge_maps[i].first;
1788 throw DataFormatError(msg.str().c_str());
1790 map_index[i] = jt->second;
1794 std::map<std::string, int>::iterator jt = maps.find("label");
1795 if (jt != maps.end()) {
1796 label_index = jt->second;
1801 map_num = maps.size();
1804 while (readLine() && line >> c && c != '@') {
1807 std::string source_token;
1808 std::string target_token;
1810 if (!_reader_bits::readToken(line, source_token))
1811 throw DataFormatError("Node u not found");
1813 if (!_reader_bits::readToken(line, target_token))
1814 throw DataFormatError("Node v not found");
1816 std::vector<std::string> tokens(map_num);
1817 for (int i = 0; i < map_num; ++i) {
1818 if (!_reader_bits::readToken(line, tokens[i])) {
1819 std::ostringstream msg;
1820 msg << "Column not found (" << i + 1 << ")";
1821 throw DataFormatError(msg.str().c_str());
1824 if (line >> std::ws >> c)
1825 throw DataFormatError("Extra character on the end of line");
1830 typename NodeIndex::iterator it;
1832 it = _node_index.find(source_token);
1833 if (it == _node_index.end()) {
1834 std::ostringstream msg;
1835 msg << "Item not found: " << source_token;
1836 throw DataFormatError(msg.str().c_str());
1838 Node source = it->second;
1840 it = _node_index.find(target_token);
1841 if (it == _node_index.end()) {
1842 std::ostringstream msg;
1843 msg << "Item not found: " << target_token;
1844 throw DataFormatError(msg.str().c_str());
1846 Node target = it->second;
1848 e = _graph.addEdge(source, target);
1849 if (label_index != -1)
1850 _edge_index.insert(std::make_pair(tokens[label_index], e));
1852 if (label_index == -1)
1853 throw DataFormatError("Label map not found in file");
1854 typename std::map<std::string, Edge>::iterator it =
1855 _edge_index.find(tokens[label_index]);
1856 if (it == _edge_index.end()) {
1857 std::ostringstream msg;
1858 msg << "Edge with label not found: " << tokens[label_index];
1859 throw DataFormatError(msg.str().c_str());
1864 for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) {
1865 _edge_maps[i].second->set(e, tokens[map_index[i]]);
1869 if (readSuccess()) {
1874 void readAttributes() {
1876 std::set<std::string> read_attr;
1879 while (readLine() && line >> c && c != '@') {
1882 std::string attr, token;
1883 if (!_reader_bits::readToken(line, attr))
1884 throw DataFormatError("Attribute name not found");
1885 if (!_reader_bits::readToken(line, token))
1886 throw DataFormatError("Attribute value not found");
1888 throw DataFormatError("Extra character on the end of line");
1891 std::set<std::string>::iterator it = read_attr.find(attr);
1892 if (it != read_attr.end()) {
1893 std::ostringstream msg;
1894 msg << "Multiple occurence of attribute " << attr;
1895 throw DataFormatError(msg.str().c_str());
1897 read_attr.insert(attr);
1901 typename Attributes::iterator it = _attributes.lower_bound(attr);
1902 while (it != _attributes.end() && it->first == attr) {
1903 it->second->set(token);
1909 if (readSuccess()) {
1912 for (typename Attributes::iterator it = _attributes.begin();
1913 it != _attributes.end(); ++it) {
1914 if (read_attr.find(it->first) == read_attr.end()) {
1915 std::ostringstream msg;
1916 msg << "Attribute not found in file: " << it->first;
1917 throw DataFormatError(msg.str().c_str());
1924 /// \name Execution of the reader
1927 /// \brief Start the batch processing
1929 /// This function starts the batch processing
1932 LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
1934 bool nodes_done = _skip_nodes;
1935 bool edges_done = _skip_edges;
1936 bool attributes_done = false;
1942 while (readSuccess()) {
1945 std::string section, caption;
1947 _reader_bits::readToken(line, section);
1948 _reader_bits::readToken(line, caption);
1951 throw DataFormatError("Extra character on the end of line");
1953 if (section == "nodes" && !nodes_done) {
1954 if (_nodes_caption.empty() || _nodes_caption == caption) {
1958 } else if ((section == "edges" || section == "arcs") &&
1960 if (_edges_caption.empty() || _edges_caption == caption) {
1964 } else if (section == "attributes" && !attributes_done) {
1965 if (_attributes_caption.empty() || _attributes_caption == caption) {
1967 attributes_done = true;
1973 } catch (DataFormatError& error) {
1974 error.line(line_num);
1980 throw DataFormatError("Section @nodes not found");
1984 throw DataFormatError("Section @edges not found");
1987 if (!attributes_done && !_attributes.empty()) {
1988 throw DataFormatError("Section @attributes not found");
1997 /// \brief Return a \ref GraphReader class
1999 /// This function just returns a \ref GraphReader class.
2000 /// \relates GraphReader
2001 template <typename Graph>
2002 GraphReader<Graph> graphReader(std::istream& is, Graph& graph) {
2003 GraphReader<Graph> tmp(is, graph);
2007 /// \brief Return a \ref GraphReader class
2009 /// This function just returns a \ref GraphReader class.
2010 /// \relates GraphReader
2011 template <typename Graph>
2012 GraphReader<Graph> graphReader(const std::string& fn,
2014 GraphReader<Graph> tmp(fn, graph);
2018 /// \brief Return a \ref GraphReader class
2020 /// This function just returns a \ref GraphReader class.
2021 /// \relates GraphReader
2022 template <typename Graph>
2023 GraphReader<Graph> graphReader(const char* fn, Graph& graph) {
2024 GraphReader<Graph> tmp(fn, graph);
2028 class SectionReader;
2030 SectionReader sectionReader(std::istream& is);
2031 SectionReader sectionReader(const std::string& fn);
2032 SectionReader sectionReader(const char* fn);
2034 /// \ingroup lemon_io
2036 /// \brief Section reader class
2038 /// In the \ref lgf-format "LGF" file extra sections can be placed,
2039 /// which contain any data in arbitrary format. Such sections can be
2040 /// read with this class. A reading rule can be added to the class
2041 /// with two different functions. With the \c sectionLines() function a
2042 /// functor can process the section line-by-line, while with the \c
2043 /// sectionStream() member the section can be read from an input
2045 class SectionReader {
2051 typedef std::map<std::string, _reader_bits::Section*> Sections;
2055 std::istringstream line;
2059 /// \brief Constructor
2061 /// Construct a section reader, which reads from the given input
2063 SectionReader(std::istream& is)
2064 : _is(&is), local_is(false) {}
2066 /// \brief Constructor
2068 /// Construct a section reader, which reads from the given file.
2069 SectionReader(const std::string& fn)
2070 : _is(new std::ifstream(fn.c_str())), local_is(true) {}
2072 /// \brief Constructor
2074 /// Construct a section reader, which reads from the given file.
2075 SectionReader(const char* fn)
2076 : _is(new std::ifstream(fn)), local_is(true) {}
2078 /// \brief Destructor
2080 for (Sections::iterator it = _sections.begin();
2081 it != _sections.end(); ++it) {
2093 friend SectionReader sectionReader(std::istream& is);
2094 friend SectionReader sectionReader(const std::string& fn);
2095 friend SectionReader sectionReader(const char* fn);
2097 SectionReader(SectionReader& other)
2098 : _is(other._is), local_is(other.local_is) {
2101 other.local_is = false;
2103 _sections.swap(other._sections);
2106 SectionReader& operator=(const SectionReader&);
2110 /// \name Section readers
2113 /// \brief Add a section processor with line oriented reading
2115 /// The first parameter is the type descriptor of the section, the
2116 /// second is a functor, which takes just one \c std::string
2117 /// parameter. At the reading process, each line of the section
2118 /// will be given to the functor object. However, the empty lines
2119 /// and the comment lines are filtered out, and the leading
2120 /// whitespaces are trimmed from each processed string.
2122 /// For example let's see a section, which contain several
2123 /// integers, which should be inserted into a vector.
2131 /// The functor is implemented as a struct:
2133 /// struct NumberSection {
2134 /// std::vector<int>& _data;
2135 /// NumberSection(std::vector<int>& data) : _data(data) {}
2136 /// void operator()(const std::string& line) {
2137 /// std::istringstream ls(line);
2139 /// while (ls >> value) _data.push_back(value);
2145 /// reader.sectionLines("numbers", NumberSection(vec));
2147 template <typename Functor>
2148 SectionReader& sectionLines(const std::string& type, Functor functor) {
2149 LEMON_ASSERT(!type.empty(), "Type is empty.");
2150 LEMON_ASSERT(_sections.find(type) == _sections.end(),
2151 "Multiple reading of section.");
2152 _sections.insert(std::make_pair(type,
2153 new _reader_bits::LineSection<Functor>(functor)));
2158 /// \brief Add a section processor with stream oriented reading
2160 /// The first parameter is the type of the section, the second is
2161 /// a functor, which takes an \c std::istream& and an \c int&
2162 /// parameter, the latter regard to the line number of stream. The
2163 /// functor can read the input while the section go on, and the
2164 /// line number should be modified accordingly.
2165 template <typename Functor>
2166 SectionReader& sectionStream(const std::string& type, Functor functor) {
2167 LEMON_ASSERT(!type.empty(), "Type is empty.");
2168 LEMON_ASSERT(_sections.find(type) == _sections.end(),
2169 "Multiple reading of section.");
2170 _sections.insert(std::make_pair(type,
2171 new _reader_bits::StreamSection<Functor>(functor)));
2181 while(++line_num, std::getline(*_is, str)) {
2182 line.clear(); line.str(str);
2184 if (line >> std::ws >> c && c != '#') {
2192 bool readSuccess() {
2193 return static_cast<bool>(*_is);
2196 void skipSection() {
2198 while (readSuccess() && line >> c && c != '@') {
2207 /// \name Execution of the reader
2210 /// \brief Start the batch processing
2212 /// This function starts the batch processing.
2215 LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
2217 std::set<std::string> extra_sections;
2223 while (readSuccess()) {
2226 std::string section, caption;
2228 _reader_bits::readToken(line, section);
2229 _reader_bits::readToken(line, caption);
2232 throw DataFormatError("Extra character on the end of line");
2234 if (extra_sections.find(section) != extra_sections.end()) {
2235 std::ostringstream msg;
2236 msg << "Multiple occurence of section " << section;
2237 throw DataFormatError(msg.str().c_str());
2239 Sections::iterator it = _sections.find(section);
2240 if (it != _sections.end()) {
2241 extra_sections.insert(section);
2242 it->second->process(*_is, line_num);
2246 } catch (DataFormatError& error) {
2247 error.line(line_num);
2251 for (Sections::iterator it = _sections.begin();
2252 it != _sections.end(); ++it) {
2253 if (extra_sections.find(it->first) == extra_sections.end()) {
2254 std::ostringstream os;
2255 os << "Cannot find section: " << it->first;
2256 throw DataFormatError(os.str().c_str());
2265 /// \brief Return a \ref SectionReader class
2267 /// This function just returns a \ref SectionReader class.
2268 /// \relates SectionReader
2269 inline SectionReader sectionReader(std::istream& is) {
2270 SectionReader tmp(is);
2274 /// \brief Return a \ref SectionReader class
2276 /// This function just returns a \ref SectionReader class.
2277 /// \relates SectionReader
2278 inline SectionReader sectionReader(const std::string& fn) {
2279 SectionReader tmp(fn);
2283 /// \brief Return a \ref SectionReader class
2285 /// This function just returns a \ref SectionReader class.
2286 /// \relates SectionReader
2287 inline SectionReader sectionReader(const char* fn) {
2288 SectionReader tmp(fn);
2292 /// \ingroup lemon_io
2294 /// \brief Reader for the contents of the \ref lgf-format "LGF" file
2296 /// This class can be used to read the sections, the map names and
2297 /// the attributes from a file. Usually, the Lemon programs know
2298 /// that, which type of graph, which maps and which attributes
2299 /// should be read from a file, but in general tools (like glemon)
2300 /// the contents of an LGF file should be guessed somehow. This class
2301 /// reads the graph and stores the appropriate information for
2302 /// reading the graph.
2305 /// LgfContents contents("graph.lgf");
2308 /// // Does it contain any node section and arc section?
2309 /// if (contents.nodeSectionNum() == 0 || contents.arcSectionNum()) {
2310 /// std::cerr << "Failure, cannot find graph." << std::endl;
2313 /// std::cout << "The name of the default node section: "
2314 /// << contents.nodeSection(0) << std::endl;
2315 /// std::cout << "The number of the arc maps: "
2316 /// << contents.arcMaps(0).size() << std::endl;
2317 /// std::cout << "The name of second arc map: "
2318 /// << contents.arcMaps(0)[1] << std::endl;
2326 std::vector<std::string> _node_sections;
2327 std::vector<std::string> _edge_sections;
2328 std::vector<std::string> _attribute_sections;
2329 std::vector<std::string> _extra_sections;
2331 std::vector<bool> _arc_sections;
2333 std::vector<std::vector<std::string> > _node_maps;
2334 std::vector<std::vector<std::string> > _edge_maps;
2336 std::vector<std::vector<std::string> > _attributes;
2340 std::istringstream line;
2344 /// \brief Constructor
2346 /// Construct an \e LGF contents reader, which reads from the given
2348 LgfContents(std::istream& is)
2349 : _is(&is), local_is(false) {}
2351 /// \brief Constructor
2353 /// Construct an \e LGF contents reader, which reads from the given
2355 LgfContents(const std::string& fn)
2356 : _is(new std::ifstream(fn.c_str())), local_is(true) {}
2358 /// \brief Constructor
2360 /// Construct an \e LGF contents reader, which reads from the given
2362 LgfContents(const char* fn)
2363 : _is(new std::ifstream(fn)), local_is(true) {}
2365 /// \brief Destructor
2367 if (local_is) delete _is;
2372 LgfContents(const LgfContents&);
2373 LgfContents& operator=(const LgfContents&);
2378 /// \name Node sections
2381 /// \brief Gives back the number of node sections in the file.
2383 /// Gives back the number of node sections in the file.
2384 int nodeSectionNum() const {
2385 return _node_sections.size();
2388 /// \brief Returns the node section name at the given position.
2390 /// Returns the node section name at the given position.
2391 const std::string& nodeSection(int i) const {
2392 return _node_sections[i];
2395 /// \brief Gives back the node maps for the given section.
2397 /// Gives back the node maps for the given section.
2398 const std::vector<std::string>& nodeMapNames(int i) const {
2399 return _node_maps[i];
2404 /// \name Arc/Edge sections
2407 /// \brief Gives back the number of arc/edge sections in the file.
2409 /// Gives back the number of arc/edge sections in the file.
2410 /// \note It is synonym of \c edgeSectionNum().
2411 int arcSectionNum() const {
2412 return _edge_sections.size();
2415 /// \brief Returns the arc/edge section name at the given position.
2417 /// Returns the arc/edge section name at the given position.
2418 /// \note It is synonym of \c edgeSection().
2419 const std::string& arcSection(int i) const {
2420 return _edge_sections[i];
2423 /// \brief Gives back the arc/edge maps for the given section.
2425 /// Gives back the arc/edge maps for the given section.
2426 /// \note It is synonym of \c edgeMapNames().
2427 const std::vector<std::string>& arcMapNames(int i) const {
2428 return _edge_maps[i];
2436 /// \brief Gives back the number of arc/edge sections in the file.
2438 /// Gives back the number of arc/edge sections in the file.
2439 /// \note It is synonym of \c arcSectionNum().
2440 int edgeSectionNum() const {
2441 return _edge_sections.size();
2444 /// \brief Returns the section name at the given position.
2446 /// Returns the section name at the given position.
2447 /// \note It is synonym of \c arcSection().
2448 const std::string& edgeSection(int i) const {
2449 return _edge_sections[i];
2452 /// \brief Gives back the edge maps for the given section.
2454 /// Gives back the edge maps for the given section.
2455 /// \note It is synonym of \c arcMapNames().
2456 const std::vector<std::string>& edgeMapNames(int i) const {
2457 return _edge_maps[i];
2462 /// \name Attribute sections
2465 /// \brief Gives back the number of attribute sections in the file.
2467 /// Gives back the number of attribute sections in the file.
2468 int attributeSectionNum() const {
2469 return _attribute_sections.size();
2472 /// \brief Returns the attribute section name at the given position.
2474 /// Returns the attribute section name at the given position.
2475 const std::string& attributeSectionNames(int i) const {
2476 return _attribute_sections[i];
2479 /// \brief Gives back the attributes for the given section.
2481 /// Gives back the attributes for the given section.
2482 const std::vector<std::string>& attributes(int i) const {
2483 return _attributes[i];
2488 /// \name Extra sections
2491 /// \brief Gives back the number of extra sections in the file.
2493 /// Gives back the number of extra sections in the file.
2494 int extraSectionNum() const {
2495 return _extra_sections.size();
2498 /// \brief Returns the extra section type at the given position.
2500 /// Returns the section type at the given position.
2501 const std::string& extraSection(int i) const {
2502 return _extra_sections[i];
2511 while(++line_num, std::getline(*_is, str)) {
2512 line.clear(); line.str(str);
2514 if (line >> std::ws >> c && c != '#') {
2522 bool readSuccess() {
2523 return static_cast<bool>(*_is);
2526 void skipSection() {
2528 while (readSuccess() && line >> c && c != '@') {
2534 void readMaps(std::vector<std::string>& maps) {
2536 if (!readLine() || !(line >> c) || c == '@') {
2537 if (readSuccess() && line) line.putback(c);
2542 while (_reader_bits::readToken(line, map)) {
2543 maps.push_back(map);
2547 void readAttributes(std::vector<std::string>& attrs) {
2550 while (readSuccess() && line >> c && c != '@') {
2553 _reader_bits::readToken(line, attr);
2554 attrs.push_back(attr);
2562 /// \name Execution of the contents reader
2565 /// \brief Starts the reading
2567 /// This function starts the reading.
2573 while (readSuccess()) {
2578 std::string section, caption;
2579 _reader_bits::readToken(line, section);
2580 _reader_bits::readToken(line, caption);
2582 if (section == "nodes") {
2583 _node_sections.push_back(caption);
2584 _node_maps.push_back(std::vector<std::string>());
2585 readMaps(_node_maps.back());
2586 readLine(); skipSection();
2587 } else if (section == "arcs" || section == "edges") {
2588 _edge_sections.push_back(caption);
2589 _arc_sections.push_back(section == "arcs");
2590 _edge_maps.push_back(std::vector<std::string>());
2591 readMaps(_edge_maps.back());
2592 readLine(); skipSection();
2593 } else if (section == "attributes") {
2594 _attribute_sections.push_back(caption);
2595 _attributes.push_back(std::vector<std::string>());
2596 readAttributes(_attributes.back());
2598 _extra_sections.push_back(section);
2599 readLine(); skipSection();