Use only a single (cached) variable to hold the version number.
1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2008
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
21 ///\brief \ref lgf-format "LEMON Graph Format" reader.
24 #ifndef LEMON_LGF_READER_H
25 #define LEMON_LGF_READER_H
34 #include <lemon/assert.h>
35 #include <lemon/core.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 inline bool isWhiteSpace(char c) {
199 return c == ' ' || c == '\t' || c == '\v' ||
200 c == '\n' || c == '\r' || c == '\f';
203 inline bool isOct(char c) {
204 return '0' <= c && c <='7';
207 inline int valueOct(char c) {
208 LEMON_ASSERT(isOct(c), "The character is not octal.");
212 inline bool isHex(char c) {
213 return ('0' <= c && c <= '9') ||
214 ('a' <= c && c <= 'z') ||
215 ('A' <= c && c <= 'Z');
218 inline 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 inline bool isIdentifierFirstChar(char c) {
226 return ('a' <= c && c <= 'z') ||
227 ('A' <= c && c <= 'Z') || c == '_';
230 inline bool isIdentifierChar(char c) {
231 return isIdentifierFirstChar(c) ||
232 ('0' <= c && c <= '9');
235 inline 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 inline 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.
448 /// It is impossible to read this in
449 /// a single pass, because the arcs are not constructed when the node
451 template <typename _Digraph>
452 class DigraphReader {
455 typedef _Digraph Digraph;
456 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
466 std::string _nodes_caption;
467 std::string _arcs_caption;
468 std::string _attributes_caption;
470 typedef std::map<std::string, Node> NodeIndex;
471 NodeIndex _node_index;
472 typedef std::map<std::string, Arc> ArcIndex;
475 typedef std::vector<std::pair<std::string,
476 _reader_bits::MapStorageBase<Node>*> > NodeMaps;
479 typedef std::vector<std::pair<std::string,
480 _reader_bits::MapStorageBase<Arc>*> >ArcMaps;
483 typedef std::multimap<std::string, _reader_bits::ValueStorageBase*>
485 Attributes _attributes;
494 std::istringstream line;
498 /// \brief Constructor
500 /// Construct a directed graph reader, which reads from the given
502 DigraphReader(std::istream& is, Digraph& digraph)
503 : _is(&is), local_is(false), _digraph(digraph),
504 _use_nodes(false), _use_arcs(false),
505 _skip_nodes(false), _skip_arcs(false) {}
507 /// \brief Constructor
509 /// Construct a directed graph reader, which reads from the given
511 DigraphReader(const std::string& fn, Digraph& digraph)
512 : _is(new std::ifstream(fn.c_str())), local_is(true), _digraph(digraph),
513 _use_nodes(false), _use_arcs(false),
514 _skip_nodes(false), _skip_arcs(false) {}
516 /// \brief Constructor
518 /// Construct a directed graph reader, which reads from the given
520 DigraphReader(const char* fn, Digraph& digraph)
521 : _is(new std::ifstream(fn)), local_is(true), _digraph(digraph),
522 _use_nodes(false), _use_arcs(false),
523 _skip_nodes(false), _skip_arcs(false) {}
525 /// \brief Destructor
527 for (typename NodeMaps::iterator it = _node_maps.begin();
528 it != _node_maps.end(); ++it) {
532 for (typename ArcMaps::iterator it = _arc_maps.begin();
533 it != _arc_maps.end(); ++it) {
537 for (typename Attributes::iterator it = _attributes.begin();
538 it != _attributes.end(); ++it) {
550 friend DigraphReader<Digraph> digraphReader<>(std::istream& is,
552 friend DigraphReader<Digraph> digraphReader<>(const std::string& fn,
554 friend DigraphReader<Digraph> digraphReader<>(const char *fn,
557 DigraphReader(DigraphReader& other)
558 : _is(other._is), local_is(other.local_is), _digraph(other._digraph),
559 _use_nodes(other._use_nodes), _use_arcs(other._use_arcs),
560 _skip_nodes(other._skip_nodes), _skip_arcs(other._skip_arcs) {
563 other.local_is = false;
565 _node_index.swap(other._node_index);
566 _arc_index.swap(other._arc_index);
568 _node_maps.swap(other._node_maps);
569 _arc_maps.swap(other._arc_maps);
570 _attributes.swap(other._attributes);
572 _nodes_caption = other._nodes_caption;
573 _arcs_caption = other._arcs_caption;
574 _attributes_caption = other._attributes_caption;
578 DigraphReader& operator=(const DigraphReader&);
582 /// \name Reading rules
585 /// \brief Node map reading rule
587 /// Add a node map reading rule to the reader.
588 template <typename Map>
589 DigraphReader& nodeMap(const std::string& caption, Map& map) {
590 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
591 _reader_bits::MapStorageBase<Node>* storage =
592 new _reader_bits::MapStorage<Node, Map>(map);
593 _node_maps.push_back(std::make_pair(caption, storage));
597 /// \brief Node map reading rule
599 /// Add a node map reading rule with specialized converter to the
601 template <typename Map, typename Converter>
602 DigraphReader& nodeMap(const std::string& caption, Map& map,
603 const Converter& converter = Converter()) {
604 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
605 _reader_bits::MapStorageBase<Node>* storage =
606 new _reader_bits::MapStorage<Node, Map, Converter>(map, converter);
607 _node_maps.push_back(std::make_pair(caption, storage));
611 /// \brief Arc map reading rule
613 /// Add an arc map reading rule to the reader.
614 template <typename Map>
615 DigraphReader& arcMap(const std::string& caption, Map& map) {
616 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
617 _reader_bits::MapStorageBase<Arc>* storage =
618 new _reader_bits::MapStorage<Arc, Map>(map);
619 _arc_maps.push_back(std::make_pair(caption, storage));
623 /// \brief Arc map reading rule
625 /// Add an arc map reading rule with specialized converter to the
627 template <typename Map, typename Converter>
628 DigraphReader& arcMap(const std::string& caption, Map& map,
629 const Converter& converter = Converter()) {
630 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
631 _reader_bits::MapStorageBase<Arc>* storage =
632 new _reader_bits::MapStorage<Arc, Map, Converter>(map, converter);
633 _arc_maps.push_back(std::make_pair(caption, storage));
637 /// \brief Attribute reading rule
639 /// Add an attribute reading rule to the reader.
640 template <typename Value>
641 DigraphReader& attribute(const std::string& caption, Value& value) {
642 _reader_bits::ValueStorageBase* storage =
643 new _reader_bits::ValueStorage<Value>(value);
644 _attributes.insert(std::make_pair(caption, storage));
648 /// \brief Attribute reading rule
650 /// Add an attribute reading rule with specialized converter to the
652 template <typename Value, typename Converter>
653 DigraphReader& attribute(const std::string& caption, Value& value,
654 const Converter& converter = Converter()) {
655 _reader_bits::ValueStorageBase* storage =
656 new _reader_bits::ValueStorage<Value, Converter>(value, converter);
657 _attributes.insert(std::make_pair(caption, storage));
661 /// \brief Node reading rule
663 /// Add a node reading rule to reader.
664 DigraphReader& node(const std::string& caption, Node& node) {
665 typedef _reader_bits::MapLookUpConverter<Node> Converter;
666 Converter converter(_node_index);
667 _reader_bits::ValueStorageBase* storage =
668 new _reader_bits::ValueStorage<Node, Converter>(node, converter);
669 _attributes.insert(std::make_pair(caption, storage));
673 /// \brief Arc reading rule
675 /// Add an arc reading rule to reader.
676 DigraphReader& arc(const std::string& caption, Arc& arc) {
677 typedef _reader_bits::MapLookUpConverter<Arc> Converter;
678 Converter converter(_arc_index);
679 _reader_bits::ValueStorageBase* storage =
680 new _reader_bits::ValueStorage<Arc, Converter>(arc, converter);
681 _attributes.insert(std::make_pair(caption, storage));
687 /// \name Select section by name
690 /// \brief Set \c \@nodes section to be read
692 /// Set \c \@nodes section to be read
693 DigraphReader& nodes(const std::string& caption) {
694 _nodes_caption = caption;
698 /// \brief Set \c \@arcs section to be read
700 /// Set \c \@arcs section to be read
701 DigraphReader& arcs(const std::string& caption) {
702 _arcs_caption = caption;
706 /// \brief Set \c \@attributes section to be read
708 /// Set \c \@attributes section to be read
709 DigraphReader& attributes(const std::string& caption) {
710 _attributes_caption = caption;
716 /// \name Using previously constructed node or arc set
719 /// \brief Use previously constructed node set
721 /// Use previously constructed node set, and specify the node
723 template <typename Map>
724 DigraphReader& useNodes(const Map& map) {
725 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
726 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
728 _writer_bits::DefaultConverter<typename Map::Value> converter;
729 for (NodeIt n(_digraph); n != INVALID; ++n) {
730 _node_index.insert(std::make_pair(converter(map[n]), n));
735 /// \brief Use previously constructed node set
737 /// Use previously constructed node set, and specify the node
738 /// label map and a functor which converts the label map values to
740 template <typename Map, typename Converter>
741 DigraphReader& useNodes(const Map& map,
742 const Converter& converter = Converter()) {
743 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
744 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
746 for (NodeIt n(_digraph); n != INVALID; ++n) {
747 _node_index.insert(std::make_pair(converter(map[n]), n));
752 /// \brief Use previously constructed arc set
754 /// Use previously constructed arc set, and specify the arc
756 template <typename Map>
757 DigraphReader& useArcs(const Map& map) {
758 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
759 LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member");
761 _writer_bits::DefaultConverter<typename Map::Value> converter;
762 for (ArcIt a(_digraph); a != INVALID; ++a) {
763 _arc_index.insert(std::make_pair(converter(map[a]), a));
768 /// \brief Use previously constructed arc set
770 /// Use previously constructed arc set, and specify the arc
771 /// label map and a functor which converts the label map values to
773 template <typename Map, typename Converter>
774 DigraphReader& useArcs(const Map& map,
775 const Converter& converter = Converter()) {
776 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
777 LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member");
779 for (ArcIt a(_digraph); a != INVALID; ++a) {
780 _arc_index.insert(std::make_pair(converter(map[a]), a));
785 /// \brief Skips the reading of node section
787 /// Omit the reading of the node section. This implies that each node
788 /// map reading rule will be abandoned, and the nodes of the graph
789 /// will not be constructed, which usually cause that the arc set
790 /// could not be read due to lack of node name resolving.
791 /// Therefore \c skipArcs() function should also be used, or
792 /// \c useNodes() should be used to specify the 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 abandoned, 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 /// \brief Return a \ref DigraphReader class
1180 /// This function just returns a \ref DigraphReader class.
1181 /// \relates DigraphReader
1182 template <typename Digraph>
1183 DigraphReader<Digraph> digraphReader(std::istream& is, Digraph& digraph) {
1184 DigraphReader<Digraph> tmp(is, digraph);
1188 /// \brief Return a \ref DigraphReader class
1190 /// This function just returns a \ref DigraphReader class.
1191 /// \relates DigraphReader
1192 template <typename Digraph>
1193 DigraphReader<Digraph> digraphReader(const std::string& fn,
1195 DigraphReader<Digraph> tmp(fn, digraph);
1199 /// \brief Return a \ref DigraphReader class
1201 /// This function just returns a \ref DigraphReader class.
1202 /// \relates DigraphReader
1203 template <typename Digraph>
1204 DigraphReader<Digraph> digraphReader(const char* fn, Digraph& digraph) {
1205 DigraphReader<Digraph> tmp(fn, digraph);
1209 template <typename Graph>
1212 template <typename Graph>
1213 GraphReader<Graph> graphReader(std::istream& is, Graph& graph);
1215 template <typename Graph>
1216 GraphReader<Graph> graphReader(const std::string& fn, Graph& graph);
1218 template <typename Graph>
1219 GraphReader<Graph> graphReader(const char *fn, Graph& graph);
1221 /// \ingroup lemon_io
1223 /// \brief \ref lgf-format "LGF" reader for undirected graphs
1225 /// This utility reads an \ref lgf-format "LGF" file.
1227 /// It can be used almost the same way as \c DigraphReader.
1228 /// The only difference is that this class can handle edges and
1229 /// edge maps as well as arcs and arc maps.
1231 /// The columns in the \c \@edges (or \c \@arcs) section are the
1232 /// edge maps. However, if there are two maps with the same name
1233 /// prefixed with \c '+' and \c '-', then these can be read into an
1234 /// arc map. Similarly, an attribute can be read into an arc, if
1235 /// it's value is an edge label prefixed with \c '+' or \c '-'.
1236 template <typename _Graph>
1240 typedef _Graph Graph;
1241 TEMPLATE_GRAPH_TYPEDEFS(Graph);
1250 std::string _nodes_caption;
1251 std::string _edges_caption;
1252 std::string _attributes_caption;
1254 typedef std::map<std::string, Node> NodeIndex;
1255 NodeIndex _node_index;
1256 typedef std::map<std::string, Edge> EdgeIndex;
1257 EdgeIndex _edge_index;
1259 typedef std::vector<std::pair<std::string,
1260 _reader_bits::MapStorageBase<Node>*> > NodeMaps;
1261 NodeMaps _node_maps;
1263 typedef std::vector<std::pair<std::string,
1264 _reader_bits::MapStorageBase<Edge>*> > EdgeMaps;
1265 EdgeMaps _edge_maps;
1267 typedef std::multimap<std::string, _reader_bits::ValueStorageBase*>
1269 Attributes _attributes;
1278 std::istringstream line;
1282 /// \brief Constructor
1284 /// Construct an undirected graph reader, which reads from the given
1286 GraphReader(std::istream& is, Graph& graph)
1287 : _is(&is), local_is(false), _graph(graph),
1288 _use_nodes(false), _use_edges(false),
1289 _skip_nodes(false), _skip_edges(false) {}
1291 /// \brief Constructor
1293 /// Construct an undirected graph reader, which reads from the given
1295 GraphReader(const std::string& fn, Graph& graph)
1296 : _is(new std::ifstream(fn.c_str())), local_is(true), _graph(graph),
1297 _use_nodes(false), _use_edges(false),
1298 _skip_nodes(false), _skip_edges(false) {}
1300 /// \brief Constructor
1302 /// Construct an undirected graph reader, which reads from the given
1304 GraphReader(const char* fn, Graph& graph)
1305 : _is(new std::ifstream(fn)), local_is(true), _graph(graph),
1306 _use_nodes(false), _use_edges(false),
1307 _skip_nodes(false), _skip_edges(false) {}
1309 /// \brief Destructor
1311 for (typename NodeMaps::iterator it = _node_maps.begin();
1312 it != _node_maps.end(); ++it) {
1316 for (typename EdgeMaps::iterator it = _edge_maps.begin();
1317 it != _edge_maps.end(); ++it) {
1321 for (typename Attributes::iterator it = _attributes.begin();
1322 it != _attributes.end(); ++it) {
1333 friend GraphReader<Graph> graphReader<>(std::istream& is, Graph& graph);
1334 friend GraphReader<Graph> graphReader<>(const std::string& fn,
1336 friend GraphReader<Graph> graphReader<>(const char *fn, Graph& graph);
1338 GraphReader(GraphReader& other)
1339 : _is(other._is), local_is(other.local_is), _graph(other._graph),
1340 _use_nodes(other._use_nodes), _use_edges(other._use_edges),
1341 _skip_nodes(other._skip_nodes), _skip_edges(other._skip_edges) {
1344 other.local_is = false;
1346 _node_index.swap(other._node_index);
1347 _edge_index.swap(other._edge_index);
1349 _node_maps.swap(other._node_maps);
1350 _edge_maps.swap(other._edge_maps);
1351 _attributes.swap(other._attributes);
1353 _nodes_caption = other._nodes_caption;
1354 _edges_caption = other._edges_caption;
1355 _attributes_caption = other._attributes_caption;
1359 GraphReader& operator=(const GraphReader&);
1363 /// \name Reading rules
1366 /// \brief Node map reading rule
1368 /// Add a node map reading rule to the reader.
1369 template <typename Map>
1370 GraphReader& nodeMap(const std::string& caption, Map& map) {
1371 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
1372 _reader_bits::MapStorageBase<Node>* storage =
1373 new _reader_bits::MapStorage<Node, Map>(map);
1374 _node_maps.push_back(std::make_pair(caption, storage));
1378 /// \brief Node map reading rule
1380 /// Add a node map reading rule with specialized converter to the
1382 template <typename Map, typename Converter>
1383 GraphReader& nodeMap(const std::string& caption, Map& map,
1384 const Converter& converter = Converter()) {
1385 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
1386 _reader_bits::MapStorageBase<Node>* storage =
1387 new _reader_bits::MapStorage<Node, Map, Converter>(map, converter);
1388 _node_maps.push_back(std::make_pair(caption, storage));
1392 /// \brief Edge map reading rule
1394 /// Add an edge map reading rule to the reader.
1395 template <typename Map>
1396 GraphReader& edgeMap(const std::string& caption, Map& map) {
1397 checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>();
1398 _reader_bits::MapStorageBase<Edge>* storage =
1399 new _reader_bits::MapStorage<Edge, Map>(map);
1400 _edge_maps.push_back(std::make_pair(caption, storage));
1404 /// \brief Edge map reading rule
1406 /// Add an edge map reading rule with specialized converter to the
1408 template <typename Map, typename Converter>
1409 GraphReader& edgeMap(const std::string& caption, Map& map,
1410 const Converter& converter = Converter()) {
1411 checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>();
1412 _reader_bits::MapStorageBase<Edge>* storage =
1413 new _reader_bits::MapStorage<Edge, Map, Converter>(map, converter);
1414 _edge_maps.push_back(std::make_pair(caption, storage));
1418 /// \brief Arc map reading rule
1420 /// Add an arc map reading rule to the reader.
1421 template <typename Map>
1422 GraphReader& arcMap(const std::string& caption, Map& map) {
1423 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
1424 _reader_bits::MapStorageBase<Edge>* forward_storage =
1425 new _reader_bits::GraphArcMapStorage<Graph, true, Map>(_graph, map);
1426 _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
1427 _reader_bits::MapStorageBase<Edge>* backward_storage =
1428 new _reader_bits::GraphArcMapStorage<Graph, false, Map>(_graph, map);
1429 _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
1433 /// \brief Arc map reading rule
1435 /// Add an arc map reading rule with specialized converter to the
1437 template <typename Map, typename Converter>
1438 GraphReader& arcMap(const std::string& caption, Map& map,
1439 const Converter& converter = Converter()) {
1440 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
1441 _reader_bits::MapStorageBase<Edge>* forward_storage =
1442 new _reader_bits::GraphArcMapStorage<Graph, true, Map, Converter>
1443 (_graph, map, converter);
1444 _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
1445 _reader_bits::MapStorageBase<Edge>* backward_storage =
1446 new _reader_bits::GraphArcMapStorage<Graph, false, Map, Converter>
1447 (_graph, map, converter);
1448 _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
1452 /// \brief Attribute reading rule
1454 /// Add an attribute reading rule to the reader.
1455 template <typename Value>
1456 GraphReader& attribute(const std::string& caption, Value& value) {
1457 _reader_bits::ValueStorageBase* storage =
1458 new _reader_bits::ValueStorage<Value>(value);
1459 _attributes.insert(std::make_pair(caption, storage));
1463 /// \brief Attribute reading rule
1465 /// Add an attribute reading rule with specialized converter to the
1467 template <typename Value, typename Converter>
1468 GraphReader& attribute(const std::string& caption, Value& value,
1469 const Converter& converter = Converter()) {
1470 _reader_bits::ValueStorageBase* storage =
1471 new _reader_bits::ValueStorage<Value, Converter>(value, converter);
1472 _attributes.insert(std::make_pair(caption, storage));
1476 /// \brief Node reading rule
1478 /// Add a node reading rule to reader.
1479 GraphReader& node(const std::string& caption, Node& node) {
1480 typedef _reader_bits::MapLookUpConverter<Node> Converter;
1481 Converter converter(_node_index);
1482 _reader_bits::ValueStorageBase* storage =
1483 new _reader_bits::ValueStorage<Node, Converter>(node, converter);
1484 _attributes.insert(std::make_pair(caption, storage));
1488 /// \brief Edge reading rule
1490 /// Add an edge reading rule to reader.
1491 GraphReader& edge(const std::string& caption, Edge& edge) {
1492 typedef _reader_bits::MapLookUpConverter<Edge> Converter;
1493 Converter converter(_edge_index);
1494 _reader_bits::ValueStorageBase* storage =
1495 new _reader_bits::ValueStorage<Edge, Converter>(edge, converter);
1496 _attributes.insert(std::make_pair(caption, storage));
1500 /// \brief Arc reading rule
1502 /// Add an arc reading rule to reader.
1503 GraphReader& arc(const std::string& caption, Arc& arc) {
1504 typedef _reader_bits::GraphArcLookUpConverter<Graph> Converter;
1505 Converter converter(_graph, _edge_index);
1506 _reader_bits::ValueStorageBase* storage =
1507 new _reader_bits::ValueStorage<Arc, Converter>(arc, converter);
1508 _attributes.insert(std::make_pair(caption, storage));
1514 /// \name Select section by name
1517 /// \brief Set \c \@nodes section to be read
1519 /// Set \c \@nodes section to be read.
1520 GraphReader& nodes(const std::string& caption) {
1521 _nodes_caption = caption;
1525 /// \brief Set \c \@edges section to be read
1527 /// Set \c \@edges section to be read.
1528 GraphReader& edges(const std::string& caption) {
1529 _edges_caption = caption;
1533 /// \brief Set \c \@attributes section to be read
1535 /// Set \c \@attributes section to be read.
1536 GraphReader& attributes(const std::string& caption) {
1537 _attributes_caption = caption;
1543 /// \name Using previously constructed node or edge set
1546 /// \brief Use previously constructed node set
1548 /// Use previously constructed node set, and specify the node
1550 template <typename Map>
1551 GraphReader& useNodes(const Map& map) {
1552 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
1553 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
1555 _writer_bits::DefaultConverter<typename Map::Value> converter;
1556 for (NodeIt n(_graph); n != INVALID; ++n) {
1557 _node_index.insert(std::make_pair(converter(map[n]), n));
1562 /// \brief Use previously constructed node set
1564 /// Use previously constructed node set, and specify the node
1565 /// label map and a functor which converts the label map values to
1567 template <typename Map, typename Converter>
1568 GraphReader& useNodes(const Map& map,
1569 const Converter& converter = Converter()) {
1570 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
1571 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
1573 for (NodeIt n(_graph); n != INVALID; ++n) {
1574 _node_index.insert(std::make_pair(converter(map[n]), n));
1579 /// \brief Use previously constructed edge set
1581 /// Use previously constructed edge set, and specify the edge
1583 template <typename Map>
1584 GraphReader& useEdges(const Map& map) {
1585 checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
1586 LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member");
1588 _writer_bits::DefaultConverter<typename Map::Value> converter;
1589 for (EdgeIt a(_graph); a != INVALID; ++a) {
1590 _edge_index.insert(std::make_pair(converter(map[a]), a));
1595 /// \brief Use previously constructed edge set
1597 /// Use previously constructed edge set, and specify the edge
1598 /// label map and a functor which converts the label map values to
1600 template <typename Map, typename Converter>
1601 GraphReader& useEdges(const Map& map,
1602 const Converter& converter = Converter()) {
1603 checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
1604 LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member");
1606 for (EdgeIt a(_graph); a != INVALID; ++a) {
1607 _edge_index.insert(std::make_pair(converter(map[a]), a));
1612 /// \brief Skip the reading of node section
1614 /// Omit the reading of the node section. This implies that each node
1615 /// map reading rule will be abandoned, and the nodes of the graph
1616 /// will not be constructed, which usually cause that the edge set
1617 /// could not be read due to lack of node name
1618 /// could not be read due to lack of node name resolving.
1619 /// Therefore \c skipEdges() function should also be used, or
1620 /// \c useNodes() should be used to specify the label of the nodes.
1621 GraphReader& skipNodes() {
1622 LEMON_ASSERT(!_skip_nodes, "Skip nodes already set");
1627 /// \brief Skip the reading of edge section
1629 /// Omit the reading of the edge section. This implies that each edge
1630 /// map reading rule will be abandoned, and the edges of the graph
1631 /// will not be constructed.
1632 GraphReader& skipEdges() {
1633 LEMON_ASSERT(!_skip_edges, "Skip edges already set");
1644 while(++line_num, std::getline(*_is, str)) {
1645 line.clear(); line.str(str);
1647 if (line >> std::ws >> c && c != '#') {
1655 bool readSuccess() {
1656 return static_cast<bool>(*_is);
1659 void skipSection() {
1661 while (readSuccess() && line >> c && c != '@') {
1669 std::vector<int> map_index(_node_maps.size());
1670 int map_num, label_index;
1673 if (!readLine() || !(line >> c) || c == '@') {
1674 if (readSuccess() && line) line.putback(c);
1675 if (!_node_maps.empty())
1676 throw DataFormatError("Cannot find map names");
1682 std::map<std::string, int> maps;
1686 while (_reader_bits::readToken(line, map)) {
1687 if (maps.find(map) != maps.end()) {
1688 std::ostringstream msg;
1689 msg << "Multiple occurence of node map: " << map;
1690 throw DataFormatError(msg.str().c_str());
1692 maps.insert(std::make_pair(map, index));
1696 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
1697 std::map<std::string, int>::iterator jt =
1698 maps.find(_node_maps[i].first);
1699 if (jt == maps.end()) {
1700 std::ostringstream msg;
1701 msg << "Map not found in file: " << _node_maps[i].first;
1702 throw DataFormatError(msg.str().c_str());
1704 map_index[i] = jt->second;
1708 std::map<std::string, int>::iterator jt = maps.find("label");
1709 if (jt != maps.end()) {
1710 label_index = jt->second;
1715 map_num = maps.size();
1718 while (readLine() && line >> c && c != '@') {
1721 std::vector<std::string> tokens(map_num);
1722 for (int i = 0; i < map_num; ++i) {
1723 if (!_reader_bits::readToken(line, tokens[i])) {
1724 std::ostringstream msg;
1725 msg << "Column not found (" << i + 1 << ")";
1726 throw DataFormatError(msg.str().c_str());
1729 if (line >> std::ws >> c)
1730 throw DataFormatError("Extra character on the end of line");
1734 n = _graph.addNode();
1735 if (label_index != -1)
1736 _node_index.insert(std::make_pair(tokens[label_index], n));
1738 if (label_index == -1)
1739 throw DataFormatError("Label map not found in file");
1740 typename std::map<std::string, Node>::iterator it =
1741 _node_index.find(tokens[label_index]);
1742 if (it == _node_index.end()) {
1743 std::ostringstream msg;
1744 msg << "Node with label not found: " << tokens[label_index];
1745 throw DataFormatError(msg.str().c_str());
1750 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
1751 _node_maps[i].second->set(n, tokens[map_index[i]]);
1755 if (readSuccess()) {
1762 std::vector<int> map_index(_edge_maps.size());
1763 int map_num, label_index;
1766 if (!readLine() || !(line >> c) || c == '@') {
1767 if (readSuccess() && line) line.putback(c);
1768 if (!_edge_maps.empty())
1769 throw DataFormatError("Cannot find map names");
1775 std::map<std::string, int> maps;
1779 while (_reader_bits::readToken(line, map)) {
1780 if (maps.find(map) != maps.end()) {
1781 std::ostringstream msg;
1782 msg << "Multiple occurence of edge map: " << map;
1783 throw DataFormatError(msg.str().c_str());
1785 maps.insert(std::make_pair(map, index));
1789 for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) {
1790 std::map<std::string, int>::iterator jt =
1791 maps.find(_edge_maps[i].first);
1792 if (jt == maps.end()) {
1793 std::ostringstream msg;
1794 msg << "Map not found in file: " << _edge_maps[i].first;
1795 throw DataFormatError(msg.str().c_str());
1797 map_index[i] = jt->second;
1801 std::map<std::string, int>::iterator jt = maps.find("label");
1802 if (jt != maps.end()) {
1803 label_index = jt->second;
1808 map_num = maps.size();
1811 while (readLine() && line >> c && c != '@') {
1814 std::string source_token;
1815 std::string target_token;
1817 if (!_reader_bits::readToken(line, source_token))
1818 throw DataFormatError("Node u not found");
1820 if (!_reader_bits::readToken(line, target_token))
1821 throw DataFormatError("Node v not found");
1823 std::vector<std::string> tokens(map_num);
1824 for (int i = 0; i < map_num; ++i) {
1825 if (!_reader_bits::readToken(line, tokens[i])) {
1826 std::ostringstream msg;
1827 msg << "Column not found (" << i + 1 << ")";
1828 throw DataFormatError(msg.str().c_str());
1831 if (line >> std::ws >> c)
1832 throw DataFormatError("Extra character on the end of line");
1837 typename NodeIndex::iterator it;
1839 it = _node_index.find(source_token);
1840 if (it == _node_index.end()) {
1841 std::ostringstream msg;
1842 msg << "Item not found: " << source_token;
1843 throw DataFormatError(msg.str().c_str());
1845 Node source = it->second;
1847 it = _node_index.find(target_token);
1848 if (it == _node_index.end()) {
1849 std::ostringstream msg;
1850 msg << "Item not found: " << target_token;
1851 throw DataFormatError(msg.str().c_str());
1853 Node target = it->second;
1855 e = _graph.addEdge(source, target);
1856 if (label_index != -1)
1857 _edge_index.insert(std::make_pair(tokens[label_index], e));
1859 if (label_index == -1)
1860 throw DataFormatError("Label map not found in file");
1861 typename std::map<std::string, Edge>::iterator it =
1862 _edge_index.find(tokens[label_index]);
1863 if (it == _edge_index.end()) {
1864 std::ostringstream msg;
1865 msg << "Edge with label not found: " << tokens[label_index];
1866 throw DataFormatError(msg.str().c_str());
1871 for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) {
1872 _edge_maps[i].second->set(e, tokens[map_index[i]]);
1876 if (readSuccess()) {
1881 void readAttributes() {
1883 std::set<std::string> read_attr;
1886 while (readLine() && line >> c && c != '@') {
1889 std::string attr, token;
1890 if (!_reader_bits::readToken(line, attr))
1891 throw DataFormatError("Attribute name not found");
1892 if (!_reader_bits::readToken(line, token))
1893 throw DataFormatError("Attribute value not found");
1895 throw DataFormatError("Extra character on the end of line");
1898 std::set<std::string>::iterator it = read_attr.find(attr);
1899 if (it != read_attr.end()) {
1900 std::ostringstream msg;
1901 msg << "Multiple occurence of attribute " << attr;
1902 throw DataFormatError(msg.str().c_str());
1904 read_attr.insert(attr);
1908 typename Attributes::iterator it = _attributes.lower_bound(attr);
1909 while (it != _attributes.end() && it->first == attr) {
1910 it->second->set(token);
1916 if (readSuccess()) {
1919 for (typename Attributes::iterator it = _attributes.begin();
1920 it != _attributes.end(); ++it) {
1921 if (read_attr.find(it->first) == read_attr.end()) {
1922 std::ostringstream msg;
1923 msg << "Attribute not found in file: " << it->first;
1924 throw DataFormatError(msg.str().c_str());
1931 /// \name Execution of the reader
1934 /// \brief Start the batch processing
1936 /// This function starts the batch processing
1939 LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
1941 bool nodes_done = _skip_nodes;
1942 bool edges_done = _skip_edges;
1943 bool attributes_done = false;
1949 while (readSuccess()) {
1952 std::string section, caption;
1954 _reader_bits::readToken(line, section);
1955 _reader_bits::readToken(line, caption);
1958 throw DataFormatError("Extra character on the end of line");
1960 if (section == "nodes" && !nodes_done) {
1961 if (_nodes_caption.empty() || _nodes_caption == caption) {
1965 } else if ((section == "edges" || section == "arcs") &&
1967 if (_edges_caption.empty() || _edges_caption == caption) {
1971 } else if (section == "attributes" && !attributes_done) {
1972 if (_attributes_caption.empty() || _attributes_caption == caption) {
1974 attributes_done = true;
1980 } catch (DataFormatError& error) {
1981 error.line(line_num);
1987 throw DataFormatError("Section @nodes not found");
1991 throw DataFormatError("Section @edges not found");
1994 if (!attributes_done && !_attributes.empty()) {
1995 throw DataFormatError("Section @attributes not found");
2004 /// \brief Return a \ref GraphReader class
2006 /// This function just returns a \ref GraphReader class.
2007 /// \relates GraphReader
2008 template <typename Graph>
2009 GraphReader<Graph> graphReader(std::istream& is, Graph& graph) {
2010 GraphReader<Graph> tmp(is, graph);
2014 /// \brief Return a \ref GraphReader class
2016 /// This function just returns a \ref GraphReader class.
2017 /// \relates GraphReader
2018 template <typename Graph>
2019 GraphReader<Graph> graphReader(const std::string& fn,
2021 GraphReader<Graph> tmp(fn, graph);
2025 /// \brief Return a \ref GraphReader class
2027 /// This function just returns a \ref GraphReader class.
2028 /// \relates GraphReader
2029 template <typename Graph>
2030 GraphReader<Graph> graphReader(const char* fn, Graph& graph) {
2031 GraphReader<Graph> tmp(fn, graph);
2035 class SectionReader;
2037 SectionReader sectionReader(std::istream& is);
2038 SectionReader sectionReader(const std::string& fn);
2039 SectionReader sectionReader(const char* fn);
2041 /// \ingroup lemon_io
2043 /// \brief Section reader class
2045 /// In the \ref lgf-format "LGF" file extra sections can be placed,
2046 /// which contain any data in arbitrary format. Such sections can be
2047 /// read with this class. A reading rule can be added to the class
2048 /// with two different functions. With the \c sectionLines() function a
2049 /// functor can process the section line-by-line, while with the \c
2050 /// sectionStream() member the section can be read from an input
2052 class SectionReader {
2058 typedef std::map<std::string, _reader_bits::Section*> Sections;
2062 std::istringstream line;
2066 /// \brief Constructor
2068 /// Construct a section reader, which reads from the given input
2070 SectionReader(std::istream& is)
2071 : _is(&is), local_is(false) {}
2073 /// \brief Constructor
2075 /// Construct a section reader, which reads from the given file.
2076 SectionReader(const std::string& fn)
2077 : _is(new std::ifstream(fn.c_str())), local_is(true) {}
2079 /// \brief Constructor
2081 /// Construct a section reader, which reads from the given file.
2082 SectionReader(const char* fn)
2083 : _is(new std::ifstream(fn)), local_is(true) {}
2085 /// \brief Destructor
2087 for (Sections::iterator it = _sections.begin();
2088 it != _sections.end(); ++it) {
2100 friend SectionReader sectionReader(std::istream& is);
2101 friend SectionReader sectionReader(const std::string& fn);
2102 friend SectionReader sectionReader(const char* fn);
2104 SectionReader(SectionReader& other)
2105 : _is(other._is), local_is(other.local_is) {
2108 other.local_is = false;
2110 _sections.swap(other._sections);
2113 SectionReader& operator=(const SectionReader&);
2117 /// \name Section readers
2120 /// \brief Add a section processor with line oriented reading
2122 /// The first parameter is the type descriptor of the section, the
2123 /// second is a functor, which takes just one \c std::string
2124 /// parameter. At the reading process, each line of the section
2125 /// will be given to the functor object. However, the empty lines
2126 /// and the comment lines are filtered out, and the leading
2127 /// whitespaces are trimmed from each processed string.
2129 /// For example let's see a section, which contain several
2130 /// integers, which should be inserted into a vector.
2138 /// The functor is implemented as a struct:
2140 /// struct NumberSection {
2141 /// std::vector<int>& _data;
2142 /// NumberSection(std::vector<int>& data) : _data(data) {}
2143 /// void operator()(const std::string& line) {
2144 /// std::istringstream ls(line);
2146 /// while (ls >> value) _data.push_back(value);
2152 /// reader.sectionLines("numbers", NumberSection(vec));
2154 template <typename Functor>
2155 SectionReader& sectionLines(const std::string& type, Functor functor) {
2156 LEMON_ASSERT(!type.empty(), "Type is empty.");
2157 LEMON_ASSERT(_sections.find(type) == _sections.end(),
2158 "Multiple reading of section.");
2159 _sections.insert(std::make_pair(type,
2160 new _reader_bits::LineSection<Functor>(functor)));
2165 /// \brief Add a section processor with stream oriented reading
2167 /// The first parameter is the type of the section, the second is
2168 /// a functor, which takes an \c std::istream& and an \c int&
2169 /// parameter, the latter regard to the line number of stream. The
2170 /// functor can read the input while the section go on, and the
2171 /// line number should be modified accordingly.
2172 template <typename Functor>
2173 SectionReader& sectionStream(const std::string& type, Functor functor) {
2174 LEMON_ASSERT(!type.empty(), "Type is empty.");
2175 LEMON_ASSERT(_sections.find(type) == _sections.end(),
2176 "Multiple reading of section.");
2177 _sections.insert(std::make_pair(type,
2178 new _reader_bits::StreamSection<Functor>(functor)));
2188 while(++line_num, std::getline(*_is, str)) {
2189 line.clear(); line.str(str);
2191 if (line >> std::ws >> c && c != '#') {
2199 bool readSuccess() {
2200 return static_cast<bool>(*_is);
2203 void skipSection() {
2205 while (readSuccess() && line >> c && c != '@') {
2214 /// \name Execution of the reader
2217 /// \brief Start the batch processing
2219 /// This function starts the batch processing.
2222 LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
2224 std::set<std::string> extra_sections;
2230 while (readSuccess()) {
2233 std::string section, caption;
2235 _reader_bits::readToken(line, section);
2236 _reader_bits::readToken(line, caption);
2239 throw DataFormatError("Extra character on the end of line");
2241 if (extra_sections.find(section) != extra_sections.end()) {
2242 std::ostringstream msg;
2243 msg << "Multiple occurence of section " << section;
2244 throw DataFormatError(msg.str().c_str());
2246 Sections::iterator it = _sections.find(section);
2247 if (it != _sections.end()) {
2248 extra_sections.insert(section);
2249 it->second->process(*_is, line_num);
2253 } catch (DataFormatError& error) {
2254 error.line(line_num);
2258 for (Sections::iterator it = _sections.begin();
2259 it != _sections.end(); ++it) {
2260 if (extra_sections.find(it->first) == extra_sections.end()) {
2261 std::ostringstream os;
2262 os << "Cannot find section: " << it->first;
2263 throw DataFormatError(os.str().c_str());
2272 /// \brief Return a \ref SectionReader class
2274 /// This function just returns a \ref SectionReader class.
2275 /// \relates SectionReader
2276 inline SectionReader sectionReader(std::istream& is) {
2277 SectionReader tmp(is);
2281 /// \brief Return a \ref SectionReader class
2283 /// This function just returns a \ref SectionReader class.
2284 /// \relates SectionReader
2285 inline SectionReader sectionReader(const std::string& fn) {
2286 SectionReader tmp(fn);
2290 /// \brief Return a \ref SectionReader class
2292 /// This function just returns a \ref SectionReader class.
2293 /// \relates SectionReader
2294 inline SectionReader sectionReader(const char* fn) {
2295 SectionReader tmp(fn);
2299 /// \ingroup lemon_io
2301 /// \brief Reader for the contents of the \ref lgf-format "LGF" file
2303 /// This class can be used to read the sections, the map names and
2304 /// the attributes from a file. Usually, the LEMON programs know
2305 /// that, which type of graph, which maps and which attributes
2306 /// should be read from a file, but in general tools (like glemon)
2307 /// the contents of an LGF file should be guessed somehow. This class
2308 /// reads the graph and stores the appropriate information for
2309 /// reading the graph.
2312 /// LgfContents contents("graph.lgf");
2315 /// // Does it contain any node section and arc section?
2316 /// if (contents.nodeSectionNum() == 0 || contents.arcSectionNum()) {
2317 /// std::cerr << "Failure, cannot find graph." << std::endl;
2320 /// std::cout << "The name of the default node section: "
2321 /// << contents.nodeSection(0) << std::endl;
2322 /// std::cout << "The number of the arc maps: "
2323 /// << contents.arcMaps(0).size() << std::endl;
2324 /// std::cout << "The name of second arc map: "
2325 /// << contents.arcMaps(0)[1] << std::endl;
2333 std::vector<std::string> _node_sections;
2334 std::vector<std::string> _edge_sections;
2335 std::vector<std::string> _attribute_sections;
2336 std::vector<std::string> _extra_sections;
2338 std::vector<bool> _arc_sections;
2340 std::vector<std::vector<std::string> > _node_maps;
2341 std::vector<std::vector<std::string> > _edge_maps;
2343 std::vector<std::vector<std::string> > _attributes;
2347 std::istringstream line;
2351 /// \brief Constructor
2353 /// Construct an \e LGF contents reader, which reads from the given
2355 LgfContents(std::istream& is)
2356 : _is(&is), local_is(false) {}
2358 /// \brief Constructor
2360 /// Construct an \e LGF contents reader, which reads from the given
2362 LgfContents(const std::string& fn)
2363 : _is(new std::ifstream(fn.c_str())), local_is(true) {}
2365 /// \brief Constructor
2367 /// Construct an \e LGF contents reader, which reads from the given
2369 LgfContents(const char* fn)
2370 : _is(new std::ifstream(fn)), local_is(true) {}
2372 /// \brief Destructor
2374 if (local_is) delete _is;
2379 LgfContents(const LgfContents&);
2380 LgfContents& operator=(const LgfContents&);
2385 /// \name Node sections
2388 /// \brief Gives back the number of node sections in the file.
2390 /// Gives back the number of node sections in the file.
2391 int nodeSectionNum() const {
2392 return _node_sections.size();
2395 /// \brief Returns the node section name at the given position.
2397 /// Returns the node section name at the given position.
2398 const std::string& nodeSection(int i) const {
2399 return _node_sections[i];
2402 /// \brief Gives back the node maps for the given section.
2404 /// Gives back the node maps for the given section.
2405 const std::vector<std::string>& nodeMapNames(int i) const {
2406 return _node_maps[i];
2411 /// \name Arc/Edge sections
2414 /// \brief Gives back the number of arc/edge sections in the file.
2416 /// Gives back the number of arc/edge sections in the file.
2417 /// \note It is synonym of \c edgeSectionNum().
2418 int arcSectionNum() const {
2419 return _edge_sections.size();
2422 /// \brief Returns the arc/edge section name at the given position.
2424 /// Returns the arc/edge section name at the given position.
2425 /// \note It is synonym of \c edgeSection().
2426 const std::string& arcSection(int i) const {
2427 return _edge_sections[i];
2430 /// \brief Gives back the arc/edge maps for the given section.
2432 /// Gives back the arc/edge maps for the given section.
2433 /// \note It is synonym of \c edgeMapNames().
2434 const std::vector<std::string>& arcMapNames(int i) const {
2435 return _edge_maps[i];
2443 /// \brief Gives back the number of arc/edge sections in the file.
2445 /// Gives back the number of arc/edge sections in the file.
2446 /// \note It is synonym of \c arcSectionNum().
2447 int edgeSectionNum() const {
2448 return _edge_sections.size();
2451 /// \brief Returns the section name at the given position.
2453 /// Returns the section name at the given position.
2454 /// \note It is synonym of \c arcSection().
2455 const std::string& edgeSection(int i) const {
2456 return _edge_sections[i];
2459 /// \brief Gives back the edge maps for the given section.
2461 /// Gives back the edge maps for the given section.
2462 /// \note It is synonym of \c arcMapNames().
2463 const std::vector<std::string>& edgeMapNames(int i) const {
2464 return _edge_maps[i];
2469 /// \name Attribute sections
2472 /// \brief Gives back the number of attribute sections in the file.
2474 /// Gives back the number of attribute sections in the file.
2475 int attributeSectionNum() const {
2476 return _attribute_sections.size();
2479 /// \brief Returns the attribute section name at the given position.
2481 /// Returns the attribute section name at the given position.
2482 const std::string& attributeSectionNames(int i) const {
2483 return _attribute_sections[i];
2486 /// \brief Gives back the attributes for the given section.
2488 /// Gives back the attributes for the given section.
2489 const std::vector<std::string>& attributes(int i) const {
2490 return _attributes[i];
2495 /// \name Extra sections
2498 /// \brief Gives back the number of extra sections in the file.
2500 /// Gives back the number of extra sections in the file.
2501 int extraSectionNum() const {
2502 return _extra_sections.size();
2505 /// \brief Returns the extra section type at the given position.
2507 /// Returns the section type at the given position.
2508 const std::string& extraSection(int i) const {
2509 return _extra_sections[i];
2518 while(++line_num, std::getline(*_is, str)) {
2519 line.clear(); line.str(str);
2521 if (line >> std::ws >> c && c != '#') {
2529 bool readSuccess() {
2530 return static_cast<bool>(*_is);
2533 void skipSection() {
2535 while (readSuccess() && line >> c && c != '@') {
2541 void readMaps(std::vector<std::string>& maps) {
2543 if (!readLine() || !(line >> c) || c == '@') {
2544 if (readSuccess() && line) line.putback(c);
2549 while (_reader_bits::readToken(line, map)) {
2550 maps.push_back(map);
2554 void readAttributes(std::vector<std::string>& attrs) {
2557 while (readSuccess() && line >> c && c != '@') {
2560 _reader_bits::readToken(line, attr);
2561 attrs.push_back(attr);
2569 /// \name Execution of the contents reader
2572 /// \brief Starts the reading
2574 /// This function starts the reading.
2580 while (readSuccess()) {
2585 std::string section, caption;
2586 _reader_bits::readToken(line, section);
2587 _reader_bits::readToken(line, caption);
2589 if (section == "nodes") {
2590 _node_sections.push_back(caption);
2591 _node_maps.push_back(std::vector<std::string>());
2592 readMaps(_node_maps.back());
2593 readLine(); skipSection();
2594 } else if (section == "arcs" || section == "edges") {
2595 _edge_sections.push_back(caption);
2596 _arc_sections.push_back(section == "arcs");
2597 _edge_maps.push_back(std::vector<std::string>());
2598 readMaps(_edge_maps.back());
2599 readLine(); skipSection();
2600 } else if (section == "attributes") {
2601 _attribute_sections.push_back(caption);
2602 _attributes.push_back(std::vector<std::string>());
2603 readAttributes(_attributes.back());
2605 _extra_sections.push_back(section);
2606 readLine(); skipSection();