2 //=======================================================================
4 // Author: Matyas W Egyhazy
6 // Distributed under the Boost Software License, Version 1.0. (See
7 // accompanying file LICENSE_1_0.txt or copy at
8 // http://www.boost.org/LICENSE_1_0.txt)
9 //=======================================================================
11 #ifndef BOOST_GRAPH_METRIC_TSP_APPROX_HPP
12 #define BOOST_GRAPH_METRIC_TSP_APPROX_HPP
15 // Generates an approximate tour solution for the traveling salesperson
16 // problem in polynomial time. The current algorithm guarantees a tour with a
17 // length at most as long as 2x optimal solution. The graph should have
18 // 'natural' (metric) weights such that the triangle inequality is maintained.
19 // Graphs must be fully interconnected.
22 // There are a couple of improvements that could be made.
23 // 1) Change implementation to lower uppper bound Christofides heuristic
24 // 2) Implement a less restrictive TSP heuristic (one that does not rely on
25 // triangle inequality).
26 // 3) Determine if the algorithm can be implemented without creating a new
31 #include <boost/shared_ptr.hpp>
32 #include <boost/concept_check.hpp>
33 #include <boost/graph/graph_traits.hpp>
34 #include <boost/graph/graph_as_tree.hpp>
35 #include <boost/graph/adjacency_list.hpp>
36 #include <boost/graph/prim_minimum_spanning_tree.hpp>
37 #include <boost/graph/lookup_edge.hpp>
38 #include <boost/throw_exception.hpp>
42 // Define a concept for the concept-checking library.
43 template < typename Visitor, typename Graph > struct TSPVertexVisitorConcept
49 typedef typename graph_traits< Graph >::vertex_descriptor Vertex;
51 BOOST_CONCEPT_USAGE(TSPVertexVisitorConcept)
53 Visitor vis(vis_); // require copy construction
55 Vertex v(*vertices(g).first);
56 vis.visit_vertex(v, g); // require visit_vertex
60 // Tree visitor that keeps track of a preorder traversal of a tree
61 // TODO: Consider migrating this to the graph_as_tree header.
62 // TODO: Parameterize the underlying stores so it doesn't have to be a vector.
63 template < typename Node, typename Tree > class PreorderTraverser
66 std::vector< Node >& path_;
69 typedef typename std::vector< Node >::const_iterator const_iterator;
71 PreorderTraverser(std::vector< Node >& p) : path_(p) {}
73 void preorder(Node n, const Tree&) { path_.push_back(n); }
75 void inorder(Node, const Tree&) const {}
76 void postorder(Node, const Tree&) const {}
78 const_iterator begin() const { return path_.begin(); }
79 const_iterator end() const { return path_.end(); }
82 // Forward declarations
83 template < typename > class tsp_tour_visitor;
84 template < typename, typename, typename, typename > class tsp_tour_len_visitor;
86 template < typename VertexListGraph, typename OutputIterator >
87 void metric_tsp_approx_tour(VertexListGraph& g, OutputIterator o)
89 metric_tsp_approx_from_vertex(g, *vertices(g).first, get(edge_weight, g),
90 get(vertex_index, g), tsp_tour_visitor< OutputIterator >(o));
93 template < typename VertexListGraph, typename WeightMap,
94 typename OutputIterator >
95 void metric_tsp_approx_tour(VertexListGraph& g, WeightMap w, OutputIterator o)
97 metric_tsp_approx_from_vertex(
98 g, *vertices(g).first, w, tsp_tour_visitor< OutputIterator >(o));
101 template < typename VertexListGraph, typename OutputIterator >
102 void metric_tsp_approx_tour_from_vertex(VertexListGraph& g,
103 typename graph_traits< VertexListGraph >::vertex_descriptor start,
106 metric_tsp_approx_from_vertex(g, start, get(edge_weight, g),
107 get(vertex_index, g), tsp_tour_visitor< OutputIterator >(o));
110 template < typename VertexListGraph, typename WeightMap,
111 typename OutputIterator >
112 void metric_tsp_approx_tour_from_vertex(VertexListGraph& g,
113 typename graph_traits< VertexListGraph >::vertex_descriptor start,
114 WeightMap w, OutputIterator o)
116 metric_tsp_approx_from_vertex(g, start, w, get(vertex_index, g),
117 tsp_tour_visitor< OutputIterator >(o));
120 template < typename VertexListGraph, typename TSPVertexVisitor >
121 void metric_tsp_approx(VertexListGraph& g, TSPVertexVisitor vis)
123 metric_tsp_approx_from_vertex(
124 g, *vertices(g).first, get(edge_weight, g), get(vertex_index, g), vis);
127 template < typename VertexListGraph, typename Weightmap,
128 typename VertexIndexMap, typename TSPVertexVisitor >
129 void metric_tsp_approx(VertexListGraph& g, Weightmap w, TSPVertexVisitor vis)
131 metric_tsp_approx_from_vertex(
132 g, *vertices(g).first, w, get(vertex_index, g), vis);
135 template < typename VertexListGraph, typename WeightMap,
136 typename VertexIndexMap, typename TSPVertexVisitor >
137 void metric_tsp_approx(
138 VertexListGraph& g, WeightMap w, VertexIndexMap id, TSPVertexVisitor vis)
140 metric_tsp_approx_from_vertex(g, *vertices(g).first, w, id, vis);
143 template < typename VertexListGraph, typename WeightMap,
144 typename TSPVertexVisitor >
145 void metric_tsp_approx_from_vertex(VertexListGraph& g,
146 typename graph_traits< VertexListGraph >::vertex_descriptor start,
147 WeightMap w, TSPVertexVisitor vis)
149 metric_tsp_approx_from_vertex(g, start, w, get(vertex_index, g), vis);
152 template < typename VertexListGraph, typename WeightMap,
153 typename VertexIndexMap, typename TSPVertexVisitor >
154 void metric_tsp_approx_from_vertex(const VertexListGraph& g,
155 typename graph_traits< VertexListGraph >::vertex_descriptor start,
156 WeightMap weightmap, VertexIndexMap indexmap, TSPVertexVisitor vis)
158 using namespace boost;
161 BOOST_CONCEPT_ASSERT((VertexListGraphConcept< VertexListGraph >));
162 BOOST_CONCEPT_ASSERT(
163 (TSPVertexVisitorConcept< TSPVertexVisitor, VertexListGraph >));
165 // Types related to the input graph (GVertex is a template parameter).
166 typedef typename graph_traits< VertexListGraph >::vertex_descriptor GVertex;
167 typedef typename graph_traits< VertexListGraph >::vertex_iterator GVItr;
169 // We build a custom graph in this algorithm.
170 typedef adjacency_list< vecS, vecS, directedS, no_property, no_property >
172 typedef graph_traits< MSTImpl >::vertex_descriptor Vertex;
173 typedef graph_traits< MSTImpl >::vertex_iterator VItr;
175 // And then re-cast it as a tree.
176 typedef iterator_property_map< vector< Vertex >::iterator,
177 property_map< MSTImpl, vertex_index_t >::type >
179 typedef graph_as_tree< MSTImpl, ParentMap > Tree;
180 typedef tree_traits< Tree >::node_descriptor Node;
182 // A predecessor map.
183 typedef vector< GVertex > PredMap;
184 typedef iterator_property_map< typename PredMap::iterator, VertexIndexMap >
187 PredMap preds(num_vertices(g));
188 PredPMap pred_pmap(preds.begin(), indexmap);
190 // Compute a spanning tree over the in put g.
191 prim_minimum_spanning_tree(g, pred_pmap,
192 root_vertex(start).vertex_index_map(indexmap).weight_map(weightmap));
194 // Build a MST using the predecessor map from prim mst
195 MSTImpl mst(num_vertices(g));
197 pair< VItr, VItr > mst_verts(vertices(mst));
198 for (typename PredMap::iterator vi(preds.begin()); vi != preds.end();
201 if (indexmap[*vi] != cnt)
203 add_edge(*next(mst_verts.first, indexmap[*vi]),
204 *next(mst_verts.first, cnt), mst);
208 // Build a tree abstraction over the MST.
209 vector< Vertex > parent(num_vertices(mst));
210 Tree t(mst, *vertices(mst).first,
211 make_iterator_property_map(parent.begin(), get(vertex_index, mst)));
213 // Create tour using a preorder traversal of the mst
215 PreorderTraverser< Node, Tree > tvis(tour);
216 traverse_tree(indexmap[start], t, tvis);
218 pair< GVItr, GVItr > g_verts(vertices(g));
219 for (PreorderTraverser< Node, Tree >::const_iterator curr(tvis.begin());
220 curr != tvis.end(); ++curr)
222 // TODO: This is will be O(n^2) if vertex storage of g != vecS.
223 GVertex v = *next(g_verts.first, get(vertex_index, mst)[*curr]);
224 vis.visit_vertex(v, g);
227 // Connect back to the start of the tour
228 vis.visit_vertex(start, g);
231 // Default tsp tour visitor that puts the tour in an OutputIterator
232 template < typename OutItr > class tsp_tour_visitor
237 tsp_tour_visitor(OutItr itr) : itr_(itr) {}
239 template < typename Vertex, typename Graph >
240 void visit_vertex(Vertex v, const Graph&)
242 BOOST_CONCEPT_ASSERT((OutputIterator< OutItr, Vertex >));
247 // Tsp tour visitor that adds the total tour length.
248 template < typename Graph, typename WeightMap, typename OutIter,
250 class tsp_tour_len_visitor
252 typedef typename graph_traits< Graph >::vertex_descriptor Vertex;
253 BOOST_CONCEPT_ASSERT((OutputIterator< OutIter, Vertex >));
260 // Helper function for getting the null vertex.
261 Vertex null() { return graph_traits< Graph >::null_vertex(); }
264 tsp_tour_len_visitor(Graph const&, OutIter iter, Length& l, WeightMap& map)
265 : iter_(iter), tourlen_(l), wmap_(map), previous_(null())
269 void visit_vertex(Vertex v, const Graph& g)
271 typedef typename graph_traits< Graph >::edge_descriptor Edge;
273 // If it is not the start, then there is a
275 if (previous_ != null())
277 // NOTE: For non-adjacency matrix graphs g, this bit of code
278 // will be linear in the degree of previous_ or v. A better
279 // solution would be to visit edges of the graph, but that
280 // would require revisiting the core algorithm.
283 boost::tie(e, found) = lookup_edge(previous_, v, g);
286 BOOST_THROW_EXCEPTION(not_complete());
289 tourlen_ += wmap_[e];
297 // Object generator(s)
298 template < typename OutIter >
299 inline tsp_tour_visitor< OutIter > make_tsp_tour_visitor(OutIter iter)
301 return tsp_tour_visitor< OutIter >(iter);
304 template < typename Graph, typename WeightMap, typename OutIter,
306 inline tsp_tour_len_visitor< Graph, WeightMap, OutIter, Length >
307 make_tsp_tour_len_visitor(
308 Graph const& g, OutIter iter, Length& l, WeightMap map)
310 return tsp_tour_len_visitor< Graph, WeightMap, OutIter, Length >(
316 #endif // BOOST_GRAPH_METRIC_TSP_APPROX_HPP