KShortestPaths3.cpp 16 KB

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