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.
 
 
 

211 lines
8.4 KiB

#include <algorithm>
#include <iostream>
#include <queue>
#include <stack>
#include <sstream>
#include "Graph.h"
#include "util/GraphParser.h"
namespace data {
Graph::Graph(bool stdout_output, bool file_output, std::string output_filename, bool verbose_max_flow, bool min_cut, int verbosity)
: 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) {
//if(!stdout_output && file_output) {
// m_stdout_output = false;
//} else {
// m_stdout_output = true;
//}
}
void Graph::parseFromString(const std::string &graph_string) {
parser::parseString(graph_string, m_arc_list, m_vertices, m_source_id, m_sink_id, m_num_vertices, m_num_arcs);
setSourceAndSinkIterator();
initMatrices();
initOstream();
}
void Graph::parseFromFile(const std::string &graph_file) {
if(graph_file == m_output_file_name) {
throw std::runtime_error("Input graph file name and output file name are the same. Will not overwrite. Exiting...");
}
parser::parseFile(graph_file, m_arc_list, m_vertices, m_source_id, m_sink_id, m_num_vertices, m_num_arcs);
setSourceAndSinkIterator();
initMatrices();
initOstream();
}
void Graph::initMatrices() {
m_flow.resize(m_num_vertices, std::vector<Capacity>(m_num_vertices, 0));
m_capapcities.resize(m_num_vertices, std::vector<Capacity>(m_num_vertices, 0));
for(auto const &arc : m_arc_list) {
m_capapcities.at(arc.start - 1).at(arc.end - 1) = arc.capacity; // how to best map arbitrary ids to index in matrix
}
}
void Graph::setSourceAndSinkIterator() {
auto m_source = std::find_if(m_vertices.begin(), m_vertices.end(), [this] (const Vertex &v) { return (v.getID() == m_source_id); });
auto m_sink = std::find_if(m_vertices.begin(), m_vertices.end(), [this] (const Vertex &v) { return (v.getID() == m_sink_id); });
}
void Graph::initOstream() {
if(m_file_output) {
m_ofstream = new std::ofstream(m_output_file_name);
} else {
m_ofstream = &std::cout;
}
}
void Graph::maxFlowDinic() {
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
printInformation();
do {
constructLevelGraph();
} while(findAugmentingPaths() != NO_AUGMENTING_PATH_FOUND);
*m_ofstream << "Found max flow |x| = " << m_max_flow << "\n";
if(m_verbose_max_flow) printMaxFlowInformation();
if(m_min_cut) printMinCut();
if(m_verbosity >= 1) printComputationStatistics(start, std::chrono::steady_clock::now());
}
int Graph::findAugmentingPaths() {
auto m_sink = std::find_if(m_vertices.begin(), m_vertices.end(), [this] (const Vertex &v) { return v.getID() == m_sink_id; });
if(m_sink->getLevel() == UNDEF_LEVEL) {
return NO_AUGMENTING_PATH_FOUND;
}
for(auto &v : m_vertices) {
v.setVisited(false);
}
auto m_source = std::find_if(m_vertices.begin(), m_vertices.end(), [this] (const Vertex &v) { return v.getID() == m_source_id; });
std::vector<Vertex> path{*m_source};
buildPath(path);
return 0;
}
void Graph::buildPath(std::vector<Vertex> &current_path) {
Vertex head = current_path.back();
if(head.getID() == m_sink_id) {
computeFlowForPath(current_path);
}
for(auto const& arc : head.getOutgoingArcs()) {
if(m_capapcities.at(arc.start - 1).at(arc.end - 1) <= 0) continue;
auto it = std::find_if(m_vertices.begin(), m_vertices.end(), [&arc] (const Vertex &v) { return v.getID() == arc.end; });
if(head.getLevel() + 1 != it->getLevel()) continue;
if(it != m_vertices.end()) {
current_path.push_back(*it);
buildPath(current_path);
}
current_path.pop_back();
}
if(m_verbosity >= 1) m_num_build_path_calls++;
}
void Graph::computeFlowForPath(const std::vector<Vertex> &current_path) {
std::vector<Capacity> path_capacities;
for(uint i = 0; i < current_path.size() - 1; i++) {
path_capacities.push_back(m_capapcities.at(current_path.at(i).getID() - 1).at(current_path.at(i + 1).getID() - 1));
}
Capacity flow = *std::min_element(path_capacities.begin(), path_capacities.end());
m_max_flow += flow;
for(uint i = 0; i < current_path.size() - 1; i++) {
m_capapcities.at(current_path.at(i).getID() - 1).at(current_path.at(i + 1).getID() - 1) -= flow;
m_flow.at(current_path.at(i).getID() - 1).at(current_path.at(i + 1).getID() - 1) += flow;
}
if(m_verbosity >= 1) m_num_paths++;
if(m_verbosity >= 2) {
std::stringstream path;
path << std::to_string(current_path.front().getID());
for(uint i = 1; i < current_path.size(); i++) {
path << " > " << current_path.at(i).getID();
}
path << " | flow = " << flow;
m_augmenting_paths.push_back(path.str());
}
}
void Graph::constructLevelGraph() {
std::queue<Vertex> q;
for(auto &v : m_vertices) {
v.setLevel(UNDEF_LEVEL);
}
auto m_source = std::find_if(m_vertices.begin(), m_vertices.end(), [this] (const Vertex &v) { return (v.getID() == m_source_id); });
m_source->setLevel(0);
q.push(*m_source);
while(!q.empty()) {
Vertex current_vertex = q.front();
int current_level = current_vertex.getLevel();
q.pop();
// restructure this to use matrix
for(auto const &arc : current_vertex.getOutgoingArcs()) {
if(m_capapcities.at(arc.start - 1).at(arc.end - 1) <= 0) continue;
auto it = std::find_if(m_vertices.begin(), m_vertices.end(), [&arc] (const Vertex &v) { return (v.getID() == arc.end) && !v.hasDefinedLevel(); });
if(it != m_vertices.end()) {
it->setLevel(current_level + 1);
q.push(*it);
}
}
}
if(m_verbosity >= 1) m_num_level_graphs_built++;
}
void Graph::printInformation() const {
auto m_source = std::find_if(m_vertices.begin(), m_vertices.end(), [this] (const Vertex &v) { return (v.getID() == m_source_id); });
auto m_sink = std::find_if(m_vertices.begin(), m_vertices.end(), [this] (const Vertex &v) { return (v.getID() == m_sink_id); });
*m_ofstream << "#Vertices: " << m_num_vertices << std::endl;
*m_ofstream << "#Arc: " << m_num_arcs << std::endl;
*m_ofstream << "Source: " << m_source->getID() << ", Sink: " << m_sink->getID() << std::endl;
*m_ofstream << "Vertices: ";
bool first = true;
for(auto const& v : m_vertices) {
if(first) first = false;
else *m_ofstream << ", ";
*m_ofstream << v.getID();
}
*m_ofstream << std::endl;
for(auto const& a : m_arc_list) {
*m_ofstream << " " << a.start << " -> " << a.end << " capacity = " << a.capacity << std::endl;
}
*m_ofstream << std::endl;
}
void Graph::printMaxFlowInformation() const {
*m_ofstream << "Max Flow per arc:\n";
for(auto const &arc : m_arc_list) {
*m_ofstream << " " << arc.start << " -> " << arc.end << " flow = " << m_flow.at(arc.start - 1 ).at(arc.end - 1) << "/" << arc.capacity << "\n";
}
}
void Graph::printMinCut() const {
std::vector<std::string> min_cut, complement;
for(auto const &vertex : m_vertices) {
if(vertex.getLevel() != UNDEF_LEVEL) {
min_cut.push_back(std::to_string(vertex.getID()));
} else {
complement.push_back(std::to_string(vertex.getID()));
}
}
*m_ofstream << "Min Cut X: {";
bool first = true;
for(auto const &v : min_cut) {
if(first) first = false;
else *m_ofstream << ", ";
*m_ofstream << v;
} *m_ofstream << "}\nComplement(X): {";
first = true;
for(auto const &v : complement) {
if(first) first = false;
else *m_ofstream << ", ";
*m_ofstream << v;
} *m_ofstream << "}\n";
}
void Graph::printComputationStatistics(const std::chrono::steady_clock::time_point &start, const std::chrono::steady_clock::time_point &end) const {
*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";
*m_ofstream << "Computation Statistics:\n";
*m_ofstream << " #level graphs built: " << m_num_level_graphs_built << "\n";
*m_ofstream << " #augmenting paths computed: " << m_num_paths << "\n";
if(m_verbosity >= 2) {
for(auto const &path : m_augmenting_paths) *m_ofstream << " " << path << "\n";
}
*m_ofstream << " #recursive buildPath calls: " << m_num_build_path_calls << "\n";
}
}