KShortestPaths2.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. //
  2. // Created by wrede on 15.06.16.
  3. //
  4. #include <boost/graph/copy.hpp>
  5. #include <boost/graph/bellman_ford_shortest_paths.hpp>
  6. #include <boost/graph/dijkstra_shortest_paths.hpp>
  7. #include "KShortestPaths2.h"
  8. #include "../util/Logger.h"
  9. #include "../util/FileIO.h"
  10. namespace algo
  11. {
  12. void KShortestPaths2::CreateCopy()
  13. {
  14. util::Logger::LogDebug("create copy");
  15. // Clear all previous data
  16. graph_copy_.clear();
  17. orig_to_copy_.clear();
  18. copy_to_orig_.clear();
  19. in_to_out_.clear();
  20. out_to_in_.clear();
  21. // Copy the graph and store the vertex map temporarily
  22. std::vector<Vertex> original_to_copy_vector(boost::num_vertices(graph_orig_));
  23. VertexVertexMap temp_map(original_to_copy_vector.begin());
  24. boost::copy_graph(graph_orig_, graph_copy_, boost::orig_to_copy(temp_map));
  25. // Copy the vertex map into the two persistent maps, one for each
  26. // mapping direction
  27. boost::graph_traits<DirectedGraph>::vertex_iterator vi, vi_end;
  28. for (boost::tie(vi, vi_end) = boost::vertices(graph_orig_);
  29. vi != vi_end; ++vi)
  30. {
  31. Vertex v_original = (*vi);
  32. Vertex v_copy = temp_map[v_original];
  33. orig_to_copy_[v_original] = v_copy;
  34. copy_to_orig_[v_copy] = v_original;
  35. }
  36. // Split every vertex in the copied graph
  37. for (boost::tie(vi, vi_end) = boost::vertices(graph_orig_);
  38. vi != vi_end; ++vi)
  39. {
  40. Vertex v_orig = *vi;
  41. Vertex v_copy_in = orig_to_copy_[v_orig];
  42. Vertex v_copy_out = boost::add_vertex(graph_copy_);
  43. in_to_out_[v_copy_in] = v_copy_out;
  44. out_to_in_[v_copy_out] = v_copy_in;
  45. copy_to_orig_[v_copy_out] = v_orig;
  46. }
  47. }
  48. void KShortestPaths2::UpdateEdges()
  49. {
  50. // Remove the old edges, needs to be done without any iterator since
  51. // the removal invalidates any iterators
  52. for (auto edge : edges_to_remove_)
  53. {
  54. boost::remove_edge(edge.first, edge.second, graph_copy_);
  55. }
  56. edges_to_remove_.clear();
  57. // Add the new edges, needs to be done without any iterator since
  58. // the addition invalidates any iterators
  59. for (auto edge : edges_to_add_)
  60. {
  61. boost::add_edge(edge.first.first, edge.first.second,
  62. edge.second, graph_copy_);
  63. }
  64. edges_to_add_.clear();
  65. }
  66. void KShortestPaths2::QueueAddEdge(Vertex source, Vertex target, double weight)
  67. {
  68. edges_to_add_.push_back(
  69. std::pair<std::pair<Vertex, Vertex>, double>(
  70. std::pair<Vertex, Vertex>(source, target), weight));
  71. }
  72. void KShortestPaths2::QueueRemoveEdge(Vertex source, Vertex target)
  73. {
  74. edges_to_remove_.push_back(std::pair<Vertex, Vertex>(source, target));
  75. }
  76. void KShortestPaths2::QueueCopyEdges()
  77. {
  78. EdgeWeightMap weights = boost::get(boost::edge_weight, graph_orig_);
  79. boost::graph_traits<DirectedGraph>::edge_iterator ei, ei_end;
  80. for (boost::tie(ei, ei_end) = boost::edges(graph_orig_);
  81. ei != ei_end; ++ei)
  82. {
  83. Vertex s_orig = boost::source(*ei, graph_orig_);
  84. Vertex t_orig = boost::target(*ei, graph_orig_);
  85. Vertex s_copy = orig_to_copy_[s_orig];
  86. Vertex t_copy = orig_to_copy_[t_orig];
  87. double weight = weights[*ei];
  88. QueueAddEdge(s_copy, t_copy, weight);
  89. }
  90. }
  91. void KShortestPaths2::QueueRemoveAll()
  92. {
  93. boost::graph_traits<DirectedGraph>::edge_iterator ei, ei_end;
  94. for (boost::tie(ei, ei_end) = boost::edges(graph_copy_);
  95. ei != ei_end; ++ei)
  96. {
  97. Vertex s_copy = boost::source(*ei, graph_copy_);
  98. Vertex t_copy = boost::target(*ei, graph_copy_);
  99. QueueRemoveEdge(s_copy, t_copy);
  100. }
  101. }
  102. MultiPredecessorMap KShortestPaths2::Run(DirectedGraph& graph_orig,
  103. Vertex source, Vertex sink,
  104. size_t iterations)
  105. {
  106. // Clear all previous data
  107. edges_to_add_.clear();
  108. edges_to_remove_.clear();
  109. i_distances_.clear();
  110. i_paths_.clear();
  111. graph_orig_ = graph_orig;
  112. source_ = source;
  113. sink_ = sink;
  114. CreateCopy();
  115. FindAndAugment(0);
  116. for (size_t i = 0; i < iterations; ++i)
  117. {
  118. util::Logger::LogDebug("ksp iteration: " + std::to_string(i));
  119. if (i > 0)
  120. {
  121. if (PathCosts(i) >= PathCosts(i - 1))
  122. {
  123. return i_paths_[i];
  124. }
  125. }
  126. ExtendGraph(i);
  127. i > 0 ? TransformEdges(i - 1) : TransformEdges(0);
  128. FindAndAugment(i + 1);
  129. Interlace(i + 1);
  130. }
  131. return i_paths_[iterations];
  132. }
  133. void KShortestPaths2::ExtendGraph(size_t iteration)
  134. {
  135. util::Logger::LogDebug("extend graph iteration: " + std::to_string(iteration));
  136. // Clear all previous working data
  137. util::Logger::LogDebug("remove all");
  138. QueueRemoveAll();
  139. util::Logger::LogDebug("copy all");
  140. QueueCopyEdges();
  141. util::Logger::LogDebug("update edges");
  142. UpdateEdges();
  143. util::Logger::LogDebug("iterate vertices");
  144. MultiPredecessorMap& paths = i_paths_[iteration];
  145. boost::graph_traits<DirectedGraph>::out_edge_iterator oei, oei_end;
  146. boost::graph_traits<DirectedGraph>::edge_iterator ei, ei_end;
  147. boost::graph_traits<DirectedGraph>::vertex_iterator vi, vi_end;
  148. EdgeWeightMap weights = boost::get(boost::edge_weight, graph_copy_);
  149. // Iterate all vertices within the original graph
  150. for (boost::tie(vi, vi_end) = boost::vertices(graph_orig_);
  151. vi != vi_end; ++vi)
  152. {
  153. Vertex v_orig = *vi;
  154. // Ignore vertices off the paths, the source and the sink
  155. if (paths.count(v_orig) == 0 || v_orig == source_ || v_orig == sink_)
  156. {
  157. continue;
  158. }
  159. Vertex v_copy_in = orig_to_copy_[v_orig];
  160. Vertex v_copy_out = in_to_out_[v_copy_in];
  161. // Iterate all input vertices
  162. for (boost::tie(oei, oei_end) = boost::out_edges(v_copy_in, graph_copy_);
  163. oei != oei_end; ++oei)
  164. {
  165. // Copy the output edges to the output vertices
  166. QueueAddEdge(v_copy_out,
  167. boost::target(*oei, graph_copy_),
  168. weights[*oei]);
  169. // Remove the old output edge
  170. QueueRemoveEdge(v_copy_in, boost::target(*oei, graph_copy_));
  171. }
  172. // Create auxiliary edge
  173. // Is already inverted, because it will not be iterated later
  174. QueueAddEdge(v_copy_out, v_copy_in, 0.0);
  175. }
  176. util::Logger::LogDebug("update edges");
  177. UpdateEdges();
  178. util::Logger::LogDebug("iterate edges");
  179. // Iterate all edges within the copied graph
  180. weights = boost::get(boost::edge_weight, graph_copy_);
  181. for (boost::tie(ei, ei_end) = boost::edges(graph_copy_);
  182. ei != ei_end; ++ei)
  183. {
  184. Vertex s_copy = boost::source(*ei, graph_copy_);
  185. Vertex t_copy = boost::target(*ei, graph_copy_);
  186. Vertex s_orig = copy_to_orig_[s_copy];
  187. Vertex t_orig = copy_to_orig_[t_copy];
  188. double weight = weights[*ei];
  189. // If the edge is part of the paths
  190. if (paths.count(t_orig) > 0 && paths[t_orig].count(s_orig) > 0)
  191. {
  192. // Add the edge with direction and weight inverted
  193. QueueAddEdge(t_copy, s_copy, -weight);
  194. // Remove the old edge
  195. QueueRemoveEdge(s_copy, t_copy);
  196. }
  197. }
  198. util::Logger::LogDebug("update edges");
  199. UpdateEdges();
  200. }
  201. void KShortestPaths2::TransformEdges(size_t iteration)
  202. {
  203. util::Logger::LogDebug("transform edges iteration: " + std::to_string(iteration));
  204. std::unordered_map<Vertex, double>& distances = i_distances_[iteration];
  205. EdgeWeightMap weights = boost::get(boost::edge_weight, graph_copy_);
  206. boost::graph_traits<DirectedGraph>::edge_iterator ei, ei_end;
  207. for (boost::tie(ei, ei_end) = boost::edges(graph_copy_);
  208. ei != ei_end; ++ei)
  209. {
  210. Vertex s_copy = boost::source(*ei, graph_copy_);
  211. Vertex t_copy = boost::target(*ei, graph_copy_);
  212. // Transform the edge weights with the distances calculated in
  213. // the specified path finding iteration
  214. if (distances.count(s_copy) > 0 && distances.count(t_copy) > 0)
  215. {
  216. //TODO set all edges to source to zero (experimental)
  217. if (t_copy == orig_to_copy_[source_]) {
  218. weights[*ei] = 0.0;
  219. continue;
  220. }
  221. // check if the vertex was found in previous iterations
  222. if (distances[s_copy] == std::numeric_limits<double>::max() ||
  223. distances[t_copy] == std::numeric_limits<double>::max())
  224. {
  225. weights[*ei] = std::numeric_limits<double>::infinity();
  226. }
  227. else
  228. {
  229. weights[*ei] += distances[s_copy] - distances[t_copy];
  230. }
  231. }
  232. // Correct rounding errors
  233. if (weights[*ei] >= -0.0000001 && weights[*ei] <= 0.0000001)
  234. {
  235. weights[*ei] = 0.0;
  236. }
  237. //TODO debug output (experimental)
  238. if (weights[*ei] < 0.0)
  239. {
  240. util::Logger::LogDebug(std::to_string(s_copy)
  241. + " -> " + std::to_string(weights[*ei])
  242. + " -> " + std::to_string(t_copy));
  243. }
  244. }
  245. // util::FileIO::WriteCSVMatlab(graph_copy_, "/home/wrede/Dokumente/graph_t.csv");
  246. }
  247. void KShortestPaths2::FindAndAugment(size_t iteration)
  248. {
  249. util::Logger::LogDebug("find and augment iteration: " + std::to_string(iteration));
  250. // Add new path maps until the needed iteration is reached
  251. while (i_paths_.size() < (iteration + 1))
  252. {
  253. i_paths_.push_back(MultiPredecessorMap());
  254. }
  255. // Add new distance maps until the needed iteration is reached
  256. while (i_distances_.size() < (iteration + 1))
  257. {
  258. i_distances_.push_back(std::unordered_map<Vertex, double>());
  259. }
  260. // Only copy old paths if old paths exist
  261. if (iteration > 0)
  262. {
  263. // Copy the old paths
  264. for (auto it = i_paths_[iteration - 1].begin();
  265. it != i_paths_[iteration - 1].end(); ++it)
  266. {
  267. i_paths_[iteration][it->first] = it->second;
  268. }
  269. }
  270. // Prepare variables for path finding
  271. size_t graph_size = boost::num_vertices(graph_copy_);
  272. Vertex root_vertex = orig_to_copy_[source_];
  273. std::vector<Vertex> pred_list(graph_size);
  274. std::vector<double> dist_list(graph_size);
  275. VertexIndexMap graph_indices = boost::get(boost::vertex_index,
  276. graph_copy_);
  277. EdgeWeightMap weight_map = boost::get(boost::edge_weight,
  278. graph_copy_);
  279. PredecessorMap pred_map(&pred_list[0], graph_indices);
  280. DistanceMap dist_map(&dist_list[0], graph_indices);
  281. // Find the shortest path
  282. if (iteration == 0)
  283. {
  284. boost::bellman_ford_shortest_paths(graph_copy_,
  285. graph_size,
  286. boost::root_vertex(root_vertex)
  287. .weight_map(weight_map)
  288. .predecessor_map(pred_map)
  289. .distance_map(dist_map));
  290. }
  291. else
  292. {
  293. boost::dijkstra_shortest_paths(graph_copy_,
  294. root_vertex,
  295. boost::predecessor_map(pred_map)
  296. .distance_map(dist_map));
  297. }
  298. // Add the new distances
  299. boost::graph_traits<DirectedGraph>::vertex_iterator vi, vi_end;
  300. for (boost::tie(vi, vi_end) = boost::vertices(graph_copy_);
  301. vi != vi_end; ++vi)
  302. {
  303. i_distances_[iteration][*vi] = dist_map[*vi];
  304. }
  305. // Add the new path (the given path is in the copied graph, so the
  306. // vertices need to be mapped to the original graph)
  307. Vertex sink_copy = orig_to_copy_[sink_];
  308. for (Vertex u_copy = sink_copy, v_copy = pred_map[u_copy];
  309. u_copy != v_copy; u_copy = v_copy, v_copy = pred_map[v_copy])
  310. {
  311. Vertex u_orig = copy_to_orig_[u_copy];
  312. Vertex v_orig = copy_to_orig_[v_copy];
  313. // Ignore loops
  314. // Loops are caused by mapping the input and output vertices in the
  315. // copied graph to the same vertex in the original graph
  316. if (u_orig == v_orig)
  317. {
  318. continue;
  319. }
  320. i_paths_[iteration][u_orig].insert(v_orig);
  321. }
  322. }
  323. void KShortestPaths2::Interlace(size_t iteration)
  324. {
  325. util::Logger::LogDebug("interlace iteration: " + std::to_string(iteration));
  326. MultiPredecessorMap& paths = i_paths_[iteration];
  327. boost::graph_traits<DirectedGraph>::edge_iterator ei, ei_end;
  328. for (boost::tie(ei, ei_end) = boost::edges(graph_orig_);
  329. ei != ei_end; ++ei)
  330. {
  331. Vertex s_orig = boost::source(*ei, graph_orig_);
  332. Vertex t_orig = boost::target(*ei, graph_orig_);
  333. // Ignore source and sink
  334. if (s_orig == source_ || t_orig == sink_)
  335. {
  336. continue;
  337. }
  338. // Is edge within paths?
  339. if (paths.count(t_orig) > 0 && paths.count(s_orig) > 0)
  340. {
  341. // Is edge duplicate?
  342. if (paths.count(s_orig) > 0 && paths[s_orig].count(t_orig) > 0)
  343. {
  344. paths[t_orig].erase(s_orig);
  345. paths[s_orig].erase(t_orig);
  346. }
  347. }
  348. }
  349. }
  350. double KShortestPaths2::PathCosts(size_t iteration)
  351. {
  352. util::Logger::LogDebug("path costs iteration: " + std::to_string(iteration));
  353. MultiPredecessorMap& paths = i_paths_[iteration];
  354. double value = 0.0;
  355. // EdgeWeightMap weights = boost::get(boost::edge_weight, graph_orig_);
  356. // boost::graph_traits<DirectedGraph>::edge_iterator ei, ei_end;
  357. // for (boost::tie(ei, ei_end) = boost::edges(graph_orig_);
  358. // ei != ei_end; ++ei)
  359. // {
  360. // Vertex s_orig = boost::source(*ei, graph_orig_);
  361. // Vertex t_orig = boost::target(*ei, graph_orig_);
  362. //
  363. // // If the edge is on the path, add the edge weight to the overall
  364. // // path costs
  365. // if (paths.count(t_orig) > 0 && paths[t_orig].count(s_orig) > 0)
  366. // {
  367. // value += weights[*ei];
  368. // }
  369. // }
  370. for (int i = 0; i < iteration; ++i)
  371. {
  372. value += i_distances_[i][orig_to_copy_[sink_]];
  373. }
  374. util::Logger::LogDebug("calculated costs: " + std::to_string(value));
  375. return value;
  376. }
  377. KShortestPaths2::KShortestPaths2()
  378. {
  379. /* EMPTY */
  380. }
  381. KShortestPaths2::~KShortestPaths2()
  382. {
  383. /* EMPTY */
  384. }
  385. }