1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2009
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/core.h>
36 #include <lemon/lgf_writer.h>
38 #include <lemon/concept_check.h>
39 #include <lemon/concepts/maps.h>
43 namespace _reader_bits {
45 template <typename Value>
46 struct DefaultConverter {
47 Value operator()(const std::string& str) {
48 std::istringstream is(str);
51 throw FormatError("Cannot read token");
55 if (is >> std::ws >> c) {
56 throw FormatError("Remaining characters in token");
63 struct DefaultConverter<std::string> {
64 std::string operator()(const std::string& str) {
69 template <typename _Item>
70 class MapStorageBase {
76 virtual ~MapStorageBase() {}
78 virtual void set(const Item& item, const std::string& value) = 0;
82 template <typename _Item, typename _Map,
83 typename _Converter = DefaultConverter<typename _Map::Value> >
84 class MapStorage : public MapStorageBase<_Item> {
87 typedef _Converter Converter;
95 MapStorage(Map& map, const Converter& converter = Converter())
96 : _map(map), _converter(converter) {}
97 virtual ~MapStorage() {}
99 virtual void set(const Item& item ,const std::string& value) {
100 _map.set(item, _converter(value));
104 template <typename _Graph, bool _dir, typename _Map,
105 typename _Converter = DefaultConverter<typename _Map::Value> >
106 class GraphArcMapStorage : public MapStorageBase<typename _Graph::Edge> {
109 typedef _Converter Converter;
110 typedef _Graph Graph;
111 typedef typename Graph::Edge Item;
112 static const bool dir = _dir;
117 Converter _converter;
120 GraphArcMapStorage(const Graph& graph, Map& map,
121 const Converter& converter = Converter())
122 : _graph(graph), _map(map), _converter(converter) {}
123 virtual ~GraphArcMapStorage() {}
125 virtual void set(const Item& item ,const std::string& value) {
126 _map.set(_graph.direct(item, dir), _converter(value));
130 class ValueStorageBase {
132 ValueStorageBase() {}
133 virtual ~ValueStorageBase() {}
135 virtual void set(const std::string&) = 0;
138 template <typename _Value, typename _Converter = DefaultConverter<_Value> >
139 class ValueStorage : public ValueStorageBase {
141 typedef _Value Value;
142 typedef _Converter Converter;
146 Converter _converter;
149 ValueStorage(Value& value, const Converter& converter = Converter())
150 : _value(value), _converter(converter) {}
152 virtual void set(const std::string& value) {
153 _value = _converter(value);
157 template <typename Value>
158 struct MapLookUpConverter {
159 const std::map<std::string, Value>& _map;
161 MapLookUpConverter(const std::map<std::string, Value>& map)
164 Value operator()(const std::string& str) {
165 typename std::map<std::string, Value>::const_iterator it =
167 if (it == _map.end()) {
168 std::ostringstream msg;
169 msg << "Item not found: " << str;
170 throw FormatError(msg.str());
176 template <typename Graph>
177 struct GraphArcLookUpConverter {
179 const std::map<std::string, typename Graph::Edge>& _map;
181 GraphArcLookUpConverter(const Graph& graph,
182 const std::map<std::string,
183 typename Graph::Edge>& map)
184 : _graph(graph), _map(map) {}
186 typename Graph::Arc operator()(const std::string& str) {
187 if (str.empty() || (str[0] != '+' && str[0] != '-')) {
188 throw FormatError("Item must start with '+' or '-'");
190 typename std::map<std::string, typename Graph::Edge>
191 ::const_iterator it = _map.find(str.substr(1));
192 if (it == _map.end()) {
193 throw FormatError("Item not found");
195 return _graph.direct(it->second, str[0] == '+');
199 inline bool isWhiteSpace(char c) {
200 return c == ' ' || c == '\t' || c == '\v' ||
201 c == '\n' || c == '\r' || c == '\f';
204 inline bool isOct(char c) {
205 return '0' <= c && c <='7';
208 inline int valueOct(char c) {
209 LEMON_ASSERT(isOct(c), "The character is not octal.");
213 inline bool isHex(char c) {
214 return ('0' <= c && c <= '9') ||
215 ('a' <= c && c <= 'z') ||
216 ('A' <= c && c <= 'Z');
219 inline int valueHex(char c) {
220 LEMON_ASSERT(isHex(c), "The character is not hexadecimal.");
221 if ('0' <= c && c <= '9') return c - '0';
222 if ('a' <= c && c <= 'z') return c - 'a' + 10;
226 inline bool isIdentifierFirstChar(char c) {
227 return ('a' <= c && c <= 'z') ||
228 ('A' <= c && c <= 'Z') || c == '_';
231 inline bool isIdentifierChar(char c) {
232 return isIdentifierFirstChar(c) ||
233 ('0' <= c && c <= '9');
236 inline char readEscape(std::istream& is) {
239 throw FormatError("Escape format error");
267 if (!is.get(c) || !isHex(c))
268 throw FormatError("Escape format error");
269 else if (code = valueHex(c), !is.get(c) || !isHex(c)) is.putback(c);
270 else code = code * 16 + valueHex(c);
277 throw FormatError("Escape format error");
278 else if (code = valueOct(c), !is.get(c) || !isOct(c))
280 else if (code = code * 8 + valueOct(c), !is.get(c) || !isOct(c))
282 else code = code * 8 + valueOct(c);
288 inline std::istream& readToken(std::istream& is, std::string& str) {
289 std::ostringstream os;
298 while (is.get(c) && c != '\"') {
304 throw FormatError("Quoted format error");
307 while (is.get(c) && !isWhiteSpace(c)) {
324 virtual ~Section() {}
325 virtual void process(std::istream& is, int& line_num) = 0;
328 template <typename Functor>
329 class LineSection : public Section {
336 LineSection(const Functor& functor) : _functor(functor) {}
337 virtual ~LineSection() {}
339 virtual void process(std::istream& is, int& line_num) {
342 while (is.get(c) && c != '@') {
345 } else if (c == '#') {
348 } else if (!isWhiteSpace(c)) {
355 if (is) is.putback(c);
356 else if (is.eof()) is.clear();
360 template <typename Functor>
361 class StreamSection : public Section {
368 StreamSection(const Functor& functor) : _functor(functor) {}
369 virtual ~StreamSection() {}
371 virtual void process(std::istream& is, int& line_num) {
372 _functor(is, line_num);
375 while (is.get(c) && c != '@') {
378 } else if (!isWhiteSpace(c)) {
383 if (is) is.putback(c);
384 else if (is.eof()) is.clear();
390 template <typename Digraph>
393 template <typename Digraph>
394 DigraphReader<Digraph> digraphReader(Digraph& digraph,
395 std::istream& is = std::cin);
396 template <typename Digraph>
397 DigraphReader<Digraph> digraphReader(Digraph& digraph, const std::string& fn);
398 template <typename Digraph>
399 DigraphReader<Digraph> digraphReader(Digraph& digraph, const char *fn);
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>(digraph, std::cin).
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 GR>
452 class DigraphReader {
459 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
463 std::string _filename;
467 std::string _nodes_caption;
468 std::string _arcs_caption;
469 std::string _attributes_caption;
471 typedef std::map<std::string, Node> NodeIndex;
472 NodeIndex _node_index;
473 typedef std::map<std::string, Arc> ArcIndex;
476 typedef std::vector<std::pair<std::string,
477 _reader_bits::MapStorageBase<Node>*> > NodeMaps;
480 typedef std::vector<std::pair<std::string,
481 _reader_bits::MapStorageBase<Arc>*> >ArcMaps;
484 typedef std::multimap<std::string, _reader_bits::ValueStorageBase*>
486 Attributes _attributes;
495 std::istringstream line;
499 /// \brief Constructor
501 /// Construct a directed graph reader, which reads from the given
503 DigraphReader(Digraph& digraph, std::istream& is = std::cin)
504 : _is(&is), local_is(false), _digraph(digraph),
505 _use_nodes(false), _use_arcs(false),
506 _skip_nodes(false), _skip_arcs(false) {}
508 /// \brief Constructor
510 /// Construct a directed graph reader, which reads from the given
512 DigraphReader(Digraph& digraph, const std::string& fn)
513 : _is(new std::ifstream(fn.c_str())), local_is(true),
514 _filename(fn), _digraph(digraph),
515 _use_nodes(false), _use_arcs(false),
516 _skip_nodes(false), _skip_arcs(false) {
519 throw IoError("Cannot open file", fn);
523 /// \brief Constructor
525 /// Construct a directed graph reader, which reads from the given
527 DigraphReader(Digraph& digraph, const char* fn)
528 : _is(new std::ifstream(fn)), local_is(true),
529 _filename(fn), _digraph(digraph),
530 _use_nodes(false), _use_arcs(false),
531 _skip_nodes(false), _skip_arcs(false) {
534 throw IoError("Cannot open file", fn);
538 /// \brief Destructor
540 for (typename NodeMaps::iterator it = _node_maps.begin();
541 it != _node_maps.end(); ++it) {
545 for (typename ArcMaps::iterator it = _arc_maps.begin();
546 it != _arc_maps.end(); ++it) {
550 for (typename Attributes::iterator it = _attributes.begin();
551 it != _attributes.end(); ++it) {
563 template <typename DGR>
564 friend DigraphReader<DGR> digraphReader(DGR& digraph, std::istream& is);
565 template <typename DGR>
566 friend DigraphReader<DGR> digraphReader(DGR& digraph,
567 const std::string& fn);
568 template <typename DGR>
569 friend DigraphReader<DGR> digraphReader(DGR& digraph, const char *fn);
571 DigraphReader(DigraphReader& other)
572 : _is(other._is), local_is(other.local_is), _digraph(other._digraph),
573 _use_nodes(other._use_nodes), _use_arcs(other._use_arcs),
574 _skip_nodes(other._skip_nodes), _skip_arcs(other._skip_arcs) {
577 other.local_is = false;
579 _node_index.swap(other._node_index);
580 _arc_index.swap(other._arc_index);
582 _node_maps.swap(other._node_maps);
583 _arc_maps.swap(other._arc_maps);
584 _attributes.swap(other._attributes);
586 _nodes_caption = other._nodes_caption;
587 _arcs_caption = other._arcs_caption;
588 _attributes_caption = other._attributes_caption;
592 DigraphReader& operator=(const DigraphReader&);
596 /// \name Reading Rules
599 /// \brief Node map reading rule
601 /// Add a node map reading rule to the reader.
602 template <typename Map>
603 DigraphReader& nodeMap(const std::string& caption, Map& map) {
604 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
605 _reader_bits::MapStorageBase<Node>* storage =
606 new _reader_bits::MapStorage<Node, Map>(map);
607 _node_maps.push_back(std::make_pair(caption, storage));
611 /// \brief Node map reading rule
613 /// Add a node map reading rule with specialized converter to the
615 template <typename Map, typename Converter>
616 DigraphReader& nodeMap(const std::string& caption, Map& map,
617 const Converter& converter = Converter()) {
618 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
619 _reader_bits::MapStorageBase<Node>* storage =
620 new _reader_bits::MapStorage<Node, Map, Converter>(map, converter);
621 _node_maps.push_back(std::make_pair(caption, storage));
625 /// \brief Arc map reading rule
627 /// Add an arc map reading rule to the reader.
628 template <typename Map>
629 DigraphReader& arcMap(const std::string& caption, Map& map) {
630 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
631 _reader_bits::MapStorageBase<Arc>* storage =
632 new _reader_bits::MapStorage<Arc, Map>(map);
633 _arc_maps.push_back(std::make_pair(caption, storage));
637 /// \brief Arc map reading rule
639 /// Add an arc map reading rule with specialized converter to the
641 template <typename Map, typename Converter>
642 DigraphReader& arcMap(const std::string& caption, Map& map,
643 const Converter& converter = Converter()) {
644 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
645 _reader_bits::MapStorageBase<Arc>* storage =
646 new _reader_bits::MapStorage<Arc, Map, Converter>(map, converter);
647 _arc_maps.push_back(std::make_pair(caption, storage));
651 /// \brief Attribute reading rule
653 /// Add an attribute reading rule to the reader.
654 template <typename Value>
655 DigraphReader& attribute(const std::string& caption, Value& value) {
656 _reader_bits::ValueStorageBase* storage =
657 new _reader_bits::ValueStorage<Value>(value);
658 _attributes.insert(std::make_pair(caption, storage));
662 /// \brief Attribute reading rule
664 /// Add an attribute reading rule with specialized converter to the
666 template <typename Value, typename Converter>
667 DigraphReader& attribute(const std::string& caption, Value& value,
668 const Converter& converter = Converter()) {
669 _reader_bits::ValueStorageBase* storage =
670 new _reader_bits::ValueStorage<Value, Converter>(value, converter);
671 _attributes.insert(std::make_pair(caption, storage));
675 /// \brief Node reading rule
677 /// Add a node reading rule to reader.
678 DigraphReader& node(const std::string& caption, Node& node) {
679 typedef _reader_bits::MapLookUpConverter<Node> Converter;
680 Converter converter(_node_index);
681 _reader_bits::ValueStorageBase* storage =
682 new _reader_bits::ValueStorage<Node, Converter>(node, converter);
683 _attributes.insert(std::make_pair(caption, storage));
687 /// \brief Arc reading rule
689 /// Add an arc reading rule to reader.
690 DigraphReader& arc(const std::string& caption, Arc& arc) {
691 typedef _reader_bits::MapLookUpConverter<Arc> Converter;
692 Converter converter(_arc_index);
693 _reader_bits::ValueStorageBase* storage =
694 new _reader_bits::ValueStorage<Arc, Converter>(arc, converter);
695 _attributes.insert(std::make_pair(caption, storage));
701 /// \name Select Section by Name
704 /// \brief Set \c \@nodes section to be read
706 /// Set \c \@nodes section to be read
707 DigraphReader& nodes(const std::string& caption) {
708 _nodes_caption = caption;
712 /// \brief Set \c \@arcs section to be read
714 /// Set \c \@arcs section to be read
715 DigraphReader& arcs(const std::string& caption) {
716 _arcs_caption = caption;
720 /// \brief Set \c \@attributes section to be read
722 /// Set \c \@attributes section to be read
723 DigraphReader& attributes(const std::string& caption) {
724 _attributes_caption = caption;
730 /// \name Using Previously Constructed Node or Arc Set
733 /// \brief Use previously constructed node set
735 /// Use previously constructed node set, and specify the node
737 template <typename Map>
738 DigraphReader& useNodes(const Map& map) {
739 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
740 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
742 _writer_bits::DefaultConverter<typename Map::Value> converter;
743 for (NodeIt n(_digraph); n != INVALID; ++n) {
744 _node_index.insert(std::make_pair(converter(map[n]), n));
749 /// \brief Use previously constructed node set
751 /// Use previously constructed node set, and specify the node
752 /// label map and a functor which converts the label map values to
754 template <typename Map, typename Converter>
755 DigraphReader& useNodes(const Map& map,
756 const Converter& converter = Converter()) {
757 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
758 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
760 for (NodeIt n(_digraph); n != INVALID; ++n) {
761 _node_index.insert(std::make_pair(converter(map[n]), n));
766 /// \brief Use previously constructed arc set
768 /// Use previously constructed arc set, and specify the arc
770 template <typename Map>
771 DigraphReader& useArcs(const Map& map) {
772 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
773 LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member");
775 _writer_bits::DefaultConverter<typename Map::Value> converter;
776 for (ArcIt a(_digraph); a != INVALID; ++a) {
777 _arc_index.insert(std::make_pair(converter(map[a]), a));
782 /// \brief Use previously constructed arc set
784 /// Use previously constructed arc set, and specify the arc
785 /// label map and a functor which converts the label map values to
787 template <typename Map, typename Converter>
788 DigraphReader& useArcs(const Map& map,
789 const Converter& converter = Converter()) {
790 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
791 LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member");
793 for (ArcIt a(_digraph); a != INVALID; ++a) {
794 _arc_index.insert(std::make_pair(converter(map[a]), a));
799 /// \brief Skips the reading of node section
801 /// Omit the reading of the node section. This implies that each node
802 /// map reading rule will be abandoned, and the nodes of the graph
803 /// will not be constructed, which usually cause that the arc set
804 /// could not be read due to lack of node name resolving.
805 /// Therefore \c skipArcs() function should also be used, or
806 /// \c useNodes() should be used to specify the label of the nodes.
807 DigraphReader& skipNodes() {
808 LEMON_ASSERT(!_skip_nodes, "Skip nodes already set");
813 /// \brief Skips the reading of arc section
815 /// Omit the reading of the arc section. This implies that each arc
816 /// map reading rule will be abandoned, and the arcs of the graph
817 /// will not be constructed.
818 DigraphReader& skipArcs() {
819 LEMON_ASSERT(!_skip_arcs, "Skip arcs already set");
830 while(++line_num, std::getline(*_is, str)) {
831 line.clear(); line.str(str);
833 if (line >> std::ws >> c && c != '#') {
842 return static_cast<bool>(*_is);
847 while (readSuccess() && line >> c && c != '@') {
857 std::vector<int> map_index(_node_maps.size());
858 int map_num, label_index;
861 if (!readLine() || !(line >> c) || c == '@') {
862 if (readSuccess() && line) line.putback(c);
863 if (!_node_maps.empty())
864 throw FormatError("Cannot find map names");
870 std::map<std::string, int> maps;
874 while (_reader_bits::readToken(line, map)) {
875 if (maps.find(map) != maps.end()) {
876 std::ostringstream msg;
877 msg << "Multiple occurence of node map: " << map;
878 throw FormatError(msg.str());
880 maps.insert(std::make_pair(map, index));
884 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
885 std::map<std::string, int>::iterator jt =
886 maps.find(_node_maps[i].first);
887 if (jt == maps.end()) {
888 std::ostringstream msg;
889 msg << "Map not found: " << _node_maps[i].first;
890 throw FormatError(msg.str());
892 map_index[i] = jt->second;
896 std::map<std::string, int>::iterator jt = maps.find("label");
897 if (jt != maps.end()) {
898 label_index = jt->second;
903 map_num = maps.size();
906 while (readLine() && line >> c && c != '@') {
909 std::vector<std::string> tokens(map_num);
910 for (int i = 0; i < map_num; ++i) {
911 if (!_reader_bits::readToken(line, tokens[i])) {
912 std::ostringstream msg;
913 msg << "Column not found (" << i + 1 << ")";
914 throw FormatError(msg.str());
917 if (line >> std::ws >> c)
918 throw FormatError("Extra character at the end of line");
922 n = _digraph.addNode();
923 if (label_index != -1)
924 _node_index.insert(std::make_pair(tokens[label_index], n));
926 if (label_index == -1)
927 throw FormatError("Label map not found");
928 typename std::map<std::string, Node>::iterator it =
929 _node_index.find(tokens[label_index]);
930 if (it == _node_index.end()) {
931 std::ostringstream msg;
932 msg << "Node with label not found: " << tokens[label_index];
933 throw FormatError(msg.str());
938 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
939 _node_maps[i].second->set(n, tokens[map_index[i]]);
950 std::vector<int> map_index(_arc_maps.size());
951 int map_num, label_index;
954 if (!readLine() || !(line >> c) || c == '@') {
955 if (readSuccess() && line) line.putback(c);
956 if (!_arc_maps.empty())
957 throw FormatError("Cannot find map names");
963 std::map<std::string, int> maps;
967 while (_reader_bits::readToken(line, map)) {
968 if (maps.find(map) != maps.end()) {
969 std::ostringstream msg;
970 msg << "Multiple occurence of arc map: " << map;
971 throw FormatError(msg.str());
973 maps.insert(std::make_pair(map, index));
977 for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) {
978 std::map<std::string, int>::iterator jt =
979 maps.find(_arc_maps[i].first);
980 if (jt == maps.end()) {
981 std::ostringstream msg;
982 msg << "Map not found: " << _arc_maps[i].first;
983 throw FormatError(msg.str());
985 map_index[i] = jt->second;
989 std::map<std::string, int>::iterator jt = maps.find("label");
990 if (jt != maps.end()) {
991 label_index = jt->second;
996 map_num = maps.size();
999 while (readLine() && line >> c && c != '@') {
1002 std::string source_token;
1003 std::string target_token;
1005 if (!_reader_bits::readToken(line, source_token))
1006 throw FormatError("Source not found");
1008 if (!_reader_bits::readToken(line, target_token))
1009 throw FormatError("Target not found");
1011 std::vector<std::string> tokens(map_num);
1012 for (int i = 0; i < map_num; ++i) {
1013 if (!_reader_bits::readToken(line, tokens[i])) {
1014 std::ostringstream msg;
1015 msg << "Column not found (" << i + 1 << ")";
1016 throw FormatError(msg.str());
1019 if (line >> std::ws >> c)
1020 throw FormatError("Extra character at the end of line");
1025 typename NodeIndex::iterator it;
1027 it = _node_index.find(source_token);
1028 if (it == _node_index.end()) {
1029 std::ostringstream msg;
1030 msg << "Item not found: " << source_token;
1031 throw FormatError(msg.str());
1033 Node source = it->second;
1035 it = _node_index.find(target_token);
1036 if (it == _node_index.end()) {
1037 std::ostringstream msg;
1038 msg << "Item not found: " << target_token;
1039 throw FormatError(msg.str());
1041 Node target = it->second;
1043 a = _digraph.addArc(source, target);
1044 if (label_index != -1)
1045 _arc_index.insert(std::make_pair(tokens[label_index], a));
1047 if (label_index == -1)
1048 throw FormatError("Label map not found");
1049 typename std::map<std::string, Arc>::iterator it =
1050 _arc_index.find(tokens[label_index]);
1051 if (it == _arc_index.end()) {
1052 std::ostringstream msg;
1053 msg << "Arc with label not found: " << tokens[label_index];
1054 throw FormatError(msg.str());
1059 for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) {
1060 _arc_maps[i].second->set(a, tokens[map_index[i]]);
1064 if (readSuccess()) {
1069 void readAttributes() {
1071 std::set<std::string> read_attr;
1074 while (readLine() && line >> c && c != '@') {
1077 std::string attr, token;
1078 if (!_reader_bits::readToken(line, attr))
1079 throw FormatError("Attribute name not found");
1080 if (!_reader_bits::readToken(line, token))
1081 throw FormatError("Attribute value not found");
1083 throw FormatError("Extra character at the end of line");
1086 std::set<std::string>::iterator it = read_attr.find(attr);
1087 if (it != read_attr.end()) {
1088 std::ostringstream msg;
1089 msg << "Multiple occurence of attribute: " << attr;
1090 throw FormatError(msg.str());
1092 read_attr.insert(attr);
1096 typename Attributes::iterator it = _attributes.lower_bound(attr);
1097 while (it != _attributes.end() && it->first == attr) {
1098 it->second->set(token);
1104 if (readSuccess()) {
1107 for (typename Attributes::iterator it = _attributes.begin();
1108 it != _attributes.end(); ++it) {
1109 if (read_attr.find(it->first) == read_attr.end()) {
1110 std::ostringstream msg;
1111 msg << "Attribute not found: " << it->first;
1112 throw FormatError(msg.str());
1119 /// \name Execution of the Reader
1122 /// \brief Start the batch processing
1124 /// This function starts the batch processing
1126 LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
1128 bool nodes_done = _skip_nodes;
1129 bool arcs_done = _skip_arcs;
1130 bool attributes_done = false;
1136 while (readSuccess()) {
1139 std::string section, caption;
1141 _reader_bits::readToken(line, section);
1142 _reader_bits::readToken(line, caption);
1145 throw FormatError("Extra character at the end of line");
1147 if (section == "nodes" && !nodes_done) {
1148 if (_nodes_caption.empty() || _nodes_caption == caption) {
1152 } else if ((section == "arcs" || section == "edges") &&
1154 if (_arcs_caption.empty() || _arcs_caption == caption) {
1158 } else if (section == "attributes" && !attributes_done) {
1159 if (_attributes_caption.empty() || _attributes_caption == caption) {
1161 attributes_done = true;
1167 } catch (FormatError& error) {
1168 error.line(line_num);
1169 error.file(_filename);
1175 throw FormatError("Section @nodes not found");
1179 throw FormatError("Section @arcs not found");
1182 if (!attributes_done && !_attributes.empty()) {
1183 throw FormatError("Section @attributes not found");
1192 /// \brief Return a \ref DigraphReader class
1194 /// This function just returns a \ref DigraphReader class.
1195 /// \relates DigraphReader
1196 template <typename Digraph>
1197 DigraphReader<Digraph> digraphReader(Digraph& digraph, std::istream& is) {
1198 DigraphReader<Digraph> tmp(digraph, is);
1202 /// \brief Return a \ref DigraphReader class
1204 /// This function just returns a \ref DigraphReader class.
1205 /// \relates DigraphReader
1206 template <typename Digraph>
1207 DigraphReader<Digraph> digraphReader(Digraph& digraph,
1208 const std::string& fn) {
1209 DigraphReader<Digraph> tmp(digraph, fn);
1213 /// \brief Return a \ref DigraphReader class
1215 /// This function just returns a \ref DigraphReader class.
1216 /// \relates DigraphReader
1217 template <typename Digraph>
1218 DigraphReader<Digraph> digraphReader(Digraph& digraph, const char* fn) {
1219 DigraphReader<Digraph> tmp(digraph, fn);
1223 template <typename Graph>
1226 template <typename Graph>
1227 GraphReader<Graph> graphReader(Graph& graph,
1228 std::istream& is = std::cin);
1229 template <typename Graph>
1230 GraphReader<Graph> graphReader(Graph& graph, const std::string& fn);
1231 template <typename Graph>
1232 GraphReader<Graph> graphReader(Graph& graph, const char *fn);
1234 /// \ingroup lemon_io
1236 /// \brief \ref lgf-format "LGF" reader for undirected graphs
1238 /// This utility reads an \ref lgf-format "LGF" file.
1240 /// It can be used almost the same way as \c DigraphReader.
1241 /// The only difference is that this class can handle edges and
1242 /// edge maps as well as arcs and arc maps.
1244 /// The columns in the \c \@edges (or \c \@arcs) section are the
1245 /// edge maps. However, if there are two maps with the same name
1246 /// prefixed with \c '+' and \c '-', then these can be read into an
1247 /// arc map. Similarly, an attribute can be read into an arc, if
1248 /// it's value is an edge label prefixed with \c '+' or \c '-'.
1249 template <typename GR>
1257 TEMPLATE_GRAPH_TYPEDEFS(Graph);
1261 std::string _filename;
1265 std::string _nodes_caption;
1266 std::string _edges_caption;
1267 std::string _attributes_caption;
1269 typedef std::map<std::string, Node> NodeIndex;
1270 NodeIndex _node_index;
1271 typedef std::map<std::string, Edge> EdgeIndex;
1272 EdgeIndex _edge_index;
1274 typedef std::vector<std::pair<std::string,
1275 _reader_bits::MapStorageBase<Node>*> > NodeMaps;
1276 NodeMaps _node_maps;
1278 typedef std::vector<std::pair<std::string,
1279 _reader_bits::MapStorageBase<Edge>*> > EdgeMaps;
1280 EdgeMaps _edge_maps;
1282 typedef std::multimap<std::string, _reader_bits::ValueStorageBase*>
1284 Attributes _attributes;
1293 std::istringstream line;
1297 /// \brief Constructor
1299 /// Construct an undirected graph reader, which reads from the given
1301 GraphReader(Graph& graph, std::istream& is = std::cin)
1302 : _is(&is), local_is(false), _graph(graph),
1303 _use_nodes(false), _use_edges(false),
1304 _skip_nodes(false), _skip_edges(false) {}
1306 /// \brief Constructor
1308 /// Construct an undirected graph reader, which reads from the given
1310 GraphReader(Graph& graph, const std::string& fn)
1311 : _is(new std::ifstream(fn.c_str())), local_is(true),
1312 _filename(fn), _graph(graph),
1313 _use_nodes(false), _use_edges(false),
1314 _skip_nodes(false), _skip_edges(false) {
1317 throw IoError("Cannot open file", fn);
1321 /// \brief Constructor
1323 /// Construct an undirected graph reader, which reads from the given
1325 GraphReader(Graph& graph, const char* fn)
1326 : _is(new std::ifstream(fn)), local_is(true),
1327 _filename(fn), _graph(graph),
1328 _use_nodes(false), _use_edges(false),
1329 _skip_nodes(false), _skip_edges(false) {
1332 throw IoError("Cannot open file", fn);
1336 /// \brief Destructor
1338 for (typename NodeMaps::iterator it = _node_maps.begin();
1339 it != _node_maps.end(); ++it) {
1343 for (typename EdgeMaps::iterator it = _edge_maps.begin();
1344 it != _edge_maps.end(); ++it) {
1348 for (typename Attributes::iterator it = _attributes.begin();
1349 it != _attributes.end(); ++it) {
1360 template <typename Graph>
1361 friend GraphReader<Graph> graphReader(Graph& graph, std::istream& is);
1362 template <typename Graph>
1363 friend GraphReader<Graph> graphReader(Graph& graph, const std::string& fn);
1364 template <typename Graph>
1365 friend GraphReader<Graph> graphReader(Graph& graph, const char *fn);
1367 GraphReader(GraphReader& other)
1368 : _is(other._is), local_is(other.local_is), _graph(other._graph),
1369 _use_nodes(other._use_nodes), _use_edges(other._use_edges),
1370 _skip_nodes(other._skip_nodes), _skip_edges(other._skip_edges) {
1373 other.local_is = false;
1375 _node_index.swap(other._node_index);
1376 _edge_index.swap(other._edge_index);
1378 _node_maps.swap(other._node_maps);
1379 _edge_maps.swap(other._edge_maps);
1380 _attributes.swap(other._attributes);
1382 _nodes_caption = other._nodes_caption;
1383 _edges_caption = other._edges_caption;
1384 _attributes_caption = other._attributes_caption;
1388 GraphReader& operator=(const GraphReader&);
1392 /// \name Reading Rules
1395 /// \brief Node map reading rule
1397 /// Add a node map reading rule to the reader.
1398 template <typename Map>
1399 GraphReader& nodeMap(const std::string& caption, Map& map) {
1400 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
1401 _reader_bits::MapStorageBase<Node>* storage =
1402 new _reader_bits::MapStorage<Node, Map>(map);
1403 _node_maps.push_back(std::make_pair(caption, storage));
1407 /// \brief Node map reading rule
1409 /// Add a node map reading rule with specialized converter to the
1411 template <typename Map, typename Converter>
1412 GraphReader& nodeMap(const std::string& caption, Map& map,
1413 const Converter& converter = Converter()) {
1414 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
1415 _reader_bits::MapStorageBase<Node>* storage =
1416 new _reader_bits::MapStorage<Node, Map, Converter>(map, converter);
1417 _node_maps.push_back(std::make_pair(caption, storage));
1421 /// \brief Edge map reading rule
1423 /// Add an edge map reading rule to the reader.
1424 template <typename Map>
1425 GraphReader& edgeMap(const std::string& caption, Map& map) {
1426 checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>();
1427 _reader_bits::MapStorageBase<Edge>* storage =
1428 new _reader_bits::MapStorage<Edge, Map>(map);
1429 _edge_maps.push_back(std::make_pair(caption, storage));
1433 /// \brief Edge map reading rule
1435 /// Add an edge map reading rule with specialized converter to the
1437 template <typename Map, typename Converter>
1438 GraphReader& edgeMap(const std::string& caption, Map& map,
1439 const Converter& converter = Converter()) {
1440 checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>();
1441 _reader_bits::MapStorageBase<Edge>* storage =
1442 new _reader_bits::MapStorage<Edge, Map, Converter>(map, converter);
1443 _edge_maps.push_back(std::make_pair(caption, storage));
1447 /// \brief Arc map reading rule
1449 /// Add an arc map reading rule to the reader.
1450 template <typename Map>
1451 GraphReader& arcMap(const std::string& caption, Map& map) {
1452 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
1453 _reader_bits::MapStorageBase<Edge>* forward_storage =
1454 new _reader_bits::GraphArcMapStorage<Graph, true, Map>(_graph, map);
1455 _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
1456 _reader_bits::MapStorageBase<Edge>* backward_storage =
1457 new _reader_bits::GraphArcMapStorage<Graph, false, Map>(_graph, map);
1458 _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
1462 /// \brief Arc map reading rule
1464 /// Add an arc map reading rule with specialized converter to the
1466 template <typename Map, typename Converter>
1467 GraphReader& arcMap(const std::string& caption, Map& map,
1468 const Converter& converter = Converter()) {
1469 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
1470 _reader_bits::MapStorageBase<Edge>* forward_storage =
1471 new _reader_bits::GraphArcMapStorage<Graph, true, Map, Converter>
1472 (_graph, map, converter);
1473 _edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
1474 _reader_bits::MapStorageBase<Edge>* backward_storage =
1475 new _reader_bits::GraphArcMapStorage<Graph, false, Map, Converter>
1476 (_graph, map, converter);
1477 _edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
1481 /// \brief Attribute reading rule
1483 /// Add an attribute reading rule to the reader.
1484 template <typename Value>
1485 GraphReader& attribute(const std::string& caption, Value& value) {
1486 _reader_bits::ValueStorageBase* storage =
1487 new _reader_bits::ValueStorage<Value>(value);
1488 _attributes.insert(std::make_pair(caption, storage));
1492 /// \brief Attribute reading rule
1494 /// Add an attribute reading rule with specialized converter to the
1496 template <typename Value, typename Converter>
1497 GraphReader& attribute(const std::string& caption, Value& value,
1498 const Converter& converter = Converter()) {
1499 _reader_bits::ValueStorageBase* storage =
1500 new _reader_bits::ValueStorage<Value, Converter>(value, converter);
1501 _attributes.insert(std::make_pair(caption, storage));
1505 /// \brief Node reading rule
1507 /// Add a node reading rule to reader.
1508 GraphReader& node(const std::string& caption, Node& node) {
1509 typedef _reader_bits::MapLookUpConverter<Node> Converter;
1510 Converter converter(_node_index);
1511 _reader_bits::ValueStorageBase* storage =
1512 new _reader_bits::ValueStorage<Node, Converter>(node, converter);
1513 _attributes.insert(std::make_pair(caption, storage));
1517 /// \brief Edge reading rule
1519 /// Add an edge reading rule to reader.
1520 GraphReader& edge(const std::string& caption, Edge& edge) {
1521 typedef _reader_bits::MapLookUpConverter<Edge> Converter;
1522 Converter converter(_edge_index);
1523 _reader_bits::ValueStorageBase* storage =
1524 new _reader_bits::ValueStorage<Edge, Converter>(edge, converter);
1525 _attributes.insert(std::make_pair(caption, storage));
1529 /// \brief Arc reading rule
1531 /// Add an arc reading rule to reader.
1532 GraphReader& arc(const std::string& caption, Arc& arc) {
1533 typedef _reader_bits::GraphArcLookUpConverter<Graph> Converter;
1534 Converter converter(_graph, _edge_index);
1535 _reader_bits::ValueStorageBase* storage =
1536 new _reader_bits::ValueStorage<Arc, Converter>(arc, converter);
1537 _attributes.insert(std::make_pair(caption, storage));
1543 /// \name Select Section by Name
1546 /// \brief Set \c \@nodes section to be read
1548 /// Set \c \@nodes section to be read.
1549 GraphReader& nodes(const std::string& caption) {
1550 _nodes_caption = caption;
1554 /// \brief Set \c \@edges section to be read
1556 /// Set \c \@edges section to be read.
1557 GraphReader& edges(const std::string& caption) {
1558 _edges_caption = caption;
1562 /// \brief Set \c \@attributes section to be read
1564 /// Set \c \@attributes section to be read.
1565 GraphReader& attributes(const std::string& caption) {
1566 _attributes_caption = caption;
1572 /// \name Using Previously Constructed Node or Edge Set
1575 /// \brief Use previously constructed node set
1577 /// Use previously constructed node set, and specify the node
1579 template <typename Map>
1580 GraphReader& useNodes(const Map& map) {
1581 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
1582 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
1584 _writer_bits::DefaultConverter<typename Map::Value> converter;
1585 for (NodeIt n(_graph); n != INVALID; ++n) {
1586 _node_index.insert(std::make_pair(converter(map[n]), n));
1591 /// \brief Use previously constructed node set
1593 /// Use previously constructed node set, and specify the node
1594 /// label map and a functor which converts the label map values to
1596 template <typename Map, typename Converter>
1597 GraphReader& useNodes(const Map& map,
1598 const Converter& converter = Converter()) {
1599 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
1600 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
1602 for (NodeIt n(_graph); n != INVALID; ++n) {
1603 _node_index.insert(std::make_pair(converter(map[n]), n));
1608 /// \brief Use previously constructed edge set
1610 /// Use previously constructed edge set, and specify the edge
1612 template <typename Map>
1613 GraphReader& useEdges(const Map& map) {
1614 checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
1615 LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member");
1617 _writer_bits::DefaultConverter<typename Map::Value> converter;
1618 for (EdgeIt a(_graph); a != INVALID; ++a) {
1619 _edge_index.insert(std::make_pair(converter(map[a]), a));
1624 /// \brief Use previously constructed edge set
1626 /// Use previously constructed edge set, and specify the edge
1627 /// label map and a functor which converts the label map values to
1629 template <typename Map, typename Converter>
1630 GraphReader& useEdges(const Map& map,
1631 const Converter& converter = Converter()) {
1632 checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
1633 LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member");
1635 for (EdgeIt a(_graph); a != INVALID; ++a) {
1636 _edge_index.insert(std::make_pair(converter(map[a]), a));
1641 /// \brief Skip the reading of node section
1643 /// Omit the reading of the node section. This implies that each node
1644 /// map reading rule will be abandoned, and the nodes of the graph
1645 /// will not be constructed, which usually cause that the edge set
1646 /// could not be read due to lack of node name
1647 /// could not be read due to lack of node name resolving.
1648 /// Therefore \c skipEdges() function should also be used, or
1649 /// \c useNodes() should be used to specify the label of the nodes.
1650 GraphReader& skipNodes() {
1651 LEMON_ASSERT(!_skip_nodes, "Skip nodes already set");
1656 /// \brief Skip the reading of edge section
1658 /// Omit the reading of the edge section. This implies that each edge
1659 /// map reading rule will be abandoned, and the edges of the graph
1660 /// will not be constructed.
1661 GraphReader& skipEdges() {
1662 LEMON_ASSERT(!_skip_edges, "Skip edges already set");
1673 while(++line_num, std::getline(*_is, str)) {
1674 line.clear(); line.str(str);
1676 if (line >> std::ws >> c && c != '#') {
1684 bool readSuccess() {
1685 return static_cast<bool>(*_is);
1688 void skipSection() {
1690 while (readSuccess() && line >> c && c != '@') {
1693 if (readSuccess()) {
1700 std::vector<int> map_index(_node_maps.size());
1701 int map_num, label_index;
1704 if (!readLine() || !(line >> c) || c == '@') {
1705 if (readSuccess() && line) line.putback(c);
1706 if (!_node_maps.empty())
1707 throw FormatError("Cannot find map names");
1713 std::map<std::string, int> maps;
1717 while (_reader_bits::readToken(line, map)) {
1718 if (maps.find(map) != maps.end()) {
1719 std::ostringstream msg;
1720 msg << "Multiple occurence of node map: " << map;
1721 throw FormatError(msg.str());
1723 maps.insert(std::make_pair(map, index));
1727 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
1728 std::map<std::string, int>::iterator jt =
1729 maps.find(_node_maps[i].first);
1730 if (jt == maps.end()) {
1731 std::ostringstream msg;
1732 msg << "Map not found: " << _node_maps[i].first;
1733 throw FormatError(msg.str());
1735 map_index[i] = jt->second;
1739 std::map<std::string, int>::iterator jt = maps.find("label");
1740 if (jt != maps.end()) {
1741 label_index = jt->second;
1746 map_num = maps.size();
1749 while (readLine() && line >> c && c != '@') {
1752 std::vector<std::string> tokens(map_num);
1753 for (int i = 0; i < map_num; ++i) {
1754 if (!_reader_bits::readToken(line, tokens[i])) {
1755 std::ostringstream msg;
1756 msg << "Column not found (" << i + 1 << ")";
1757 throw FormatError(msg.str());
1760 if (line >> std::ws >> c)
1761 throw FormatError("Extra character at the end of line");
1765 n = _graph.addNode();
1766 if (label_index != -1)
1767 _node_index.insert(std::make_pair(tokens[label_index], n));
1769 if (label_index == -1)
1770 throw FormatError("Label map not found");
1771 typename std::map<std::string, Node>::iterator it =
1772 _node_index.find(tokens[label_index]);
1773 if (it == _node_index.end()) {
1774 std::ostringstream msg;
1775 msg << "Node with label not found: " << tokens[label_index];
1776 throw FormatError(msg.str());
1781 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
1782 _node_maps[i].second->set(n, tokens[map_index[i]]);
1786 if (readSuccess()) {
1793 std::vector<int> map_index(_edge_maps.size());
1794 int map_num, label_index;
1797 if (!readLine() || !(line >> c) || c == '@') {
1798 if (readSuccess() && line) line.putback(c);
1799 if (!_edge_maps.empty())
1800 throw FormatError("Cannot find map names");
1806 std::map<std::string, int> maps;
1810 while (_reader_bits::readToken(line, map)) {
1811 if (maps.find(map) != maps.end()) {
1812 std::ostringstream msg;
1813 msg << "Multiple occurence of edge map: " << map;
1814 throw FormatError(msg.str());
1816 maps.insert(std::make_pair(map, index));
1820 for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) {
1821 std::map<std::string, int>::iterator jt =
1822 maps.find(_edge_maps[i].first);
1823 if (jt == maps.end()) {
1824 std::ostringstream msg;
1825 msg << "Map not found: " << _edge_maps[i].first;
1826 throw FormatError(msg.str());
1828 map_index[i] = jt->second;
1832 std::map<std::string, int>::iterator jt = maps.find("label");
1833 if (jt != maps.end()) {
1834 label_index = jt->second;
1839 map_num = maps.size();
1842 while (readLine() && line >> c && c != '@') {
1845 std::string source_token;
1846 std::string target_token;
1848 if (!_reader_bits::readToken(line, source_token))
1849 throw FormatError("Node u not found");
1851 if (!_reader_bits::readToken(line, target_token))
1852 throw FormatError("Node v not found");
1854 std::vector<std::string> tokens(map_num);
1855 for (int i = 0; i < map_num; ++i) {
1856 if (!_reader_bits::readToken(line, tokens[i])) {
1857 std::ostringstream msg;
1858 msg << "Column not found (" << i + 1 << ")";
1859 throw FormatError(msg.str());
1862 if (line >> std::ws >> c)
1863 throw FormatError("Extra character at the end of line");
1868 typename NodeIndex::iterator it;
1870 it = _node_index.find(source_token);
1871 if (it == _node_index.end()) {
1872 std::ostringstream msg;
1873 msg << "Item not found: " << source_token;
1874 throw FormatError(msg.str());
1876 Node source = it->second;
1878 it = _node_index.find(target_token);
1879 if (it == _node_index.end()) {
1880 std::ostringstream msg;
1881 msg << "Item not found: " << target_token;
1882 throw FormatError(msg.str());
1884 Node target = it->second;
1886 e = _graph.addEdge(source, target);
1887 if (label_index != -1)
1888 _edge_index.insert(std::make_pair(tokens[label_index], e));
1890 if (label_index == -1)
1891 throw FormatError("Label map not found");
1892 typename std::map<std::string, Edge>::iterator it =
1893 _edge_index.find(tokens[label_index]);
1894 if (it == _edge_index.end()) {
1895 std::ostringstream msg;
1896 msg << "Edge with label not found: " << tokens[label_index];
1897 throw FormatError(msg.str());
1902 for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) {
1903 _edge_maps[i].second->set(e, tokens[map_index[i]]);
1907 if (readSuccess()) {
1912 void readAttributes() {
1914 std::set<std::string> read_attr;
1917 while (readLine() && line >> c && c != '@') {
1920 std::string attr, token;
1921 if (!_reader_bits::readToken(line, attr))
1922 throw FormatError("Attribute name not found");
1923 if (!_reader_bits::readToken(line, token))
1924 throw FormatError("Attribute value not found");
1926 throw FormatError("Extra character at the end of line");
1929 std::set<std::string>::iterator it = read_attr.find(attr);
1930 if (it != read_attr.end()) {
1931 std::ostringstream msg;
1932 msg << "Multiple occurence of attribute: " << attr;
1933 throw FormatError(msg.str());
1935 read_attr.insert(attr);
1939 typename Attributes::iterator it = _attributes.lower_bound(attr);
1940 while (it != _attributes.end() && it->first == attr) {
1941 it->second->set(token);
1947 if (readSuccess()) {
1950 for (typename Attributes::iterator it = _attributes.begin();
1951 it != _attributes.end(); ++it) {
1952 if (read_attr.find(it->first) == read_attr.end()) {
1953 std::ostringstream msg;
1954 msg << "Attribute not found: " << it->first;
1955 throw FormatError(msg.str());
1962 /// \name Execution of the Reader
1965 /// \brief Start the batch processing
1967 /// This function starts the batch processing
1970 LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
1972 bool nodes_done = _skip_nodes;
1973 bool edges_done = _skip_edges;
1974 bool attributes_done = false;
1980 while (readSuccess()) {
1983 std::string section, caption;
1985 _reader_bits::readToken(line, section);
1986 _reader_bits::readToken(line, caption);
1989 throw FormatError("Extra character at the end of line");
1991 if (section == "nodes" && !nodes_done) {
1992 if (_nodes_caption.empty() || _nodes_caption == caption) {
1996 } else if ((section == "edges" || section == "arcs") &&
1998 if (_edges_caption.empty() || _edges_caption == caption) {
2002 } else if (section == "attributes" && !attributes_done) {
2003 if (_attributes_caption.empty() || _attributes_caption == caption) {
2005 attributes_done = true;
2011 } catch (FormatError& error) {
2012 error.line(line_num);
2013 error.file(_filename);
2019 throw FormatError("Section @nodes not found");
2023 throw FormatError("Section @edges not found");
2026 if (!attributes_done && !_attributes.empty()) {
2027 throw FormatError("Section @attributes not found");
2036 /// \brief Return a \ref GraphReader class
2038 /// This function just returns a \ref GraphReader class.
2039 /// \relates GraphReader
2040 template <typename Graph>
2041 GraphReader<Graph> graphReader(Graph& graph, std::istream& is) {
2042 GraphReader<Graph> tmp(graph, is);
2046 /// \brief Return a \ref GraphReader class
2048 /// This function just returns a \ref GraphReader class.
2049 /// \relates GraphReader
2050 template <typename Graph>
2051 GraphReader<Graph> graphReader(Graph& graph, const std::string& fn) {
2052 GraphReader<Graph> tmp(graph, fn);
2056 /// \brief Return a \ref GraphReader class
2058 /// This function just returns a \ref GraphReader class.
2059 /// \relates GraphReader
2060 template <typename Graph>
2061 GraphReader<Graph> graphReader(Graph& graph, const char* fn) {
2062 GraphReader<Graph> tmp(graph, fn);
2066 class SectionReader;
2068 SectionReader sectionReader(std::istream& is);
2069 SectionReader sectionReader(const std::string& fn);
2070 SectionReader sectionReader(const char* fn);
2072 /// \ingroup lemon_io
2074 /// \brief Section reader class
2076 /// In the \ref lgf-format "LGF" file extra sections can be placed,
2077 /// which contain any data in arbitrary format. Such sections can be
2078 /// read with this class. A reading rule can be added to the class
2079 /// with two different functions. With the \c sectionLines() function a
2080 /// functor can process the section line-by-line, while with the \c
2081 /// sectionStream() member the section can be read from an input
2083 class SectionReader {
2088 std::string _filename;
2090 typedef std::map<std::string, _reader_bits::Section*> Sections;
2094 std::istringstream line;
2098 /// \brief Constructor
2100 /// Construct a section reader, which reads from the given input
2102 SectionReader(std::istream& is)
2103 : _is(&is), local_is(false) {}
2105 /// \brief Constructor
2107 /// Construct a section reader, which reads from the given file.
2108 SectionReader(const std::string& fn)
2109 : _is(new std::ifstream(fn.c_str())), local_is(true),
2113 throw IoError("Cannot open file", fn);
2117 /// \brief Constructor
2119 /// Construct a section reader, which reads from the given file.
2120 SectionReader(const char* fn)
2121 : _is(new std::ifstream(fn)), local_is(true),
2125 throw IoError("Cannot open file", fn);
2129 /// \brief Destructor
2131 for (Sections::iterator it = _sections.begin();
2132 it != _sections.end(); ++it) {
2144 friend SectionReader sectionReader(std::istream& is);
2145 friend SectionReader sectionReader(const std::string& fn);
2146 friend SectionReader sectionReader(const char* fn);
2148 SectionReader(SectionReader& other)
2149 : _is(other._is), local_is(other.local_is) {
2152 other.local_is = false;
2154 _sections.swap(other._sections);
2157 SectionReader& operator=(const SectionReader&);
2161 /// \name Section Readers
2164 /// \brief Add a section processor with line oriented reading
2166 /// The first parameter is the type descriptor of the section, the
2167 /// second is a functor, which takes just one \c std::string
2168 /// parameter. At the reading process, each line of the section
2169 /// will be given to the functor object. However, the empty lines
2170 /// and the comment lines are filtered out, and the leading
2171 /// whitespaces are trimmed from each processed string.
2173 /// For example let's see a section, which contain several
2174 /// integers, which should be inserted into a vector.
2182 /// The functor is implemented as a struct:
2184 /// struct NumberSection {
2185 /// std::vector<int>& _data;
2186 /// NumberSection(std::vector<int>& data) : _data(data) {}
2187 /// void operator()(const std::string& line) {
2188 /// std::istringstream ls(line);
2190 /// while (ls >> value) _data.push_back(value);
2196 /// reader.sectionLines("numbers", NumberSection(vec));
2198 template <typename Functor>
2199 SectionReader& sectionLines(const std::string& type, Functor functor) {
2200 LEMON_ASSERT(!type.empty(), "Type is empty.");
2201 LEMON_ASSERT(_sections.find(type) == _sections.end(),
2202 "Multiple reading of section.");
2203 _sections.insert(std::make_pair(type,
2204 new _reader_bits::LineSection<Functor>(functor)));
2209 /// \brief Add a section processor with stream oriented reading
2211 /// The first parameter is the type of the section, the second is
2212 /// a functor, which takes an \c std::istream& and an \c int&
2213 /// parameter, the latter regard to the line number of stream. The
2214 /// functor can read the input while the section go on, and the
2215 /// line number should be modified accordingly.
2216 template <typename Functor>
2217 SectionReader& sectionStream(const std::string& type, Functor functor) {
2218 LEMON_ASSERT(!type.empty(), "Type is empty.");
2219 LEMON_ASSERT(_sections.find(type) == _sections.end(),
2220 "Multiple reading of section.");
2221 _sections.insert(std::make_pair(type,
2222 new _reader_bits::StreamSection<Functor>(functor)));
2232 while(++line_num, std::getline(*_is, str)) {
2233 line.clear(); line.str(str);
2235 if (line >> std::ws >> c && c != '#') {
2243 bool readSuccess() {
2244 return static_cast<bool>(*_is);
2247 void skipSection() {
2249 while (readSuccess() && line >> c && c != '@') {
2252 if (readSuccess()) {
2260 /// \name Execution of the Reader
2263 /// \brief Start the batch processing
2265 /// This function starts the batch processing.
2268 LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
2270 std::set<std::string> extra_sections;
2276 while (readSuccess()) {
2279 std::string section, caption;
2281 _reader_bits::readToken(line, section);
2282 _reader_bits::readToken(line, caption);
2285 throw FormatError("Extra character at the end of line");
2287 if (extra_sections.find(section) != extra_sections.end()) {
2288 std::ostringstream msg;
2289 msg << "Multiple occurence of section: " << section;
2290 throw FormatError(msg.str());
2292 Sections::iterator it = _sections.find(section);
2293 if (it != _sections.end()) {
2294 extra_sections.insert(section);
2295 it->second->process(*_is, line_num);
2299 } catch (FormatError& error) {
2300 error.line(line_num);
2301 error.file(_filename);
2305 for (Sections::iterator it = _sections.begin();
2306 it != _sections.end(); ++it) {
2307 if (extra_sections.find(it->first) == extra_sections.end()) {
2308 std::ostringstream os;
2309 os << "Cannot find section: " << it->first;
2310 throw FormatError(os.str());
2319 /// \brief Return a \ref SectionReader class
2321 /// This function just returns a \ref SectionReader class.
2322 /// \relates SectionReader
2323 inline SectionReader sectionReader(std::istream& is) {
2324 SectionReader tmp(is);
2328 /// \brief Return a \ref SectionReader class
2330 /// This function just returns a \ref SectionReader class.
2331 /// \relates SectionReader
2332 inline SectionReader sectionReader(const std::string& fn) {
2333 SectionReader tmp(fn);
2337 /// \brief Return a \ref SectionReader class
2339 /// This function just returns a \ref SectionReader class.
2340 /// \relates SectionReader
2341 inline SectionReader sectionReader(const char* fn) {
2342 SectionReader tmp(fn);
2346 /// \ingroup lemon_io
2348 /// \brief Reader for the contents of the \ref lgf-format "LGF" file
2350 /// This class can be used to read the sections, the map names and
2351 /// the attributes from a file. Usually, the LEMON programs know
2352 /// that, which type of graph, which maps and which attributes
2353 /// should be read from a file, but in general tools (like glemon)
2354 /// the contents of an LGF file should be guessed somehow. This class
2355 /// reads the graph and stores the appropriate information for
2356 /// reading the graph.
2359 /// LgfContents contents("graph.lgf");
2362 /// // Does it contain any node section and arc section?
2363 /// if (contents.nodeSectionNum() == 0 || contents.arcSectionNum()) {
2364 /// std::cerr << "Failure, cannot find graph." << std::endl;
2367 /// std::cout << "The name of the default node section: "
2368 /// << contents.nodeSection(0) << std::endl;
2369 /// std::cout << "The number of the arc maps: "
2370 /// << contents.arcMaps(0).size() << std::endl;
2371 /// std::cout << "The name of second arc map: "
2372 /// << contents.arcMaps(0)[1] << std::endl;
2380 std::vector<std::string> _node_sections;
2381 std::vector<std::string> _edge_sections;
2382 std::vector<std::string> _attribute_sections;
2383 std::vector<std::string> _extra_sections;
2385 std::vector<bool> _arc_sections;
2387 std::vector<std::vector<std::string> > _node_maps;
2388 std::vector<std::vector<std::string> > _edge_maps;
2390 std::vector<std::vector<std::string> > _attributes;
2394 std::istringstream line;
2398 /// \brief Constructor
2400 /// Construct an \e LGF contents reader, which reads from the given
2402 LgfContents(std::istream& is)
2403 : _is(&is), local_is(false) {}
2405 /// \brief Constructor
2407 /// Construct an \e LGF contents reader, which reads from the given
2409 LgfContents(const std::string& fn)
2410 : _is(new std::ifstream(fn.c_str())), local_is(true) {
2413 throw IoError("Cannot open file", fn);
2417 /// \brief Constructor
2419 /// Construct an \e LGF contents reader, which reads from the given
2421 LgfContents(const char* fn)
2422 : _is(new std::ifstream(fn)), local_is(true) {
2425 throw IoError("Cannot open file", fn);
2429 /// \brief Destructor
2431 if (local_is) delete _is;
2436 LgfContents(const LgfContents&);
2437 LgfContents& operator=(const LgfContents&);
2442 /// \name Node Sections
2445 /// \brief Gives back the number of node sections in the file.
2447 /// Gives back the number of node sections in the file.
2448 int nodeSectionNum() const {
2449 return _node_sections.size();
2452 /// \brief Returns the node section name at the given position.
2454 /// Returns the node section name at the given position.
2455 const std::string& nodeSection(int i) const {
2456 return _node_sections[i];
2459 /// \brief Gives back the node maps for the given section.
2461 /// Gives back the node maps for the given section.
2462 const std::vector<std::string>& nodeMapNames(int i) const {
2463 return _node_maps[i];
2468 /// \name Arc/Edge Sections
2471 /// \brief Gives back the number of arc/edge sections in the file.
2473 /// Gives back the number of arc/edge sections in the file.
2474 /// \note It is synonym of \c edgeSectionNum().
2475 int arcSectionNum() const {
2476 return _edge_sections.size();
2479 /// \brief Returns the arc/edge section name at the given position.
2481 /// Returns the arc/edge section name at the given position.
2482 /// \note It is synonym of \c edgeSection().
2483 const std::string& arcSection(int i) const {
2484 return _edge_sections[i];
2487 /// \brief Gives back the arc/edge maps for the given section.
2489 /// Gives back the arc/edge maps for the given section.
2490 /// \note It is synonym of \c edgeMapNames().
2491 const std::vector<std::string>& arcMapNames(int i) const {
2492 return _edge_maps[i];
2500 /// \brief Gives back the number of arc/edge sections in the file.
2502 /// Gives back the number of arc/edge sections in the file.
2503 /// \note It is synonym of \c arcSectionNum().
2504 int edgeSectionNum() const {
2505 return _edge_sections.size();
2508 /// \brief Returns the section name at the given position.
2510 /// Returns the section name at the given position.
2511 /// \note It is synonym of \c arcSection().
2512 const std::string& edgeSection(int i) const {
2513 return _edge_sections[i];
2516 /// \brief Gives back the edge maps for the given section.
2518 /// Gives back the edge maps for the given section.
2519 /// \note It is synonym of \c arcMapNames().
2520 const std::vector<std::string>& edgeMapNames(int i) const {
2521 return _edge_maps[i];
2526 /// \name Attribute Sections
2529 /// \brief Gives back the number of attribute sections in the file.
2531 /// Gives back the number of attribute sections in the file.
2532 int attributeSectionNum() const {
2533 return _attribute_sections.size();
2536 /// \brief Returns the attribute section name at the given position.
2538 /// Returns the attribute section name at the given position.
2539 const std::string& attributeSectionNames(int i) const {
2540 return _attribute_sections[i];
2543 /// \brief Gives back the attributes for the given section.
2545 /// Gives back the attributes for the given section.
2546 const std::vector<std::string>& attributes(int i) const {
2547 return _attributes[i];
2552 /// \name Extra Sections
2555 /// \brief Gives back the number of extra sections in the file.
2557 /// Gives back the number of extra sections in the file.
2558 int extraSectionNum() const {
2559 return _extra_sections.size();
2562 /// \brief Returns the extra section type at the given position.
2564 /// Returns the section type at the given position.
2565 const std::string& extraSection(int i) const {
2566 return _extra_sections[i];
2575 while(++line_num, std::getline(*_is, str)) {
2576 line.clear(); line.str(str);
2578 if (line >> std::ws >> c && c != '#') {
2586 bool readSuccess() {
2587 return static_cast<bool>(*_is);
2590 void skipSection() {
2592 while (readSuccess() && line >> c && c != '@') {
2595 if (readSuccess()) {
2600 void readMaps(std::vector<std::string>& maps) {
2602 if (!readLine() || !(line >> c) || c == '@') {
2603 if (readSuccess() && line) line.putback(c);
2608 while (_reader_bits::readToken(line, map)) {
2609 maps.push_back(map);
2613 void readAttributes(std::vector<std::string>& attrs) {
2616 while (readSuccess() && line >> c && c != '@') {
2619 _reader_bits::readToken(line, attr);
2620 attrs.push_back(attr);
2628 /// \name Execution of the Contents Reader
2631 /// \brief Starts the reading
2633 /// This function starts the reading.
2639 while (readSuccess()) {
2644 std::string section, caption;
2645 _reader_bits::readToken(line, section);
2646 _reader_bits::readToken(line, caption);
2648 if (section == "nodes") {
2649 _node_sections.push_back(caption);
2650 _node_maps.push_back(std::vector<std::string>());
2651 readMaps(_node_maps.back());
2652 readLine(); skipSection();
2653 } else if (section == "arcs" || section == "edges") {
2654 _edge_sections.push_back(caption);
2655 _arc_sections.push_back(section == "arcs");
2656 _edge_maps.push_back(std::vector<std::string>());
2657 readMaps(_edge_maps.back());
2658 readLine(); skipSection();
2659 } else if (section == "attributes") {
2660 _attribute_sections.push_back(caption);
2661 _attributes.push_back(std::vector<std::string>());
2662 readAttributes(_attributes.back());
2664 _extra_sections.push_back(section);
2665 readLine(); skipSection();