Wrong member variable settings bug fix. (Ticket #95)
3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2008
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
21 ///\brief Lemon Graph Format reader.
24 #ifndef LEMON_LGF_READER_H
25 #define LEMON_LGF_READER_H
34 #include <lemon/assert.h>
35 #include <lemon/graph_utils.h>
37 #include <lemon/lgf_writer.h>
39 #include <lemon/concept_check.h>
40 #include <lemon/concepts/maps.h>
44 namespace _reader_bits {
46 template <typename Value>
47 struct DefaultConverter {
48 Value operator()(const std::string& str) {
49 std::istringstream is(str);
54 if (is >> std::ws >> c) {
55 throw DataFormatError("Remaining characters in token");
62 struct DefaultConverter<std::string> {
63 std::string operator()(const std::string& str) {
68 template <typename _Item>
69 class MapStorageBase {
75 virtual ~MapStorageBase() {}
77 virtual void set(const Item& item, const std::string& value) = 0;
81 template <typename _Item, typename _Map,
82 typename _Converter = DefaultConverter<typename _Map::Value> >
83 class MapStorage : public MapStorageBase<_Item> {
86 typedef _Converter Converter;
94 MapStorage(Map& map, const Converter& converter = Converter())
95 : _map(map), _converter(converter) {}
96 virtual ~MapStorage() {}
98 virtual void set(const Item& item ,const std::string& value) {
99 _map.set(item, _converter(value));
103 class ValueStorageBase {
105 ValueStorageBase() {}
106 virtual ~ValueStorageBase() {}
108 virtual void set(const std::string&) = 0;
111 template <typename _Value, typename _Converter = DefaultConverter<_Value> >
112 class ValueStorage : public ValueStorageBase {
114 typedef _Value Value;
115 typedef _Converter Converter;
119 Converter _converter;
122 ValueStorage(Value& value, const Converter& converter = Converter())
123 : _value(value), _converter(converter) {}
125 virtual void set(const std::string& value) {
126 _value = _converter(value);
130 template <typename Value>
131 struct MapLookUpConverter {
132 const std::map<std::string, Value>& _map;
134 MapLookUpConverter(const std::map<std::string, Value>& map)
137 Value operator()(const std::string& str) {
138 typename std::map<std::string, Value>::const_iterator it =
140 if (it == _map.end()) {
141 std::ostringstream msg;
142 msg << "Item not found: " << str;
143 throw DataFormatError(msg.str().c_str());
149 bool isWhiteSpace(char c) {
150 return c == ' ' || c == '\t' || c == '\v' ||
151 c == '\n' || c == '\r' || c == '\f';
155 return '0' <= c && c <='7';
158 int valueOct(char c) {
159 LEMON_ASSERT(isOct(c), "The character is not octal.");
164 return ('0' <= c && c <= '9') ||
165 ('a' <= c && c <= 'z') ||
166 ('A' <= c && c <= 'Z');
169 int valueHex(char c) {
170 LEMON_ASSERT(isHex(c), "The character is not hexadecimal.");
171 if ('0' <= c && c <= '9') return c - '0';
172 if ('a' <= c && c <= 'z') return c - 'a' + 10;
176 bool isIdentifierFirstChar(char c) {
177 return ('a' <= c && c <= 'z') ||
178 ('A' <= c && c <= 'Z') || c == '_';
181 bool isIdentifierChar(char c) {
182 return isIdentifierFirstChar(c) ||
183 ('0' <= c && c <= '9');
186 char readEscape(std::istream& is) {
189 throw DataFormatError("Escape format error");
217 if (!is.get(c) || !isHex(c))
218 throw DataFormatError("Escape format error");
219 else if (code = valueHex(c), !is.get(c) || !isHex(c)) is.putback(c);
220 else code = code * 16 + valueHex(c);
227 throw DataFormatError("Escape format error");
228 else if (code = valueOct(c), !is.get(c) || !isOct(c))
230 else if (code = code * 8 + valueOct(c), !is.get(c) || !isOct(c))
232 else code = code * 8 + valueOct(c);
238 std::istream& readToken(std::istream& is, std::string& str) {
239 std::ostringstream os;
248 while (is.get(c) && c != '\"') {
254 throw DataFormatError("Quoted format error");
257 while (is.get(c) && !isWhiteSpace(c)) {
274 /// \ingroup lemon_io
276 /// \brief LGF reader for directed graphs
278 /// This utility reads an \ref lgf-format "LGF" file.
280 /// The reading method does a batch processing. The user creates a
281 /// reader object, then various reading rules can be added to the
282 /// reader, and eventually the reading is executed with the \c run()
283 /// member function. A map reading rule can be added to the reader
284 /// with the \c nodeMap() or \c arcMap() members. An optional
285 /// converter parameter can also be added as a standard functor converting from
286 /// std::string to the value type of the map. If it is set, it will
287 /// determine how the tokens in the file should be is converted to the map's
288 /// value type. If the functor is not set, then a default conversion
289 /// will be used. One map can be read into multiple map objects at the
290 /// same time. The \c attribute(), \c node() and \c arc() functions
291 /// are used to add attribute reading rules.
294 /// DigraphReader<Digraph>(std::cin, digraph).
295 /// nodeMap("coordinates", coord_map).
296 /// arcMap("capacity", cap_map).
297 /// node("source", src).
298 /// node("target", trg).
299 /// attribute("caption", caption).
303 /// By default the reader uses the first section in the file of the
304 /// proper type. If a section has an optional name, then it can be
305 /// selected for reading by giving an optional name parameter to
306 /// the \c nodes(), \c arcs() or \c attributes()
309 /// The \c useNodes() and \c useArcs() functions are used to tell the reader
310 /// that the nodes or arcs should not be constructed (added to the
311 /// graph) during the reading, but instead the label map of the items
312 /// are given as a parameter of these functions. An
313 /// application of these function is multipass reading, which is
314 /// important if two \e \@arcs sections must be read from the
315 /// file. In this example the first phase would read the node set and one
316 /// of the arc sets, while the second phase would read the second arc
317 /// set into an \e ArcSet class (\c SmartArcSet or \c ListArcSet).
318 /// The previously read label node map should be passed to the \c
319 /// useNodes() functions. Another application of multipass reading when
320 /// paths are given as a node map or an arc map. It is impossible read this in
321 /// a single pass, because the arcs are not constructed when the node
323 template <typename _Digraph>
324 class DigraphReader {
327 typedef _Digraph Digraph;
328 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
338 std::string _nodes_caption;
339 std::string _arcs_caption;
340 std::string _attributes_caption;
342 typedef std::map<std::string, Node> NodeIndex;
343 NodeIndex _node_index;
344 typedef std::map<std::string, Arc> ArcIndex;
347 typedef std::vector<std::pair<std::string,
348 _reader_bits::MapStorageBase<Node>*> > NodeMaps;
351 typedef std::vector<std::pair<std::string,
352 _reader_bits::MapStorageBase<Arc>*> >ArcMaps;
355 typedef std::multimap<std::string, _reader_bits::ValueStorageBase*>
357 Attributes _attributes;
363 std::istringstream line;
367 /// \brief Constructor
369 /// Construct a directed graph reader, which reads from the given
371 DigraphReader(std::istream& is, Digraph& digraph)
372 : _is(&is), local_is(false), _digraph(digraph),
373 _use_nodes(false), _use_arcs(false) {}
375 /// \brief Constructor
377 /// Construct a directed graph reader, which reads from the given
379 DigraphReader(const std::string& fn, Digraph& digraph)
380 : _is(new std::ifstream(fn.c_str())), local_is(true), _digraph(digraph),
381 _use_nodes(false), _use_arcs(false) {}
383 /// \brief Constructor
385 /// Construct a directed graph reader, which reads from the given
387 DigraphReader(const char* fn, Digraph& digraph)
388 : _is(new std::ifstream(fn)), local_is(true), _digraph(digraph),
389 _use_nodes(false), _use_arcs(false) {}
391 /// \brief Copy constructor
393 /// The copy constructor transfers all data from the other reader,
394 /// therefore the copied reader will not be usable more.
395 DigraphReader(DigraphReader& other)
396 : _is(other._is), local_is(other.local_is), _digraph(other._digraph),
397 _use_nodes(other._use_nodes), _use_arcs(other._use_arcs) {
400 other.local_is = false;
402 _node_index.swap(other._node_index);
403 _arc_index.swap(other._arc_index);
405 _node_maps.swap(other._node_maps);
406 _arc_maps.swap(other._arc_maps);
407 _attributes.swap(other._attributes);
409 _nodes_caption = other._nodes_caption;
410 _arcs_caption = other._arcs_caption;
411 _attributes_caption = other._attributes_caption;
414 /// \brief Destructor
416 for (typename NodeMaps::iterator it = _node_maps.begin();
417 it != _node_maps.end(); ++it) {
421 for (typename ArcMaps::iterator it = _arc_maps.begin();
422 it != _arc_maps.end(); ++it) {
426 for (typename Attributes::iterator it = _attributes.begin();
427 it != _attributes.end(); ++it) {
439 DigraphReader& operator=(const DigraphReader&);
443 /// \name Reading rules
446 /// \brief Node map reading rule
448 /// Add a node map reading rule to the reader.
449 template <typename Map>
450 DigraphReader& nodeMap(const std::string& caption, Map& map) {
451 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
452 _reader_bits::MapStorageBase<Node>* storage =
453 new _reader_bits::MapStorage<Node, Map>(map);
454 _node_maps.push_back(std::make_pair(caption, storage));
458 /// \brief Node map reading rule
460 /// Add a node map reading rule with specialized converter to the
462 template <typename Map, typename Converter>
463 DigraphReader& nodeMap(const std::string& caption, Map& map,
464 const Converter& converter = Converter()) {
465 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
466 _reader_bits::MapStorageBase<Node>* storage =
467 new _reader_bits::MapStorage<Node, Map, Converter>(map, converter);
468 _node_maps.push_back(std::make_pair(caption, storage));
472 /// \brief Arc map reading rule
474 /// Add an arc map reading rule to the reader.
475 template <typename Map>
476 DigraphReader& arcMap(const std::string& caption, Map& map) {
477 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
478 _reader_bits::MapStorageBase<Arc>* storage =
479 new _reader_bits::MapStorage<Arc, Map>(map);
480 _arc_maps.push_back(std::make_pair(caption, storage));
484 /// \brief Arc map reading rule
486 /// Add an arc map reading rule with specialized converter to the
488 template <typename Map, typename Converter>
489 DigraphReader& arcMap(const std::string& caption, Map& map,
490 const Converter& converter = Converter()) {
491 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
492 _reader_bits::MapStorageBase<Arc>* storage =
493 new _reader_bits::MapStorage<Arc, Map, Converter>(map, converter);
494 _arc_maps.push_back(std::make_pair(caption, storage));
498 /// \brief Attribute reading rule
500 /// Add an attribute reading rule to the reader.
501 template <typename Value>
502 DigraphReader& attribute(const std::string& caption, Value& value) {
503 _reader_bits::ValueStorageBase* storage =
504 new _reader_bits::ValueStorage<Value>(value);
505 _attributes.insert(std::make_pair(caption, storage));
509 /// \brief Attribute reading rule
511 /// Add an attribute reading rule with specialized converter to the
513 template <typename Value, typename Converter>
514 DigraphReader& attribute(const std::string& caption, Value& value,
515 const Converter& converter = Converter()) {
516 _reader_bits::ValueStorageBase* storage =
517 new _reader_bits::ValueStorage<Value, Converter>(value, converter);
518 _attributes.insert(std::make_pair(caption, storage));
522 /// \brief Node reading rule
524 /// Add a node reading rule to reader.
525 DigraphReader& node(const std::string& caption, Node& node) {
526 typedef _reader_bits::MapLookUpConverter<Node> Converter;
527 Converter converter(_node_index);
528 _reader_bits::ValueStorageBase* storage =
529 new _reader_bits::ValueStorage<Node, Converter>(node, converter);
530 _attributes.insert(std::make_pair(caption, storage));
534 /// \brief Arc reading rule
536 /// Add an arc reading rule to reader.
537 DigraphReader& arc(const std::string& caption, Arc& arc) {
538 typedef _reader_bits::MapLookUpConverter<Arc> Converter;
539 Converter converter(_arc_index);
540 _reader_bits::ValueStorageBase* storage =
541 new _reader_bits::ValueStorage<Arc, Converter>(arc, converter);
542 _attributes.insert(std::make_pair(caption, storage));
548 /// \name Select section by name
551 /// \brief Set \c \@nodes section to be read
553 /// Set \c \@nodes section to be read
554 DigraphReader& nodes(const std::string& caption) {
555 _nodes_caption = caption;
559 /// \brief Set \c \@arcs section to be read
561 /// Set \c \@arcs section to be read
562 DigraphReader& arcs(const std::string& caption) {
563 _arcs_caption = caption;
567 /// \brief Set \c \@attributes section to be read
569 /// Set \c \@attributes section to be read
570 DigraphReader& attributes(const std::string& caption) {
571 _attributes_caption = caption;
577 /// \name Using previously constructed node or arc set
580 /// \brief Use previously constructed node set
582 /// Use previously constructed node set, and specify the node
584 template <typename Map>
585 DigraphReader& useNodes(const Map& map) {
586 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
587 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
589 _writer_bits::DefaultConverter<typename Map::Value> converter;
590 for (NodeIt n(_digraph); n != INVALID; ++n) {
591 _node_index.insert(std::make_pair(converter(map[n]), n));
596 /// \brief Use previously constructed node set
598 /// Use previously constructed node set, and specify the node
599 /// label map and a functor which converts the label map values to
601 template <typename Map, typename Converter>
602 DigraphReader& useNodes(const Map& map,
603 const Converter& converter = Converter()) {
604 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
605 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
607 for (NodeIt n(_digraph); n != INVALID; ++n) {
608 _node_index.insert(std::make_pair(converter(map[n]), n));
613 /// \brief Use previously constructed arc set
615 /// Use previously constructed arc set, and specify the arc
617 template <typename Map>
618 DigraphReader& useArcs(const Map& map) {
619 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
620 LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member");
622 _writer_bits::DefaultConverter<typename Map::Value> converter;
623 for (ArcIt a(_digraph); a != INVALID; ++a) {
624 _arc_index.insert(std::make_pair(converter(map[a]), a));
629 /// \brief Use previously constructed arc set
631 /// Use previously constructed arc set, and specify the arc
632 /// label map and a functor which converts the label map values to
634 template <typename Map, typename Converter>
635 DigraphReader& useArcs(const Map& map,
636 const Converter& converter = Converter()) {
637 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
638 LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member");
640 for (ArcIt a(_digraph); a != INVALID; ++a) {
641 _arc_index.insert(std::make_pair(converter(map[a]), a));
652 while(++line_num, std::getline(*_is, str)) {
653 line.clear(); line.str(str);
655 if (line >> std::ws >> c && c != '#') {
664 return static_cast<bool>(*_is);
669 while (readSuccess() && line >> c && c != '@') {
677 std::vector<int> map_index(_node_maps.size());
678 int map_num, label_index;
681 throw DataFormatError("Cannot find map captions");
684 std::map<std::string, int> maps;
688 while (_reader_bits::readToken(line, map)) {
689 if (maps.find(map) != maps.end()) {
690 std::ostringstream msg;
691 msg << "Multiple occurence of node map: " << map;
692 throw DataFormatError(msg.str().c_str());
694 maps.insert(std::make_pair(map, index));
698 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
699 std::map<std::string, int>::iterator jt =
700 maps.find(_node_maps[i].first);
701 if (jt == maps.end()) {
702 std::ostringstream msg;
703 msg << "Map not found in file: " << _node_maps[i].first;
704 throw DataFormatError(msg.str().c_str());
706 map_index[i] = jt->second;
710 std::map<std::string, int>::iterator jt = maps.find("label");
711 if (jt == maps.end())
712 throw DataFormatError("Label map not found in file");
713 label_index = jt->second;
715 map_num = maps.size();
719 while (readLine() && line >> c && c != '@') {
722 std::vector<std::string> tokens(map_num);
723 for (int i = 0; i < map_num; ++i) {
724 if (!_reader_bits::readToken(line, tokens[i])) {
725 std::ostringstream msg;
726 msg << "Column not found (" << i + 1 << ")";
727 throw DataFormatError(msg.str().c_str());
730 if (line >> std::ws >> c)
731 throw DataFormatError("Extra character on the end of line");
735 n = _digraph.addNode();
736 _node_index.insert(std::make_pair(tokens[label_index], n));
738 typename std::map<std::string, Node>::iterator it =
739 _node_index.find(tokens[label_index]);
740 if (it == _node_index.end()) {
741 std::ostringstream msg;
742 msg << "Node with label not found: " << tokens[label_index];
743 throw DataFormatError(msg.str().c_str());
748 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
749 _node_maps[i].second->set(n, tokens[map_index[i]]);
760 std::vector<int> map_index(_arc_maps.size());
761 int map_num, label_index;
764 throw DataFormatError("Cannot find map captions");
767 std::map<std::string, int> maps;
771 while (_reader_bits::readToken(line, map)) {
772 if (maps.find(map) != maps.end()) {
773 std::ostringstream msg;
774 msg << "Multiple occurence of arc map: " << map;
775 throw DataFormatError(msg.str().c_str());
777 maps.insert(std::make_pair(map, index));
781 for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) {
782 std::map<std::string, int>::iterator jt =
783 maps.find(_arc_maps[i].first);
784 if (jt == maps.end()) {
785 std::ostringstream msg;
786 msg << "Map not found in file: " << _arc_maps[i].first;
787 throw DataFormatError(msg.str().c_str());
789 map_index[i] = jt->second;
793 std::map<std::string, int>::iterator jt = maps.find("label");
794 if (jt == maps.end())
795 throw DataFormatError("Label map not found in file");
796 label_index = jt->second;
798 map_num = maps.size();
802 while (readLine() && line >> c && c != '@') {
805 std::string source_token;
806 std::string target_token;
808 if (!_reader_bits::readToken(line, source_token))
809 throw DataFormatError("Source not found");
811 if (!_reader_bits::readToken(line, target_token))
812 throw DataFormatError("Source not found");
814 std::vector<std::string> tokens(map_num);
815 for (int i = 0; i < map_num; ++i) {
816 if (!_reader_bits::readToken(line, tokens[i])) {
817 std::ostringstream msg;
818 msg << "Column not found (" << i + 1 << ")";
819 throw DataFormatError(msg.str().c_str());
822 if (line >> std::ws >> c)
823 throw DataFormatError("Extra character on the end of line");
828 typename NodeIndex::iterator it;
830 it = _node_index.find(source_token);
831 if (it == _node_index.end()) {
832 std::ostringstream msg;
833 msg << "Item not found: " << source_token;
834 throw DataFormatError(msg.str().c_str());
836 Node source = it->second;
838 it = _node_index.find(target_token);
839 if (it == _node_index.end()) {
840 std::ostringstream msg;
841 msg << "Item not found: " << target_token;
842 throw DataFormatError(msg.str().c_str());
844 Node target = it->second;
846 a = _digraph.addArc(source, target);
847 _arc_index.insert(std::make_pair(tokens[label_index], a));
849 typename std::map<std::string, Arc>::iterator it =
850 _arc_index.find(tokens[label_index]);
851 if (it == _arc_index.end()) {
852 std::ostringstream msg;
853 msg << "Arc with label not found: " << tokens[label_index];
854 throw DataFormatError(msg.str().c_str());
859 for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) {
860 _arc_maps[i].second->set(a, tokens[map_index[i]]);
869 void readAttributes() {
871 std::set<std::string> read_attr;
874 while (readLine() && line >> c && c != '@') {
877 std::string attr, token;
878 if (!_reader_bits::readToken(line, attr))
879 throw DataFormatError("Attribute name not found");
880 if (!_reader_bits::readToken(line, token))
881 throw DataFormatError("Attribute value not found");
883 throw DataFormatError("Extra character on the end of line");
886 std::set<std::string>::iterator it = read_attr.find(attr);
887 if (it != read_attr.end()) {
888 std::ostringstream msg;
889 msg << "Multiple occurence of attribute " << attr;
890 throw DataFormatError(msg.str().c_str());
892 read_attr.insert(attr);
896 typename Attributes::iterator it = _attributes.lower_bound(attr);
897 while (it != _attributes.end() && it->first == attr) {
898 it->second->set(token);
907 for (typename Attributes::iterator it = _attributes.begin();
908 it != _attributes.end(); ++it) {
909 if (read_attr.find(it->first) == read_attr.end()) {
910 std::ostringstream msg;
911 msg << "Attribute not found in file: " << it->first;
912 throw DataFormatError(msg.str().c_str());
919 /// \name Execution of the reader
922 /// \brief Start the batch processing
924 /// This function starts the batch processing
927 LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
929 bool nodes_done = false;
930 bool arcs_done = false;
931 bool attributes_done = false;
936 while (readSuccess()) {
940 std::string section, caption;
942 _reader_bits::readToken(line, section);
943 _reader_bits::readToken(line, caption);
946 throw DataFormatError("Extra character on the end of line");
948 if (section == "nodes" && !nodes_done) {
949 if (_nodes_caption.empty() || _nodes_caption == caption) {
953 } else if ((section == "arcs" || section == "edges") &&
955 if (_arcs_caption.empty() || _arcs_caption == caption) {
959 } else if (section == "attributes" && !attributes_done) {
960 if (_attributes_caption.empty() || _attributes_caption == caption) {
962 attributes_done = true;
968 } catch (DataFormatError& error) {
969 error.line(line_num);
975 throw DataFormatError("Section @nodes not found");
979 throw DataFormatError("Section @arcs not found");
982 if (!attributes_done && !_attributes.empty()) {
983 throw DataFormatError("Section @attributes not found");
992 /// \relates DigraphReader
993 template <typename Digraph>
994 DigraphReader<Digraph> digraphReader(std::istream& is, Digraph& digraph) {
995 return DigraphReader<Digraph>(is, digraph);
998 /// \relates DigraphReader
999 template <typename Digraph>
1000 DigraphReader<Digraph> digraphReader(const std::string& fn,
1002 return DigraphReader<Digraph>(fn, digraph);
1005 /// \relates DigraphReader
1006 template <typename Digraph>
1007 DigraphReader<Digraph> digraphReader(const char* fn, Digraph& digraph) {
1008 return DigraphReader<Digraph>(fn, digraph);