KShortestPaths2.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. util::Logger::LogDebug("remove edges");
  51. // Remove the old edges, needs to be done without any iterator since
  52. // the removal invalidates any iterators
  53. for (auto edge : edges_to_remove_)
  54. {
  55. boost::remove_edge(edge.first, edge.second, graph_copy_);
  56. }
  57. edges_to_remove_.clear();
  58. util::Logger::LogDebug("add edges");
  59. // Add the new edges, needs to be done without any iterator since
  60. // the addition invalidates any iterators
  61. for (auto edge : edges_to_add_)
  62. {
  63. boost::add_edge(edge.first.first, edge.first.second,
  64. edge.second, graph_copy_);
  65. }
  66. edges_to_add_.clear();
  67. }
  68. void KShortestPaths2::QueueAddEdge(Vertex source, Vertex target, double weight)
  69. {
  70. edges_to_add_.push_back(
  71. std::pair<std::pair<Vertex, Vertex>, double>(
  72. std::pair<Vertex, Vertex>(source, target), weight));
  73. }
  74. void KShortestPaths2::QueueRemoveEdge(Vertex source, Vertex target)
  75. {
  76. edges_to_remove_.push_back(std::pair<Vertex, Vertex>(source, target));
  77. }
  78. void KShortestPaths2::QueueCopyEdges()
  79. {
  80. EdgeWeightMap weights = boost::get(boost::edge_weight, graph_orig_);
  81. boost::graph_traits<DirectedGraph>::edge_iterator ei, ei_end;
  82. for (boost::tie(ei, ei_end) = boost::edges(graph_orig_);
  83. ei != ei_end; ++ei)
  84. {
  85. Vertex s_orig = boost::source(*ei, graph_orig_);
  86. Vertex t_orig = boost::target(*ei, graph_orig_);
  87. Vertex s_copy = orig_to_copy_[s_orig];
  88. Vertex t_copy = orig_to_copy_[t_orig];
  89. double weight = weights[*ei];
  90. QueueAddEdge(s_copy, t_copy, weight);
  91. }
  92. }
  93. void KShortestPaths2::ClearAllEdges()
  94. {
  95. boost::graph_traits<DirectedGraph>::vertex_iterator vi, vi_end;
  96. for (boost::tie(vi, vi_end) = boost::vertices(graph_copy_); vi != vi_end; ++vi)
  97. {
  98. boost::clear_out_edges(*vi, graph_copy_);
  99. }
  100. }
  101. MultiPredecessorMap KShortestPaths2::Run(DirectedGraph& graph_orig,
  102. Vertex source, Vertex sink,
  103. size_t iterations)
  104. {
  105. // Clear all previous data
  106. edges_to_add_.clear();
  107. edges_to_remove_.clear();
  108. i_distances_.clear();
  109. i_paths_.clear();
  110. graph_orig_ = graph_orig;
  111. source_ = source;
  112. sink_ = sink;
  113. CreateCopy();
  114. FindAndAugment(0);
  115. for (size_t i = 0; i < iterations; ++i)
  116. {
  117. util::Logger::LogDebug("ksp iteration: " + std::to_string(i));
  118. if (i > 0)
  119. {
  120. if (PathCosts(i) >= PathCosts(i - 1))
  121. {
  122. return i_paths_[i];
  123. }
  124. }
  125. ExtendGraph(i);
  126. // TransformEdges(i > 0 ? i - 1 : 0);
  127. TransformEdges(i);
  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("clear all edges");
  138. ClearAllEdges();
  139. util::Logger::LogDebug("queue copy edges");
  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, boost::target(*oei, graph_copy_), weights[*oei]);
  167. // Remove the old output edge
  168. QueueRemoveEdge(v_copy_in, boost::target(*oei, graph_copy_));
  169. }
  170. // Create auxiliary edge
  171. QueueAddEdge(v_copy_out, v_copy_in, 0.0);
  172. }
  173. util::Logger::LogDebug("update edges");
  174. UpdateEdges();
  175. util::Logger::LogDebug("iterate edges");
  176. // Iterate all edges within the copied graph
  177. weights = boost::get(boost::edge_weight, graph_copy_);
  178. for (boost::tie(ei, ei_end) = boost::edges(graph_copy_);
  179. ei != ei_end; ++ei)
  180. {
  181. Vertex s_copy = boost::source(*ei, graph_copy_);
  182. Vertex t_copy = boost::target(*ei, graph_copy_);
  183. Vertex s_orig = copy_to_orig_[s_copy];
  184. Vertex t_orig = copy_to_orig_[t_copy];
  185. double weight = weights[*ei];
  186. // If the edge is part of the paths
  187. if (paths.count(t_orig) > 0 && paths[t_orig].count(s_orig) > 0)
  188. {
  189. // Add the edge with direction and weight inverted
  190. QueueAddEdge(t_copy, s_copy, -weight);
  191. // Remove the old edge
  192. QueueRemoveEdge(s_copy, t_copy);
  193. }
  194. }
  195. util::Logger::LogDebug("update edges");
  196. UpdateEdges();
  197. // util::FileIO::WriteCSVMatlab(graph_copy_, "/home/wrede/Dokumente/graph_" + std::to_string(iteration) + "e.csv");
  198. }
  199. void KShortestPaths2::TransformEdges(size_t iteration)
  200. {
  201. util::Logger::LogDebug("transform edges iteration: " + std::to_string(iteration));
  202. std::unordered_map<Vertex, double>& distances = i_distances_[iteration];
  203. EdgeWeightMap weights = boost::get(boost::edge_weight, graph_copy_);
  204. boost::graph_traits<DirectedGraph>::edge_iterator ei, ei_end;
  205. for (boost::tie(ei, ei_end) = boost::edges(graph_copy_); ei != ei_end; ++ei)
  206. {
  207. Vertex s_copy = boost::source(*ei, graph_copy_);
  208. Vertex t_copy = boost::target(*ei, graph_copy_);
  209. // Transform the edge weights with the distances calculated in
  210. // the specified path finding iteration
  211. if (distances.count(s_copy) > 0 && distances.count(t_copy) > 0)
  212. {
  213. weights[*ei] += distances[s_copy] - distances[t_copy];
  214. }
  215. // Correct rounding errors
  216. if (weights[*ei] >= -0.0000001 && weights[*ei] <= 0.0000001)
  217. {
  218. weights[*ei] = 0.0;
  219. }
  220. //TODO debug output (experimental)
  221. if (weights[*ei] < 0.0)
  222. {
  223. util::Logger::LogDebug(std::to_string(s_copy)
  224. + " -> " + std::to_string(weights[*ei])
  225. + " -> " + std::to_string(t_copy));
  226. }
  227. }
  228. // util::FileIO::WriteCSVMatlab(graph_copy_, "/home/wrede/Dokumente/graph_" + std::to_string(iteration) + "t.csv");
  229. }
  230. void KShortestPaths2::FindAndAugment(size_t iteration)
  231. {
  232. util::Logger::LogDebug("find and augment iteration: " + std::to_string(iteration));
  233. // Add new path maps until the needed iteration is reached
  234. while (i_paths_.size() < (iteration + 1))
  235. {
  236. i_paths_.push_back(MultiPredecessorMap());
  237. }
  238. // Add new distance maps until the needed iteration is reached
  239. while (i_distances_.size() < (iteration + 1))
  240. {
  241. i_distances_.push_back(std::unordered_map<Vertex, double>());
  242. }
  243. // Only copy old paths if old paths exist
  244. if (iteration > 0)
  245. {
  246. // Copy the old paths
  247. for (auto it = i_paths_[iteration - 1].begin();
  248. it != i_paths_[iteration - 1].end(); ++it)
  249. {
  250. i_paths_[iteration][it->first] = it->second;
  251. }
  252. }
  253. // Prepare variables for path finding
  254. size_t graph_size = boost::num_vertices(graph_copy_);
  255. Vertex root_vertex = orig_to_copy_[source_];
  256. std::vector<Vertex> pred_list(graph_size);
  257. std::vector<double> dist_list(graph_size);
  258. VertexIndexMap graph_indices = boost::get(boost::vertex_index,
  259. graph_copy_);
  260. EdgeWeightMap weight_map = boost::get(boost::edge_weight,
  261. graph_copy_);
  262. PredecessorMap pred_map(&pred_list[0], graph_indices);
  263. DistanceMap dist_map(&dist_list[0], graph_indices);
  264. // Find the shortest path
  265. if (iteration == 0)
  266. {
  267. boost::bellman_ford_shortest_paths(graph_copy_,
  268. graph_size,
  269. boost::root_vertex(root_vertex)
  270. .weight_map(weight_map)
  271. .predecessor_map(pred_map)
  272. .distance_map(dist_map));
  273. }
  274. else
  275. {
  276. boost::dijkstra_shortest_paths(graph_copy_,
  277. root_vertex,
  278. boost::predecessor_map(pred_map)
  279. .distance_map(dist_map));
  280. }
  281. // Add the new distances
  282. boost::graph_traits<DirectedGraph>::vertex_iterator vi, vi_end;
  283. double max_dist = dist_map[orig_to_copy_[sink_]];
  284. for (boost::tie(vi, vi_end) = boost::vertices(graph_copy_); vi != vi_end; ++vi)
  285. {
  286. double dist = dist_map[*vi];
  287. if (dist == std::numeric_limits<double>::max() ||
  288. dist == std::numeric_limits<double>::infinity())
  289. {
  290. dist = max_dist;
  291. }
  292. i_distances_[iteration][*vi] = dist;
  293. }
  294. // Add the new path (the given path is in the copied graph, so the
  295. // vertices need to be mapped to the original graph)
  296. Vertex sink_copy = orig_to_copy_[sink_];
  297. for (Vertex u_copy = sink_copy, v_copy = pred_map[u_copy];
  298. u_copy != v_copy; u_copy = v_copy, v_copy = pred_map[v_copy])
  299. {
  300. Vertex u_orig = copy_to_orig_[u_copy];
  301. Vertex v_orig = copy_to_orig_[v_copy];
  302. // Ignore loops
  303. // Loops are caused by mapping the input and output vertices in the
  304. // copied graph to the same vertex in the original graph
  305. if (u_orig == v_orig)
  306. {
  307. continue;
  308. }
  309. i_paths_[iteration][u_orig].insert(v_orig);
  310. }
  311. }
  312. void KShortestPaths2::Interlace(size_t iteration)
  313. {
  314. util::Logger::LogDebug("interlace iteration: " + std::to_string(iteration));
  315. MultiPredecessorMap& paths = i_paths_[iteration];
  316. boost::graph_traits<DirectedGraph>::edge_iterator ei, ei_end;
  317. for (boost::tie(ei, ei_end) = boost::edges(graph_orig_);
  318. ei != ei_end; ++ei)
  319. {
  320. Vertex s_orig = boost::source(*ei, graph_orig_);
  321. Vertex t_orig = boost::target(*ei, graph_orig_);
  322. // Ignore source and sink
  323. if (s_orig == source_ || t_orig == sink_)
  324. {
  325. continue;
  326. }
  327. // Is edge within paths?
  328. if (paths.count(t_orig) > 0 && paths.count(s_orig) > 0)
  329. {
  330. // Is edge duplicate?
  331. if (paths.count(s_orig) > 0 && paths[s_orig].count(t_orig) > 0)
  332. {
  333. paths[t_orig].erase(s_orig);
  334. paths[s_orig].erase(t_orig);
  335. }
  336. }
  337. }
  338. }
  339. double KShortestPaths2::PathCosts(size_t iteration)
  340. {
  341. util::Logger::LogDebug("path costs iteration: " + std::to_string(iteration));
  342. MultiPredecessorMap& paths = i_paths_[iteration];
  343. double value = 0.0;
  344. // EdgeWeightMap weights = boost::get(boost::edge_weight, graph_orig_);
  345. // boost::graph_traits<DirectedGraph>::edge_iterator ei, ei_end;
  346. // for (boost::tie(ei, ei_end) = boost::edges(graph_orig_);
  347. // ei != ei_end; ++ei)
  348. // {
  349. // Vertex s_orig = boost::source(*ei, graph_orig_);
  350. // Vertex t_orig = boost::target(*ei, graph_orig_);
  351. //
  352. // // If the edge is on the path, add the edge weight to the overall
  353. // // path costs
  354. // if (paths.count(t_orig) > 0 && paths[t_orig].count(s_orig) > 0)
  355. // {
  356. // value += weights[*ei];
  357. // }
  358. // }
  359. for (int i = 0; i < iteration; ++i)
  360. {
  361. value += i_distances_[i][orig_to_copy_[sink_]];
  362. }
  363. util::Logger::LogDebug("calculated costs: " + std::to_string(value));
  364. return value;
  365. }
  366. KShortestPaths2::KShortestPaths2()
  367. {
  368. /* EMPTY */
  369. }
  370. KShortestPaths2::~KShortestPaths2()
  371. {
  372. /* EMPTY */
  373. }
  374. }