From 830765bc33e7f3c4342bc9cae4f87fa49dfee9f3 Mon Sep 17 00:00:00 2001 From: kateonbxsh Date: Mon, 8 Dec 2025 18:00:12 +0100 Subject: [PATCH] feat: implement FOrd-Fulkerson maxflow algorithm --- .gitignore | 1 + .vscode/settings.json | 6 +++- src/algo.ml | 73 +++++++++++++++++++++++++++++++++++++++++++ src/algo.mli | 13 ++++++++ src/dune | 8 +---- src/ftest.ml | 14 +++++---- src/gfile.ml | 36 ++++++++++----------- src/graph.ml | 4 +-- src/graph.mli | 4 +-- src/tools.ml | 13 ++++---- src/tools.mli | 2 +- 11 files changed, 131 insertions(+), 43 deletions(-) create mode 100644 src/algo.ml create mode 100644 src/algo.mli diff --git a/.gitignore b/.gitignore index bbc178c..3fa627d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ _build/ +ford/ outfile *~ *.exe diff --git a/.vscode/settings.json b/.vscode/settings.json index 9845603..561dcbb 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -3,5 +3,9 @@ "*.ml": "ocaml", "*.mli": "ocaml" }, - "editor.formatOnSave": true + "editor.formatOnSave": true, + "ocaml.sandbox": { + "kind": "custom", + "template": "$prog $args" + } } \ No newline at end of file diff --git a/src/algo.ml b/src/algo.ml new file mode 100644 index 0000000..f27e701 --- /dev/null +++ b/src/algo.ml @@ -0,0 +1,73 @@ +open Graph +open Tools + +type flow = { + flow: int; + capacity: int; +} + +type initial_graph = flow graph;; +type redisual_graph = int graph;; + +let reset_graph graph = e_fold graph (fun gr arc -> new_arc gr {arc with lbl = {arc.lbl with flow = 0}}) (clone_nodes graph);; + +let flow_to_residual graph = + let residual_graph = clone_nodes graph in + let add_double_arc gr arc = + new_arc (new_arc gr {arc with lbl = (arc.lbl.capacity)}) {src = arc.tgt; tgt = arc.src; lbl = 0} in + e_fold graph add_double_arc residual_graph;; + +let arc_list_includes l arc = match (List.find_opt (fun other -> other.src == arc.src && other.tgt == arc.tgt) l) with + | None -> false + | Some _ -> true;; + + +let find_path residual_graph src tgt = + let rec find_next_arc source memo = + let possible_arcs = List.filter (fun arc -> arc.lbl > 0 && not (arc_list_includes memo arc)) (out_arcs residual_graph source) in + if List.length possible_arcs == 0 then None else match (List.find_opt (fun a -> a.tgt == tgt) possible_arcs) with + | Some final_arc -> Some (List.rev (final_arc :: memo)) + | None -> List.find_map (fun a -> find_next_arc a.tgt (a :: memo)) possible_arcs + in find_next_arc src [];; + +let get_path_min_augmentation path = + List.fold_left (fun a b -> min a b) max_int (List.map (fun a -> a.lbl) path);; + +let update_augmentations gr path aug = + let add_augmentation_to_arc graph arc = + add_arc (add_arc graph arc.src arc.tgt (-aug)) arc.tgt arc.src aug; + in List.fold_left add_augmentation_to_arc gr path;; + +let residual_to_flow initial residual = + let update_initial_arc_from_residual initial_graph initial_arc = + match (find_arc residual initial_arc.src initial_arc.tgt) with + | None -> initial_graph + | Some residual_arc -> new_arc initial_graph { + initial_arc with lbl = { + initial_arc.lbl with flow = initial_arc.lbl.capacity - residual_arc.lbl + } + }; + in e_fold initial (update_initial_arc_from_residual) initial;; + +let apply_ford_fulkerson initial src tgt = + let residual_graph = flow_to_residual (reset_graph initial) in + let rec loop current_graph = + match (find_path current_graph src tgt) with + | None -> Printf.printf "could not find path, ending algorithm\n" ; current_graph + | Some path -> + Printf.printf "found path: "; + List.iter (fun arc -> Printf.printf "%d -> " arc.src) path; + Printf.printf "%d\nfinding min augment\n" tgt; + let min_aug = get_path_min_augmentation path in + Printf.printf "found min augment: %d\n" min_aug; + let updated_graph = update_augmentations current_graph path min_aug in + loop updated_graph; + in + let final_residual_graph = loop residual_graph in + residual_to_flow initial final_residual_graph;; + +let printable_flow_graph graph = + gmap graph (fun arc -> {arc with lbl = Printf.sprintf "%d/%d" arc.lbl.flow arc.lbl.capacity});; + +let flow_from_string_graph graph = + gmap graph (fun arc -> {arc with lbl = {flow = 0; capacity = int_of_string arc.lbl}});; \ No newline at end of file diff --git a/src/algo.mli b/src/algo.mli new file mode 100644 index 0000000..4242618 --- /dev/null +++ b/src/algo.mli @@ -0,0 +1,13 @@ +open Graph + +type flow = { + flow: int; + capacity: int; +};; + +type initial_graph = flow graph;; +type redisual_graph = int graph;; + +val apply_ford_fulkerson: flow graph -> int -> int -> flow graph;; +val printable_flow_graph: flow graph -> string graph;; +val flow_from_string_graph: string graph -> flow graph;; \ No newline at end of file diff --git a/src/dune b/src/dune index 8887851..ed3eb51 100644 --- a/src/dune +++ b/src/dune @@ -1,13 +1,7 @@ - (executable (name ftest) ;; (libraries ) - ;; Disable some warnings ;; (flags (:standard -w -6)) - ;; Link to executable in main dir - (promote (until-clean)) - - ) - + (promote (until-clean))) diff --git a/src/ftest.ml b/src/ftest.ml index a51d90e..121d9f0 100644 --- a/src/ftest.ml +++ b/src/ftest.ml @@ -1,5 +1,6 @@ open Gfile - +open Algo + let () = (* Check the number of command-line arguments *) @@ -16,20 +17,21 @@ let () = (* Arguments are : infile(1) source-id(2) sink-id(3) outfile(4) *) - + let infile = Sys.argv.(1) and outfile = Sys.argv.(4) - + (* These command-line arguments are not used for the moment. *) - and _source = int_of_string Sys.argv.(2) - and _sink = int_of_string Sys.argv.(3) + and source = int_of_string Sys.argv.(2) + and sink = int_of_string Sys.argv.(3) in (* Open file *) let graph = from_file infile in (* Rewrite the graph that has been read. *) - let () = export outfile graph in + let result_graph = apply_ford_fulkerson (flow_from_string_graph graph) source sink in + let () = export outfile (printable_flow_graph result_graph) in () diff --git a/src/gfile.ml b/src/gfile.ml index 2de142e..c7f3d89 100644 --- a/src/gfile.ml +++ b/src/gfile.ml @@ -1,13 +1,13 @@ open Graph open Printf - + type path = string let export path graph = - let ff = open_out path in - - fprintf ff -" + let ff = open_out path in + + fprintf ff + " digraph cool_generated_graph { fontname=\"Helvetica,Arial,sans-serif\" node [fontname=\"Helvetica,Arial,sans-serif\"] @@ -15,17 +15,17 @@ digraph cool_generated_graph { rankdir=LR; node [shape = circle];"; - let print_arc arc = - fprintf ff " - %d -> %d [label = \"%s\"];" - arc.src arc.tgt arc.lbl; - in e_iter graph print_arc; - + let print_arc arc = fprintf ff " + %d -> %d [label = \"%s\"];" + arc.src arc.tgt arc.lbl; + in e_iter graph print_arc; + + fprintf ff " }"; - close_out ff - ;; + close_out ff +;; (* Format of text files: @@ -55,7 +55,7 @@ let compute_y id = let sgn = if delta mod 2 = 0 then -1 else 1 in 300 + sgn * (delta / 2) * 100 - + let write_file path graph = @@ -71,9 +71,9 @@ let write_file path graph = (* Write all arcs *) let _ = e_fold graph (fun count arc -> fprintf ff "e %d %d %d %s\n" arc.src arc.tgt count arc.lbl ; count + 1) 0 in - + fprintf ff "\n%% End of graph\n" ; - + close_out ff ; () @@ -133,7 +133,7 @@ let from_file path = in let final_graph = loop empty_graph in - + close_in infile ; final_graph - + diff --git a/src/graph.ml b/src/graph.ml index ab47c80..9fc5831 100644 --- a/src/graph.ml +++ b/src/graph.ml @@ -1,5 +1,5 @@ (* - + You do not need to read this file for the project. Read graph.mli instead. You may read it though, out of curiosity. @@ -65,7 +65,7 @@ let new_arc gr arc = (* Update out-arcs. *) let outb = arc :: List.filter (fun a -> a.tgt <> arc.tgt) outa in - + (* Replace out-arcs in the graph. *) let gr2 = List.remove_assoc arc.src gr in (arc.src, outb) :: gr2 diff --git a/src/graph.mli b/src/graph.mli index cbafc4b..3c7e255 100644 --- a/src/graph.mli +++ b/src/graph.mli @@ -46,7 +46,7 @@ val node_exists: 'a graph -> id -> bool val out_arcs: 'a graph -> id -> 'a arc list (* find_arc gr id1 id2 finds an arc between id1 and id2. Returns None if the arc does not exist. -* @raise Graph_error if id1 is unknown. *) + * @raise Graph_error if id1 is unknown. *) val find_arc: 'a graph -> id -> id -> 'a arc option @@ -57,7 +57,7 @@ val n_iter: 'a graph -> (id -> unit) -> unit (* Like n_iter, but the nodes are sorted. *) val n_iter_sorted: 'a graph -> (id -> unit) -> unit - + (* Fold on all (unsorted) nodes. You must remember what List.fold_left does. *) val n_fold: 'a graph -> ('b -> id -> 'b) -> 'b -> 'b diff --git a/src/tools.ml b/src/tools.ml index b78ea0c..6680b4c 100644 --- a/src/tools.ml +++ b/src/tools.ml @@ -1,18 +1,19 @@ open Graph (* we fold the graph using new_node as the function, -and using empty_graph as the initial value*) + and using empty_graph as the initial value*) let clone_nodes (graph: 'a graph) = n_fold graph (fun x -> new_node x) empty_graph;; (* we clone the graph, then fold the old graph, mapping the arcs, -and using the new cloned graph as the initial value *) + and using the new cloned graph as the initial value *) let gmap graph f = let new_graph = clone_nodes graph - in e_fold graph (fun old_graph old_arc -> new_arc old_graph (f old_arc)) new_graph;; + in e_fold graph (fun old_graph old_arc -> new_arc old_graph (f old_arc)) new_graph;; -(* new_arc already does the job (thanks prof for pointing it out)*) -let add_arc graph fromid toid value = - new_arc graph {src = fromid; tgt = toid; lbl = value } +let add_arc graph src tgt value = + match (find_arc graph src tgt) with + | None -> graph + | Some arc -> new_arc graph {arc with lbl = arc.lbl + value};; diff --git a/src/tools.mli b/src/tools.mli index 79db193..a4a5487 100644 --- a/src/tools.mli +++ b/src/tools.mli @@ -1,6 +1,6 @@ open Graph val clone_nodes: 'a graph -> 'b graph -val gmap: 'a graph -> ('a -> 'b) -> 'b graph +val gmap: 'a graph -> ('a arc -> 'b arc) -> 'b graph val add_arc: int graph -> id -> id -> int -> int graph