implicit_graph.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. // Copyright W.P. McNeill 2010.
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. #include <boost/concept/assert.hpp>
  6. #include <boost/graph/adjacency_iterator.hpp>
  7. #include <boost/graph/dijkstra_shortest_paths.hpp>
  8. #include <boost/graph/graph_concepts.hpp>
  9. #include <boost/graph/properties.hpp>
  10. #include <boost/iterator/counting_iterator.hpp>
  11. #include <boost/iterator/iterator_facade.hpp>
  12. #include <boost/lexical_cast.hpp>
  13. #include <iostream>
  14. #include <utility>
  15. /*
  16. This file defines a simple example of a read-only implicit weighted graph
  17. built using the Boost Graph Library. It can be used as a starting point for
  18. developers creating their own implicit graphs.
  19. The graph models the following concepts:
  20. Graph
  21. IncidenceGraph
  22. BidirectionalGraph
  23. AdjacencyGraph
  24. VertexListGraph
  25. EdgeListGraph
  26. AdjacencyMatrix
  27. ReadablePropertyGraph
  28. The graph defined here is a ring graph, a graph whose vertices are arranged in
  29. a ring so that each vertex has exactly two neighbors. For example, here is a
  30. ring graph with five nodes.
  31. 0
  32. / \
  33. 4 1
  34. | |
  35. 3 ---- 2
  36. The edges of this graph are undirected and each has a weight that is a
  37. function of its position in the graph.
  38. The vertices indexed are by integer and arranged sequentially so that each
  39. vertex i is adjacent to i-1 for i>0 and i+1 for i<n-1. Vertex 0 is also
  40. adjacent to vertex n-1. Edges are indexed by pairs of vertex indices.
  41. Various aspects of the graph are modeled by the following classes:
  42. ring_graph
  43. The graph class instantiated by a client. This defines types for the
  44. concepts that this graph models and keeps track of the number of vertices
  45. in the graph.
  46. ring_incident_edge_iterator
  47. This is an iterator that ranges over edges incident on a given vertex. The
  48. behavior of this iterator defines the ring topology. Other iterators that
  49. make reference to the graph structure are defined in terms of this one.
  50. edge_weight_map
  51. This defines a property map between edges and weights. Here edges have a
  52. weight equal to the average of their endpoint vertex indices, i.e. edge
  53. (2,3) has weight 2.5, edge (0,4) has weight 2, etc.
  54. boost::property_map<graph, boost::edge_weight_t>
  55. This tells Boost to associate the edges of the ring graph with the edge
  56. weight map.
  57. Along with these classes, the graph concepts are modeled by various valid
  58. expression functions defined below. This example also defines a
  59. get(boost::vertex_index_t, const ring_graph&) function which isn't part of a
  60. graph concept, but is used for Dijkstra search.
  61. Apart from graph, client code should not instantiate the model classes
  62. directly. Instead it should access them and their properties via
  63. graph_traits<...> and property_traits<...> lookups. For convenience,
  64. this example defines short names for all these properties that client code can
  65. use.
  66. */
  67. // Forward declarations
  68. class ring_graph;
  69. class ring_incident_edge_iterator;
  70. class ring_adjacency_iterator;
  71. class ring_edge_iterator;
  72. struct edge_weight_map;
  73. // ReadablePropertyGraph associated types
  74. namespace boost {
  75. template<>
  76. struct property_map< ring_graph, edge_weight_t > {
  77. typedef edge_weight_map type;
  78. typedef edge_weight_map const_type;
  79. };
  80. template<>
  81. struct property_map< const ring_graph, edge_weight_t > {
  82. typedef edge_weight_map type;
  83. typedef edge_weight_map const_type;
  84. };
  85. }
  86. // Tag values that specify the traversal type in graph::traversal_category.
  87. struct ring_traversal_catetory:
  88. virtual public boost::bidirectional_graph_tag,
  89. virtual public boost::adjacency_graph_tag,
  90. virtual public boost::vertex_list_graph_tag,
  91. virtual public boost::edge_list_graph_tag
  92. {};
  93. /*
  94. Undirected graph of vertices arranged in a ring shape.
  95. Vertices are indexed by integer, and edges connect vertices with consecutive
  96. indices. Vertex 0 is also adjacent to the vertex n-1.
  97. */
  98. class ring_graph {
  99. public:
  100. // Graph associated types
  101. typedef std::size_t vertex_descriptor;
  102. typedef boost::undirected_tag directed_category;
  103. typedef boost::disallow_parallel_edge_tag edge_parallel_category;
  104. typedef ring_traversal_catetory traversal_category;
  105. // IncidenceGraph associated types
  106. typedef std::pair<vertex_descriptor, vertex_descriptor> edge_descriptor;
  107. typedef ring_incident_edge_iterator out_edge_iterator;
  108. typedef std::size_t degree_size_type;
  109. // BidirectionalGraph associated types
  110. // Note that undirected graphs make no distinction between in- and out-
  111. // edges.
  112. typedef ring_incident_edge_iterator in_edge_iterator;
  113. // AdjacencyGraph associated types
  114. typedef ring_adjacency_iterator adjacency_iterator;
  115. // VertexListGraph associated types
  116. typedef boost::counting_iterator<vertex_descriptor> vertex_iterator;
  117. typedef std::size_t vertices_size_type;
  118. // EdgeListGraph associated types
  119. typedef ring_edge_iterator edge_iterator;
  120. typedef std::size_t edges_size_type;
  121. // This type is not part of a graph concept, but is used to return the
  122. // default vertex index map used by the Dijkstra search algorithm.
  123. typedef vertex_descriptor vertex_property_type;
  124. ring_graph(std::size_t n):m_n(n) {};
  125. std::size_t n() const {return m_n;}
  126. private:
  127. // The number of vertices in the graph.
  128. std::size_t m_n;
  129. };
  130. // Use these graph_traits parameterizations to refer to the associated
  131. // graph types.
  132. typedef boost::graph_traits<ring_graph>::vertex_descriptor vertex_descriptor;
  133. typedef boost::graph_traits<ring_graph>::edge_descriptor edge_descriptor;
  134. typedef boost::graph_traits<ring_graph>::out_edge_iterator out_edge_iterator;
  135. typedef boost::graph_traits<ring_graph>::in_edge_iterator in_edge_iterator;
  136. typedef boost::graph_traits<ring_graph>::adjacency_iterator adjacency_iterator;
  137. typedef boost::graph_traits<ring_graph>::degree_size_type degree_size_type;
  138. typedef boost::graph_traits<ring_graph>::vertex_iterator vertex_iterator;
  139. typedef boost::graph_traits<ring_graph>::vertices_size_type vertices_size_type;
  140. typedef boost::graph_traits<ring_graph>::edge_iterator edge_iterator;
  141. typedef boost::graph_traits<ring_graph>::edges_size_type edges_size_type;
  142. // Tag values passed to an iterator constructor to specify whether it should
  143. // be created at the start or the end of its range.
  144. struct iterator_position {};
  145. struct iterator_start:virtual public iterator_position {};
  146. struct iterator_end:virtual public iterator_position {};
  147. /*
  148. Iterator over edges incident on a vertex in a ring graph.
  149. For vertex i, this returns edge (i, i+1) and then edge (i, i-1), wrapping
  150. around the end of the ring as needed.
  151. It is implemented with the boost::iterator_adaptor class, adapting an
  152. offset into the dereference::ring_offset array.
  153. */
  154. class ring_incident_edge_iterator:public boost::iterator_adaptor <
  155. ring_incident_edge_iterator,
  156. boost::counting_iterator<std::size_t>,
  157. edge_descriptor,
  158. boost::use_default,
  159. edge_descriptor > {
  160. public:
  161. ring_incident_edge_iterator():
  162. ring_incident_edge_iterator::iterator_adaptor_(0),m_n(0),m_u(0) {};
  163. explicit ring_incident_edge_iterator(const ring_graph& g,
  164. vertex_descriptor u,
  165. iterator_start):
  166. ring_incident_edge_iterator::iterator_adaptor_(0),
  167. m_n(g.n()),m_u(u) {};
  168. explicit ring_incident_edge_iterator(const ring_graph& g,
  169. vertex_descriptor u,
  170. iterator_end):
  171. // A graph with one vertex only has a single self-loop. A graph with
  172. // two vertices has a single edge between them. All other graphs have
  173. // two edges per vertex.
  174. ring_incident_edge_iterator::iterator_adaptor_(g.n() > 2 ? 2:1),
  175. m_n(g.n()),m_u(u) {};
  176. private:
  177. friend class boost::iterator_core_access;
  178. edge_descriptor dereference() const {
  179. static const int ring_offset[] = {1, -1};
  180. vertex_descriptor v;
  181. std::size_t p = *this->base_reference();
  182. if (m_u == 0 && p == 1)
  183. v = m_n-1; // Vertex n-1 precedes vertex 0.
  184. else
  185. v = (m_u+ring_offset[p]) % m_n;
  186. return edge_descriptor(m_u, v);
  187. }
  188. std::size_t m_n; // Size of the graph
  189. vertex_descriptor m_u; // Vertex whose out edges are iterated
  190. };
  191. // IncidenceGraph valid expressions
  192. vertex_descriptor source(edge_descriptor e, const ring_graph&) {
  193. // The first vertex in the edge pair is the source.
  194. return e.first;
  195. }
  196. vertex_descriptor target(edge_descriptor e, const ring_graph&) {
  197. // The second vertex in the edge pair is the target.
  198. return e.second;
  199. }
  200. std::pair<out_edge_iterator, out_edge_iterator>
  201. out_edges(vertex_descriptor u, const ring_graph& g) {
  202. return std::pair<out_edge_iterator, out_edge_iterator>(
  203. out_edge_iterator(g, u, iterator_start()),
  204. out_edge_iterator(g, u, iterator_end()) );
  205. }
  206. degree_size_type out_degree(vertex_descriptor, const ring_graph&) {
  207. // All vertices in a ring graph have two neighbors.
  208. return 2;
  209. }
  210. // BidirectionalGraph valid expressions
  211. std::pair<in_edge_iterator, in_edge_iterator>
  212. in_edges(vertex_descriptor u, const ring_graph& g) {
  213. // The in-edges and out-edges are the same in an undirected graph.
  214. return out_edges(u, g);
  215. }
  216. degree_size_type in_degree(vertex_descriptor u, const ring_graph& g) {
  217. // The in-degree and out-degree are both equal to the number of incident
  218. // edges in an undirected graph.
  219. return out_degree(u, g);
  220. }
  221. degree_size_type degree(vertex_descriptor u, const ring_graph& g) {
  222. // The in-degree and out-degree are both equal to the number of incident
  223. // edges in an undirected graph.
  224. return out_degree(u, g);
  225. }
  226. /*
  227. Iterator over vertices adjacent to a given vertex.
  228. This iterates over the target vertices of all the incident edges.
  229. */
  230. class ring_adjacency_iterator:public boost::adjacency_iterator_generator<
  231. ring_graph,
  232. vertex_descriptor,
  233. out_edge_iterator>::type {
  234. // The parent class is an iterator_adpator that turns an iterator over
  235. // out edges into an iterator over adjacent vertices.
  236. typedef boost::adjacency_iterator_generator<
  237. ring_graph,
  238. vertex_descriptor,
  239. out_edge_iterator>::type parent_class;
  240. public:
  241. ring_adjacency_iterator() {};
  242. ring_adjacency_iterator(vertex_descriptor u,
  243. const ring_graph& g,
  244. iterator_start):
  245. parent_class(out_edge_iterator(g, u, iterator_start()), &g) {};
  246. ring_adjacency_iterator(vertex_descriptor u,
  247. const ring_graph& g,
  248. iterator_end):
  249. parent_class(out_edge_iterator(g, u, iterator_end()), &g) {};
  250. };
  251. // AdjacencyGraph valid expressions
  252. std::pair<adjacency_iterator, adjacency_iterator>
  253. adjacent_vertices(vertex_descriptor u, const ring_graph& g) {
  254. return std::pair<adjacency_iterator, adjacency_iterator>(
  255. adjacency_iterator(u, g, iterator_start()),
  256. adjacency_iterator(u, g, iterator_end()));
  257. }
  258. // VertexListGraph valid expressions
  259. vertices_size_type num_vertices(const ring_graph& g) {
  260. return g.n();
  261. };
  262. std::pair<vertex_iterator, vertex_iterator> vertices(const ring_graph& g) {
  263. return std::pair<vertex_iterator, vertex_iterator>(
  264. vertex_iterator(0), // The first iterator position
  265. vertex_iterator(num_vertices(g)) ); // The last iterator position
  266. }
  267. /*
  268. Iterator over edges in a ring graph.
  269. This object iterates over all the vertices in the graph, then for each
  270. vertex returns its first outgoing edge.
  271. It is implemented with the boost::iterator_adaptor class, because it is
  272. essentially a vertex_iterator with a customized deference operation.
  273. */
  274. class ring_edge_iterator:public boost::iterator_adaptor<
  275. ring_edge_iterator,
  276. vertex_iterator,
  277. edge_descriptor,
  278. boost::use_default,
  279. edge_descriptor > {
  280. public:
  281. ring_edge_iterator():
  282. ring_edge_iterator::iterator_adaptor_(0),m_g(NULL) {};
  283. explicit ring_edge_iterator(const ring_graph& g, iterator_start):
  284. ring_edge_iterator::iterator_adaptor_(vertices(g).first),m_g(&g) {};
  285. explicit ring_edge_iterator(const ring_graph& g, iterator_end):
  286. ring_edge_iterator::iterator_adaptor_(
  287. // Size 2 graphs have a single edge connecting the two vertices.
  288. g.n() == 2 ? ++(vertices(g).first) : vertices(g).second ),
  289. m_g(&g) {};
  290. private:
  291. friend class boost::iterator_core_access;
  292. edge_descriptor dereference() const {
  293. // The first element in the incident edge list of the current vertex.
  294. return *(out_edges(*this->base_reference(), *m_g).first);
  295. }
  296. // The graph being iterated over
  297. const ring_graph *m_g;
  298. };
  299. // EdgeListGraph valid expressions
  300. std::pair<edge_iterator, edge_iterator> edges(const ring_graph& g) {
  301. return std::pair<edge_iterator, edge_iterator>(
  302. ring_edge_iterator(g, iterator_start()),
  303. ring_edge_iterator(g, iterator_end()) );
  304. }
  305. edges_size_type num_edges(const ring_graph& g) {
  306. // There are as many edges as there are vertices, except for size 2
  307. // graphs, which have a single edge connecting the two vertices.
  308. return g.n() == 2 ? 1:g.n();
  309. }
  310. // AdjacencyMatrix valid expressions
  311. std::pair<edge_descriptor, bool>
  312. edge(vertex_descriptor u, vertex_descriptor v, const ring_graph& g) {
  313. if ((u == v + 1 || v == u + 1) &&
  314. u > 0 && u < num_vertices(g) && v > 0 && v < num_vertices(g))
  315. return std::pair<edge_descriptor, bool>(edge_descriptor(u, v), true);
  316. else
  317. return std::pair<edge_descriptor, bool>(edge_descriptor(), false);
  318. }
  319. /*
  320. Map from edges to weight values
  321. */
  322. struct edge_weight_map {
  323. typedef double value_type;
  324. typedef value_type reference;
  325. typedef edge_descriptor key_type;
  326. typedef boost::readable_property_map_tag category;
  327. // Edges have a weight equal to the average of their endpoint indexes.
  328. reference operator[](key_type e) const {
  329. return (e.first + e.second)/2.0;
  330. }
  331. };
  332. // Use these propety_map and property_traits parameterizations to refer to
  333. // the associated property map types.
  334. typedef boost::property_map<ring_graph,
  335. boost::edge_weight_t>::const_type
  336. const_edge_weight_map;
  337. typedef boost::property_traits<const_edge_weight_map>::reference
  338. edge_weight_map_value_type;
  339. typedef boost::property_traits<const_edge_weight_map>::key_type
  340. edge_weight_map_key;
  341. // PropertyMap valid expressions
  342. edge_weight_map_value_type
  343. get(const_edge_weight_map pmap, edge_weight_map_key e) {
  344. return pmap[e];
  345. }
  346. // ReadablePropertyGraph valid expressions
  347. const_edge_weight_map get(boost::edge_weight_t, const ring_graph&) {
  348. return const_edge_weight_map();
  349. }
  350. edge_weight_map_value_type get(boost::edge_weight_t tag,
  351. const ring_graph& g,
  352. edge_weight_map_key e) {
  353. return get(tag, g)[e];
  354. }
  355. // This expression is not part of a graph concept, but is used to return the
  356. // default vertex index map used by the Dijkstra search algorithm.
  357. boost::identity_property_map get(boost::vertex_index_t, const ring_graph&) {
  358. // The vertex descriptors are already unsigned integer indices, so just
  359. // return an identity map.
  360. return boost::identity_property_map();
  361. }
  362. // Print edges as (x, y)
  363. std::ostream& operator<<(std::ostream& output, const edge_descriptor& e) {
  364. return output << "(" << e.first << ", " << e.second << ")";
  365. }
  366. int main (int argc, char const *argv[]) {
  367. using namespace boost;
  368. // Check the concepts that graph models. This is included to demonstrate
  369. // how concept checking works, but is not required for a working program
  370. // since Boost algorithms do their own concept checking.
  371. BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<ring_graph> ));
  372. BOOST_CONCEPT_ASSERT(( AdjacencyGraphConcept<ring_graph> ));
  373. BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<ring_graph> ));
  374. BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<ring_graph> ));
  375. BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<ring_graph> ));
  376. BOOST_CONCEPT_ASSERT((
  377. ReadablePropertyMapConcept<const_edge_weight_map, edge_descriptor> ));
  378. BOOST_CONCEPT_ASSERT((
  379. ReadablePropertyGraphConcept<ring_graph, edge_descriptor, edge_weight_t> ));
  380. // Specify the size of the graph on the command line, or use a default size
  381. // of 5.
  382. std::size_t n = argc == 2 ? boost::lexical_cast<std::size_t>(argv[1]) : 5;
  383. // Create a small ring graph.
  384. ring_graph g(n);
  385. // Print the outgoing edges of all the vertices. For n=5 this will print:
  386. //
  387. // Vertices, outgoing edges, and adjacent vertices
  388. // Vertex 0: (0, 1) (0, 4) Adjacent vertices 1 4
  389. // Vertex 1: (1, 2) (1, 0) Adjacent vertices 2 0
  390. // Vertex 2: (2, 3) (2, 1) Adjacent vertices 3 1
  391. // Vertex 3: (3, 4) (3, 2) Adjacent vertices 4 2
  392. // Vertex 4: (4, 0) (4, 3) Adjacent vertices 0 3
  393. // 5 vertices
  394. std::cout << "Vertices, outgoing edges, and adjacent vertices" << std::endl;
  395. vertex_iterator vi, vi_end;
  396. for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; vi++) {
  397. vertex_descriptor u = *vi;
  398. std::cout << "Vertex " << u << ": ";
  399. // Adjacenct edges
  400. out_edge_iterator ei, ei_end;
  401. for (boost::tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ei++)
  402. std::cout << *ei << " ";
  403. std::cout << " Adjacent vertices ";
  404. // Adjacent vertices
  405. // Here we want our adjacency_iterator and not boost::adjacency_iterator.
  406. ::adjacency_iterator ai, ai_end;
  407. for (boost::tie(ai, ai_end) = adjacent_vertices(u, g); ai != ai_end; ai++) {
  408. std::cout << *ai << " ";
  409. }
  410. std::cout << std::endl;
  411. }
  412. std::cout << num_vertices(g) << " vertices" << std::endl << std::endl;
  413. // Print all the edges in the graph along with their weights. For n=5 this
  414. // will print:
  415. //
  416. // Edges and weights
  417. // (0, 1) weight 0.5
  418. // (1, 2) weight 1.5
  419. // (2, 3) weight 2.5
  420. // (3, 4) weight 3.5
  421. // (4, 0) weight 2
  422. // 5 edges
  423. std::cout << "Edges and weights" << std::endl;
  424. edge_iterator ei, ei_end;
  425. for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ei++) {
  426. edge_descriptor e = *ei;
  427. std::cout << e << " weight " << get(edge_weight, g, e) << std::endl;
  428. }
  429. std::cout << num_edges(g) << " edges" << std::endl;
  430. if (n>0) {
  431. std::cout << std::endl;
  432. // Do a Dijkstra search from vertex 0. For n=5 this will print:
  433. //
  434. // Dijkstra search from vertex 0
  435. // Vertex 0: parent 0, distance 0
  436. // Vertex 1: parent 0, distance 0.5
  437. // Vertex 2: parent 1, distance 2
  438. // Vertex 3: parent 2, distance 4.5
  439. // Vertex 4: parent 0, distance 2
  440. vertex_descriptor source = 0;
  441. std::vector<vertex_descriptor> pred(num_vertices(g));
  442. std::vector<edge_weight_map_value_type> dist(num_vertices(g));
  443. iterator_property_map<std::vector<vertex_descriptor>::iterator,
  444. property_map<ring_graph, vertex_index_t>::const_type>
  445. pred_pm(pred.begin(), get(vertex_index, g));
  446. iterator_property_map<std::vector<edge_weight_map_value_type>::iterator,
  447. property_map<ring_graph, vertex_index_t>::const_type>
  448. dist_pm(dist.begin(), get(vertex_index, g));
  449. dijkstra_shortest_paths(g, source,
  450. predecessor_map(pred_pm).
  451. distance_map(dist_pm) );
  452. std::cout << "Dijkstra search from vertex " << source << std::endl;
  453. for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) {
  454. vertex_descriptor u = *vi;
  455. std::cout << "Vertex " << u << ": "
  456. << "parent "<< pred[*vi] << ", "
  457. << "distance " << dist[u]
  458. << std::endl;
  459. }
  460. }
  461. return 0;
  462. }