A simple students project implementing Dinic's Algorithm to compute the max flow/min cut of a network.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

199 lines
7.8 KiB

  1. #include <algorithm>
  2. #include <iostream>
  3. #include <queue>
  4. #include <stack>
  5. #include <sstream>
  6. #include "Graph.h"
  7. #include "util/GraphParser.h"
  8. namespace data {
  9. Graph::Graph(bool stdout_output, bool file_output, std::string output_filename, bool verbose_max_flow, bool min_cut, int verbosity)
  10. : m_file_output(file_output), m_output_file_name(output_filename), m_verbose_max_flow(verbose_max_flow), m_min_cut(min_cut), m_verbosity(verbosity) {
  11. }
  12. void Graph::parseFromString(const std::string &graph_string) {
  13. parser::parseString(graph_string, m_arc_list, m_vertices, m_source_id, m_sink_id, m_num_vertices, m_num_arcs);
  14. initMatrices();
  15. initOstream();
  16. }
  17. void Graph::parseFromFile(const std::string &graph_file) {
  18. if(graph_file == m_output_file_name) {
  19. throw std::runtime_error("Input graph file name and output file name are the same. Will not overwrite. Exiting...");
  20. }
  21. parser::parseFile(graph_file, m_arc_list, m_vertices, m_source_id, m_sink_id, m_num_vertices, m_num_arcs);
  22. initMatrices();
  23. initOstream();
  24. }
  25. void Graph::initMatrices() {
  26. m_flow.resize(m_num_vertices, std::vector<Capacity>(m_num_vertices, 0));
  27. m_capapcities.resize(m_num_vertices, std::vector<Capacity>(m_num_vertices, 0));
  28. for(auto const &arc : m_arc_list) {
  29. m_capapcities.at(arc.start - 1).at(arc.end - 1) += arc.capacity;
  30. }
  31. }
  32. void Graph::initOstream() {
  33. if(m_file_output) {
  34. m_ofstream = new std::ofstream(m_output_file_name);
  35. } else {
  36. m_ofstream = &std::cout;
  37. }
  38. }
  39. void Graph::maxFlowDinic() {
  40. std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
  41. printInformation();
  42. do {
  43. constructLevelGraph();
  44. } while(findAugmentingPaths() != NO_AUGMENTING_PATH_FOUND);
  45. *m_ofstream << "Found max flow |x| = " << m_max_flow << "\n";
  46. if(m_verbose_max_flow) printMaxFlowInformation();
  47. if(m_min_cut) printMinCut();
  48. if(m_verbosity >= 1) printComputationStatistics(start, std::chrono::steady_clock::now());
  49. }
  50. int Graph::findAugmentingPaths() {
  51. auto m_sink = std::find_if(m_vertices.begin(), m_vertices.end(), [this] (const Vertex &v) { return v.getID() == m_sink_id; });
  52. if(m_sink->getLevel() == UNDEF_LEVEL) {
  53. return NO_AUGMENTING_PATH_FOUND;
  54. }
  55. for(auto &v : m_vertices) {
  56. v.setVisited(false);
  57. }
  58. auto m_source = std::find_if(m_vertices.begin(), m_vertices.end(), [this] (const Vertex &v) { return v.getID() == m_source_id; });
  59. std::vector<Vertex> path{*m_source};
  60. buildPath(path);
  61. return 0;
  62. }
  63. void Graph::buildPath(std::vector<Vertex> &current_path) {
  64. Vertex head = current_path.back();
  65. if(head.getID() == m_sink_id) {
  66. computeFlowForPath(current_path);
  67. }
  68. for(auto const& arc : head.getOutgoingArcs()) {
  69. if(m_capapcities.at(arc.start - 1).at(arc.end - 1) <= 0) continue;
  70. auto it = std::find_if(m_vertices.begin(), m_vertices.end(), [&arc] (const Vertex &v) { return v.getID() == arc.end; });
  71. if(head.getLevel() + 1 != it->getLevel()) continue;
  72. if(it != m_vertices.end()) {
  73. current_path.push_back(*it);
  74. buildPath(current_path);
  75. }
  76. current_path.pop_back();
  77. }
  78. if(m_verbosity >= 1) m_num_build_path_calls++;
  79. }
  80. void Graph::computeFlowForPath(const std::vector<Vertex> &current_path) {
  81. std::vector<Capacity> path_capacities;
  82. for(uint i = 0; i < current_path.size() - 1; i++) {
  83. path_capacities.push_back(m_capapcities.at(current_path.at(i).getID() - 1).at(current_path.at(i + 1).getID() - 1));
  84. }
  85. Capacity flow = *std::min_element(path_capacities.begin(), path_capacities.end());
  86. m_max_flow += flow;
  87. for(uint i = 0; i < current_path.size() - 1; i++) {
  88. m_capapcities.at(current_path.at(i).getID() - 1).at(current_path.at(i + 1).getID() - 1) -= flow;
  89. m_flow.at(current_path.at(i).getID() - 1).at(current_path.at(i + 1).getID() - 1) += flow;
  90. }
  91. if(m_verbosity >= 1) m_num_paths++;
  92. if(m_verbosity >= 2) {
  93. std::stringstream path;
  94. path << std::to_string(current_path.front().getID());
  95. for(uint i = 1; i < current_path.size(); i++) {
  96. path << " > " << current_path.at(i).getID();
  97. }
  98. path << " | flow = " << flow;
  99. m_augmenting_paths.push_back(path.str());
  100. }
  101. }
  102. void Graph::constructLevelGraph() {
  103. std::queue<Vertex> q;
  104. for(auto &v : m_vertices) {
  105. v.setLevel(UNDEF_LEVEL);
  106. }
  107. auto m_source = std::find_if(m_vertices.begin(), m_vertices.end(), [this] (const Vertex &v) { return (v.getID() == m_source_id); });
  108. m_source->setLevel(0);
  109. q.push(*m_source);
  110. while(!q.empty()) {
  111. Vertex current_vertex = q.front();
  112. int current_level = current_vertex.getLevel();
  113. q.pop();
  114. // restructure this to use matrix
  115. for(auto const &arc : current_vertex.getOutgoingArcs()) {
  116. if(m_capapcities.at(arc.start - 1).at(arc.end - 1) <= 0) continue;
  117. auto it = std::find_if(m_vertices.begin(), m_vertices.end(), [&arc] (const Vertex &v) { return (v.getID() == arc.end) && !v.hasDefinedLevel(); });
  118. if(it != m_vertices.end()) {
  119. it->setLevel(current_level + 1);
  120. q.push(*it);
  121. }
  122. }
  123. }
  124. if(m_verbosity >= 1) m_num_level_graphs_built++;
  125. }
  126. void Graph::printInformation() const {
  127. auto m_source = std::find_if(m_vertices.begin(), m_vertices.end(), [this] (const Vertex &v) { return (v.getID() == m_source_id); });
  128. auto m_sink = std::find_if(m_vertices.begin(), m_vertices.end(), [this] (const Vertex &v) { return (v.getID() == m_sink_id); });
  129. *m_ofstream << "#Vertices: " << m_num_vertices << std::endl;
  130. *m_ofstream << "#Arc: " << m_num_arcs << std::endl;
  131. *m_ofstream << "Source: " << m_source->getID() << ", Sink: " << m_sink->getID() << std::endl;
  132. *m_ofstream << "Vertices: ";
  133. bool first = true;
  134. for(auto const& v : m_vertices) {
  135. if(first) first = false;
  136. else *m_ofstream << ", ";
  137. *m_ofstream << v.getID();
  138. }
  139. *m_ofstream << std::endl;
  140. for(auto const& a : m_arc_list) {
  141. *m_ofstream << " " << a.start << " -> " << a.end << " capacity = " << a.capacity << std::endl;
  142. }
  143. *m_ofstream << std::endl;
  144. }
  145. void Graph::printMaxFlowInformation() const {
  146. *m_ofstream << "Max Flow per arc:\n";
  147. for(auto const &arc : m_arc_list) {
  148. *m_ofstream << " " << arc.start << " -> " << arc.end << " flow = " << m_flow.at(arc.start - 1 ).at(arc.end - 1) << "/" << arc.capacity << "\n";
  149. }
  150. }
  151. void Graph::printMinCut() const {
  152. std::vector<std::string> min_cut, complement;
  153. for(auto const &vertex : m_vertices) {
  154. if(vertex.getLevel() != UNDEF_LEVEL) {
  155. min_cut.push_back(std::to_string(vertex.getID()));
  156. } else {
  157. complement.push_back(std::to_string(vertex.getID()));
  158. }
  159. }
  160. *m_ofstream << "Min Cut X: {";
  161. bool first = true;
  162. for(auto const &v : min_cut) {
  163. if(first) first = false;
  164. else *m_ofstream << ", ";
  165. *m_ofstream << v;
  166. } *m_ofstream << "}\nComplement(X): {";
  167. first = true;
  168. for(auto const &v : complement) {
  169. if(first) first = false;
  170. else *m_ofstream << ", ";
  171. *m_ofstream << v;
  172. } *m_ofstream << "}\n";
  173. }
  174. void Graph::printComputationStatistics(const std::chrono::steady_clock::time_point &start, const std::chrono::steady_clock::time_point &end) const {
  175. *m_ofstream << "Elapsed time: " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms (" << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << "µs).\n";
  176. *m_ofstream << "Computation Statistics:\n";
  177. *m_ofstream << " #level graphs built: " << m_num_level_graphs_built << "\n";
  178. *m_ofstream << " #augmenting paths computed: " << m_num_paths << "\n";
  179. if(m_verbosity >= 2) {
  180. for(auto const &path : m_augmenting_paths) *m_ofstream << " " << path << "\n";
  181. }
  182. *m_ofstream << " #recursive buildPath calls: " << m_num_build_path_calls << "\n";
  183. }
  184. }