struct::graph::op(n)

๐Ÿ“ฆ
version 2.0 ยท 2 versions
, in fedora 43, fedora 44, nixos 26.05, nixpkgs unstable

โœจ NAME โœจ

okay bestie, this is the struct::graph::op(n) manual โ€” yes, the Tcl Data Structures one, and it's lowkey iconic. The name is:

struct::graph::op - Operation for (un)directed graph objects


๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

here's the vibe check for what you can call, fr fr:

package require Tcl 8.6 9

package require struct::graph::op ?0.11.4?

struct::graph::op::toAdjacencyMatrix g

struct::graph::op::toAdjacencyList G ?options...?

struct::graph::op::kruskal g

struct::graph::op::prim g

struct::graph::op::isBipartite? g ?bipartvar?

struct::graph::op::tarjan g

struct::graph::op::connectedComponents g

struct::graph::op::connectedComponentOf g n

struct::graph::op::isConnected? g

struct::graph::op::isCutVertex? g n

struct::graph::op::isBridge? g a

struct::graph::op::isEulerian? g ?tourvar?

struct::graph::op::isSemiEulerian? g ?pathvar?

struct::graph::op::dijkstra g start ?options...?

struct::graph::op::distance g origin destination ?options...?

struct::graph::op::eccentricity g n ?options...?

struct::graph::op::radius g ?options...?

struct::graph::op::diameter g ?options...?

struct::graph::op::BellmanFord G startnode

struct::graph::op::Johnsons G ?options...?

struct::graph::op::FloydWarshall G

struct::graph::op::MetricTravellingSalesman G

struct::graph::op::Christofides G

struct::graph::op::GreedyMaxMatching G

struct::graph::op::MaxCut G U V

struct::graph::op::UnweightedKCenter G k

struct::graph::op::WeightedKCenter G nodeWeights W

struct::graph::op::GreedyMaxIndependentSet G

struct::graph::op::GreedyWeightedMaxIndependentSet G nodeWeights

struct::graph::op::VerticesCover G

struct::graph::op::EdmondsKarp G s t

struct::graph::op::BusackerGowen G desiredFlow s t

struct::graph::op::ShortestsPathsByBFS G s outputFormat

struct::graph::op::BFS G s ?outputFormat...?

struct::graph::op::MinimumDiameterSpanningTree G

struct::graph::op::MinimumDegreeSpanningTree G

struct::graph::op::MaximumFlowByDinic G s t blockingFlowAlg

struct::graph::op::BlockingFlowByDinic G s t

struct::graph::op::BlockingFlowByMKM G s t

struct::graph::op::createResidualGraph G f

struct::graph::op::createAugmentingNetwork G f path

struct::graph::op::createLevelGraph Gf s

struct::graph::op::TSPLocalSearching G C

struct::graph::op::TSPLocalSearching3Approx G C

struct::graph::op::createSquaredGraph G

struct::graph::op::createCompleteGraph G originalEdges

๐Ÿ’– DESCRIPTION ๐Ÿ’–

okay so the package described by this document, struct::graph::op, is a companion to the package struct::graph. It provides a series of common operations and algorithms applicable to (un)directed graphs.

Despite being a companion the package is not directly dependent on struct::graph, only on the API defined by that package. I.e. the operations of this package can be applied to any and all graph objects which provide the same API as the objects created through struct::graph.


๐Ÿ”ฅ OPERATIONS ๐Ÿ”ฅ

struct::graph::op::toAdjacencyMatrix g

This command takes the graph g and returns a nested list containing the adjacency matrix of g.

The elements of the outer list are the rows of the matrix, the inner elements are the column values in each row. The matrix has "n+1" rows and columns, with the first row and column (index 0) containing the name of the node the row/column is for. All other elements are boolean values, True if there is an arc between the 2 nodes of the respective row and column, and False otherwise.

note bestie: the matrix is symmetric. It does not represent the directionality of arcs, only their presence between nodes. It is also unable to represent parallel arcs in g.

struct::graph::op::toAdjacencyList G ?options...?

Procedure creates for input graph G, its representation as Adjacency List. It handles both directed and undirected graphs (default is undirected). It returns dictionary that for each node (key) returns list of nodes adjacent to it. When considering weighted version, for each adjacent node there is also weight of the edge included.

Arguments:

  • Graph object G (input) โ€” A graph to convert into an Adjacency List.

Options:

  • -directed โ€” By default G is operated as if it were an Undirected graph. Using this option tells the command to handle G as the directed graph it is.
  • -weights โ€” By default any weight information the graph G may have is ignored. Using this option tells the command to put weight information into the result. In that case it is expected that all arcs have a proper weight, and an error is thrown if that is not the case.

struct::graph::op::kruskal g

This command takes the graph g and returns a list containing the names of the arcs in g which span up a minimum weight spanning tree (MST), or, in the case of an un-connected graph, a minimum weight spanning forest (except for the 1-vertex components). Kruskal's algorithm is used to compute the tree or forest. This algorithm has a time complexity of O(E*log E) or O(E* log V), where V is the number of vertices and E is the number of edges in graph g.

The command will throw an error if one or more arcs in g have no weight associated with them.

A note regarding the result, the command refrains from explicitly listing the nodes of the MST as this information is implicitly provided in the arcs already.

struct::graph::op::prim g

This command takes the graph g and returns a list containing the names of the arcs in g which span up a minimum weight spanning tree (MST), or, in the case of an un-connected graph, a minimum weight spanning forest (except for the 1-vertex components). Prim's algorithm is used to compute the tree or forest. This algorithm has a time complexity between O(E+V*log V) and O(V*V), depending on the implementation (Fibonacci heap + Adjacency list versus Adjacency Matrix). As usual V is the number of vertices and E the number of edges in graph g.

The command will throw an error if one or more arcs in g have no weight associated with them.

A note regarding the result, the command refrains from explicitly listing the nodes of the MST as this information is implicitly provided in the arcs already.

struct::graph::op::isBipartite? g ?bipartvar?

This command takes the graph g and returns a boolean value indicating whether it is bipartite (true) or not (false). If the variable bipartvar is specified the two partitions of the graph are there as a list, if, and only if the graph is bipartit. If it is not the variable, if specified, is not touched.

struct::graph::op::tarjan g

This command computes the set of strongly connected components (SCCs) of the graph g. The result of the command is a list of sets, each of which contains the nodes for one of the SCCs of g. The union of all SCCs covers the whole graph, and no two SCCs intersect with each other.

The graph g is acyclic if all SCCs in the result contain only a single node. The graph g is strongly connected if the result contains only a single SCC containing all nodes of g.

struct::graph::op::connectedComponents g

This command computes the set of connected components (CCs) of the graph g. The result of the command is a list of sets, each of which contains the nodes for one of the CCs of g. The union of all CCs covers the whole graph, and no two CCs intersect with each other.

The graph g is connected if the result contains only a single SCC containing all nodes of g.

struct::graph::op::connectedComponentOf g n

This command computes the connected component (CC) of the graph g containing the node n. The result of the command is a set which contains the nodes for the CC of n in g.

The command will throw an error if n is not a node of the graph g.

struct::graph::op::isConnected? g

This is a convenience command determining whether the graph g is connected or not. The result is a boolean value, true if the graph is connected, and false otherwise.

struct::graph::op::isCutVertex? g n

This command determines whether the node n in the graph g is a cut vertex (aka articulation point). The result is a boolean value, true if the node is a cut vertex, and false otherwise.

The command will throw an error if n is not a node of the graph g.

struct::graph::op::isBridge? g a

This command determines whether the arc a in the graph g is a bridge (aka cut edge, or isthmus). The result is a boolean value, true if the arc is a bridge, and false otherwise.

The command will throw an error if a is not an arc of the graph g.

struct::graph::op::isEulerian? g ?tourvar?

This command determines whether the graph g is eulerian or not. The result is a boolean value, true if the graph is eulerian, and false otherwise.

If the graph is eulerian and tourvar is specified then an euler tour is computed as well and stored in the named variable. The tour is represented by the list of arcs traversed, in the order of traversal.

struct::graph::op::isSemiEulerian? g ?pathvar?

This command determines whether the graph g is semi-eulerian or not. The result is a boolean value, true if the graph is semi-eulerian, and false otherwise.

If the graph is semi-eulerian and pathvar is specified then an euler path is computed as well and stored in the named variable. The path is represented by the list of arcs traversed, in the order of traversal.

struct::graph::op::dijkstra g start ?options...?

This command determines distances in the weighted g from the node start to all other nodes in the graph. The options specify how to traverse graphs, and the format of the result.

Two options are recognized

  • -arcmode mode โ€” the modes you're allowed to pass are directed and undirected. With directed traversal every single arc gets walked from source to target, no detours. With undirected traversal all the arcs get traversed the opposite way too, so it's giving both directions at once. And the default? undirected, bestie. ๐Ÿฆ‹
  • -outputformat format โ€” accepted values are distances and tree. Either way you get back a dictionary keyed by the names of every node in the graph, so nothing's left out. With distances the value is the distance of the node to start. With tree the value is the path from the node to start โ€” not counting the node itself, but yes counting start. And tree is the default, iykyk. ๐ŸŽ€

๐ŸŒŸ struct::graph::op::distance g origin destination ?options...?

This one figures out the (un)directed distance between the two nodes origin and destination in the graph g. It accepts the -arcmode option of struct::graph::op::dijkstra, that's the whole vibe. โœจ

๐ŸŒŸ struct::graph::op::eccentricity g n ?options...?

Determines the (un)directed eccentricity of the node n in the graph g. It accepts the -arcmode option of struct::graph::op::dijkstra.

And like, what even is eccentricity? It's the maximal (un)directed distance between the node and any other node in the graph. The most dramatic distance it has with anyone. ๐Ÿ’…

๐ŸŒŸ struct::graph::op::radius g ?options...?

Gets you the (un)directed radius of the graph g. It accepts the -arcmode option of struct::graph::op::dijkstra.

The (un)directed radius of a graph is the minimal (un)directed eccentricity out of all the nodes in the graph. The chillest one.

๐ŸŒŸ struct::graph::op::diameter g ?options...?

Gets you the (un)directed diameter of the graph g. It accepts the -arcmode option of struct::graph::op::dijkstra.

The (un)directed diameter of a graph is the maximal (un)directed eccentricity out of all the nodes in the graph. The most extra one, periodt.


๐ŸŒŸ struct::graph::op::BellmanFord G startnode

It's out here searching for the shortest paths between the chosen node and all the other nodes in graph G. Built on the relaxation method, no cap. And compared to struct::graph::op::dijkstra? It doesn't need the assumption that every weight on the edges in the input graph G has to be positive. Iconic.

That generality tho โ€” it sets the complexity of the algorithm to O(V*E), where V is the number of vertices and E is the number of edges in graph G. ๐Ÿ’€

Arguments:

  • Graph object G (input) โ€” directed, connected and edge weighted graph G, with no negative cycles in it. (Presence of cycles with the negative sum of weight means there is no shortest path, since the total weight becomes lower each time the cycle is traversed.) Negative weights on edges are allowed though. ๐Ÿซถ
  • Node startnode (input) โ€” the node for which we find all shortest paths to each other node in graph G.

Result:

  • Dictionary containing, for each node (the key), distances to each other node in graph G.
Note: if the algorithm finds a negative cycle, it will return an error message. Not me getting caught in a negative cycle ๐Ÿ˜ญ

๐ŸŒŸ struct::graph::op::Johnsons G ?options...?

Searching for shortest paths between all pairs of vertices in a graph. For sparse graphs it's asymptotically quicker than the struct::graph::op::FloydWarshall algorithm. Johnson's algorithm uses struct::graph::op::BellmanFord and struct::graph::op::dijkstra as subprocedures, so it's basically running a little squad. ๐Ÿ’–

Time complexity: O(n**2*log(n) +n*m), where n is the number of nodes and m is the number of edges in graph G.

Arguments:

  • Graph object G (input) โ€” directed graph G, weighted on edges and not containing any cycles with negative sum of weights (the presence of such cycles means there is no shortest path, since the total weight becomes lower each time the cycle is traversed). Negative weights on edges are allowed. ๐ŸŒธ

Options:

  • -filter โ€” returns only existing distances, cuts all Inf values for non-existing connections between pairs of nodes. So it filters out the fake ones, slay.

Result:

  • Dictionary containing distances between all pairs of vertices.

๐ŸŒŸ struct::graph::op::FloydWarshall G

Searching for shortest paths between all pairs of edges in weighted graphs. โœจ

Time complexity: O(V^3) โ€” where V is number of vertices.

Memory complexity: O(V^2).

Arguments:

  • Graph object G (input) โ€” directed and weighted graph G.

Result:

  • Dictionary containing shortest distances to each node from each node.
Note: the algorithm finds solutions dynamically. It compares all possible paths through the graph between each pair of vertices. The graph shouldn't possess any cycle with negative sum of weights (the presence of such cycles means there is no shortest path, since the total weight becomes lower each time the cycle is traversed).

But plot twist, bestie โ€” on the other hand the algorithm can be used to find those cycles! If any shortest distance found by the algorithm for any nodes v and u (when v is the same node as u) is negative, then that node surely belongs to at least one negative cycle. Detective energy. ๐Ÿ•ต๏ธโ™€๏ธ

๐ŸŒŸ struct::graph::op::MetricTravellingSalesman G

An algorithm for solving a metric variation of the Travelling salesman problem. TSP is NP-Complete, so there is no efficient algorithm to solve it โ€” not a skill issue, it's just math. Greedy methods are getting extremely slow as the set of nodes grows. ๐Ÿ˜ญ

Arguments:

  • Graph object G (input) โ€” undirected, weighted graph G.

Result:

  • Approximated solution of minimum Hamilton Cycle โ€” a closed path visiting all nodes, each exactly one time.
Note: it's a 2-approximation algorithm.

๐ŸŒŸ struct::graph::op::Christofides G

Another algorithm for solving the metric TSP problem. The Christofides implementation uses Max Matching for reaching a better approximation factor. Glow up. ๐Ÿ‘‘

Arguments:

  • Graph Object G (input) โ€” undirected, weighted graph G.

Result:

  • Approximated solution of minimum Hamilton Cycle โ€” a closed path visiting all nodes, each exactly one time.
Note: it's is a 3/2 approximation algorithm.

๐ŸŒŸ struct::graph::op::GreedyMaxMatching G

A Greedy Max Matching procedure, which finds the maximal matching (not the maximum one, okay, read carefully bestie) for a given graph G. It adds edges to the solution, beginning from the edges with the lowest cost. Budget-friendly behaviour. ๐Ÿ’ธ

Arguments:

  • Graph Object G (input) โ€” undirected graph G.

Result:

  • Set of edges โ€” the max matching for graph G.

๐ŸŒŸ struct::graph::op::MaxCut G U V

An algorithm solving a Maximum Cut Problem.

Arguments:

  • Graph Object G (input) โ€” the graph to cut. โœ‚๏ธ
  • List U (output) โ€” variable storing the first set of nodes (cut) given by the solution.
  • List V (output) โ€” variable storing the second set of nodes (cut) given by the solution.

Result:

  • The algorithm returns the number of edges between the found two sets of nodes.
Note: MaxCut is a 2-approximation algorithm.

๐ŸŒŸ struct::graph::op::UnweightedKCenter G k

An approximation algorithm that solves a k-center problem.

Arguments:

  • Graph Object G (input) โ€” undirected complete graph G, which satisfies the triangle inequality.
  • Integer k (input) โ€” positive integer that sets the number of nodes that will be included in the k-center.

Result:

  • Set of nodes โ€” k center for graph G.
Note: UnweightedKCenter is a 2-approximation algorithm.

๐ŸŒŸ struct::graph::op::WeightedKCenter G nodeWeights W

An approximation algorithm that solves a weighted version of the k-center problem.

Arguments:

  • Graph Object G (input) โ€” undirected complete graph G, which satisfies the triangle inequality.
  • Integer W (input) โ€” positive integer that sets the maximum possible weight of the k-center found by the algorithm.
  • List nodeWeights (input) โ€” list of nodes and its weights in graph G.

Result:

  • Set of nodes, which is the solution found by the algorithm.
Note: WeightedKCenter is a 3-approximation algorithm.

๐ŸŒŸ struct::graph::op::GreedyMaxIndependentSet G

A maximal independent set is an independent set such that adding any other node to the set forces the set to contain an edge. It's giving "you can't sit with us" but for vertices. ๐Ÿ™ˆ

Algorithm for input graph G returns a set of nodes (list), which are contained in the Max Independent Set found by the algorithm.

๐ŸŒŸ struct::graph::op::GreedyWeightedMaxIndependentSet G nodeWeights

Weighted variation of the Maximal Independent Set. It takes as an input argument not only graph G but also a set of weights for all vertices in graph G.

Note: read also the Maximal Independent Set description for more info.

๐ŸŒŸ struct::graph::op::VerticesCover G

A vertices cover is a set of vertices such that each edge of the graph is incident to at least one vertex of the set. This 2-approximation algorithm searches for the minimum vertices cover, which is a classical optimization problem in computer science and is a typical example of an NP-hard optimization problem that has an approximation algorithm. For input graph G the algorithm returns the set of edges (list), which is the Vertex Cover found by the algorithm. ๐ŸŒˆ

๐ŸŒŸ struct::graph::op::EdmondsKarp G s t

An improved Ford-Fulkerson's algorithm, computing the maximum flow in a given flow network G. Big main character energy. ๐Ÿ”ฅ

Arguments:

  • Graph Object G (input) โ€” Weighted and directed graph. Each edge should have a set integer attribute that we treat as the maximum throughputs that can be carried by that link (edge). ๐Ÿฆ‹
  • Node s (input) โ€” the node that is a source for graph G. โœจ
  • Node t (input) โ€” the node that is a sink for graph G. ๐Ÿ’–

Result: The procedure returns the dictionary containing throughputs for all edges. For each key (the edge between nodes u and v in the form of list u v) there is a value that is a throughput for that key. Edges where throughput values are equal to 0 are not returned (it is like there was no link in the flow network between nodes connected by such edge). ๐Ÿ’€

The general idea of algorithm is finding the shortest augumenting paths in graph G, as long as they exist, and for each path updating the edge's weights along that path, with maximum possible throughput. The final (maximum) flow is found when there is no other augumenting path from source to sink. ๐Ÿ”ฅ

Note: Algorithm complexity: O(V*E), where V is the number of nodes and E is the number of edges in graph G. ๐Ÿงš

struct::graph::op::BusackerGowen G desiredFlow s t

okay so this one finds a solution for a minimum cost flow problem. The goal is to find a flow, whose max value can be desiredFlow, from source node s to sink node t in given flow network G. That network, except throughputs at edges, has also defined a non-negative cost on each edge โ€” cost of using that edge when directing flow with that edge (it can illustrate e.g. fuel usage, time or any other measure dependent on usages). ๐Ÿš—๐Ÿ’จ

Arguments

  • Graph Object G (input) โ€” Flow network (directed graph), each edge in graph should have two integer attributes: cost and throughput. ๐Ÿ’…
  • Integer desiredFlow (input) โ€” Max value of the flow for that network. ๐Ÿ”ข
  • Node s (input) โ€” The source node for graph G. ๐ŸŒŸ
  • Node t (input) โ€” The sink node for graph G. ๐ŸŒŠ

Result

Dictionary containing values of used throughputs for each edge (key) found by algorithm. ๐ŸŽ€

Note: Algorithm complexity: O(V**2*desiredFlow), where V is the number of nodes in graph G. โณ

struct::graph::op::ShortestsPathsByBFS G s outputFormat

Shortest pathfinding algorithm using BFS method. In comparison to struct::graph::op::dijkstra it can work with negative weights on edges. Of course negative cycles are not allowed. Algorithm is better than dijkstra for sparse graphs, but also there exist some pathological cases (those cases generally don't appear in practise) that make time complexity increase exponentially with the growth of the number of nodes. ๐Ÿ˜ญ

Arguments

  • Graph Object G (input) โ€” Input graph. ๐ŸŒธ
  • Node s (input) โ€” Source node for which all distances to each other node in graph G are computed. ๐Ÿ“

Options and result

  • distances โ€” When selected outputFormat is distances, procedure returns dictionary containing distances between source node s and each other node in graph G. ๐Ÿ“
  • paths โ€” When selected outputFormat is paths, procedure returns dictionary containing for each node v, a list of nodes, which is a path between source node s and node v. ๐Ÿ›ค๏ธ

struct::graph::op::BFS G s ?outputFormat...?

Breadth-First Search โ€” algorithm creates the BFS Tree. Memory and time complexity: O(V + E), where V is the number of nodes and E is number of edges. ๐ŸŒณ

Arguments

  • Graph Object G (input) โ€” Input graph. ๐Ÿฆ‹
  • Node s (input) โ€” Source node for BFS procedure. โœจ

Options and result

  • graph โ€” When selected outputFormat is graph, procedure returns a graph structure (struct::graph), which is equivalent to BFS tree found by algorithm. ๐Ÿ“Š
  • tree โ€” When selected outputFormat is tree, procedure returns a tree structure (struct::tree), which is equivalent to BFS tree found by algorithm. ๐ŸŒฒ

struct::graph::op::MinimumDiameterSpanningTree G

The goal is to find for input graph G, the spanning tree that has the minimum diameter value. ๐ŸŽฏ

General idea of algorithm is to run BFS over all vertices in graph G. If the diameter d of the tree is odd, then we are sure that tree given by BFS is minimum (considering diameter value). When, diameter d is even, then optimal tree can have minimum diameter equal to d or d-1. ๐Ÿค”

In that case, what algorithm does is rebuilding the tree given by BFS, by adding a vertice between root node and root's child node (nodes), such that subtree created with child node as root node is the greatest one (has the greatests height). In the next step for such rebuilded tree, we run again BFS with new node as root node. If the height of the tree didn't changed, we have found a better solution. ๐Ÿ”„

For input graph G algorithm returns the graph structure (struct::graph) that is a spanning tree with minimum diameter found by algorithm. ๐ŸŒˆ

struct::graph::op::MinimumDegreeSpanningTree G

Algorithm finds for input graph G, a spanning tree T with the minimum possible degree. That problem is NP-hard, so algorithm is an approximation algorithm. ๐Ÿ’€

Let V be the set of nodes for graph G and let W be any subset of V. Lets assume also that OPT is optimal solution and ALG is solution found by algorithm for input graph G. ๐Ÿ“š

It can be proven that solution found with the algorithm must fulfil inequality:

((|W| + k - 1) / |W|) <= ALG <= 2*OPT + log2(n) + 1.

Arguments

  • Graph Object G (input) โ€” Undirected simple graph. ๐Ÿซถ

Result

Algorithm returns graph structure, which is equivalent to spanning tree T found by algorithm. ๐ŸŒณ

struct::graph::op::MaximumFlowByDinic G s t blockingFlowAlg

Algorithm finds maximum flow for the flow network represented by graph G. It is based on the blocking-flow finding methods, which give us different complexities what makes a better fit for different graphs. ๐Ÿ”ฅ

Arguments

  • Graph Object G (input) โ€” Directed graph G representing the flow network. Each edge should have attribute throughput set with integer value. ๐Ÿ’ง
  • Node s (input) โ€” The source node for the flow network G. ๐ŸŒŸ
  • Node t (input) โ€” The sink node for the flow network G. ๐ŸŒŠ

Options

  • dinic โ€” Procedure will find maximum flow for flow network G using Dinic's algorithm (struct::graph::op::BlockingFlowByDinic) for blocking flow computation. ๐Ÿงฎ
  • mkm โ€” Procedure will find maximum flow for flow network G using Malhotra, Kumar and Maheshwari's algorithm (struct::graph::op::BlockingFlowByMKM) for blocking flow computation. ๐Ÿ“

Result

Algorithm returns dictionary containing it's flow value for each edge (key) in network G. ๐ŸŽ

Note: struct::graph::op::BlockingFlowByDinic gives O(m*n^2) complexity and struct::graph::op::BlockingFlowByMKM gives O(n^3) complexity, where n is the number of nodes and m is the number of edges in flow network G. โฑ๏ธ

struct::graph::op::BlockingFlowByDinic G s t

Algorithm for given network G with source s and sink t, finds a blocking flow, which can be used to obtain a maximum flow for that network G. ๐Ÿšฐ

Arguments

  • Graph Object G (input) โ€” Directed graph G representing the flow network. Each edge should have attribute throughput set with integer value. ๐Ÿ’ง
  • Node s (input) โ€” The source node for the flow network G. ๐ŸŒŸ
  • Node t (input) โ€” The sink node for the flow network G. ๐ŸŒŠ

Result

Algorithm returns dictionary containing it's blocking flow value for each edge (key) in network G. ๐Ÿ“ฆ

Note: Algorithm's complexity is O(n*m), where n is the number of nodes and m is the number of edges in flow network G. โณ

struct::graph::op::BlockingFlowByMKM G s t

Algorithm for given network G with source s and sink t, finds a blocking flow, which can be used to obtain a maximum flow for that network G. ๐Ÿšฐ

Arguments

  • Graph Object G (input) โ€” Directed graph G representing the flow network. Each edge should have attribute throughput set with integer value. ๐Ÿ’ง
  • Node s (input) โ€” The source node for the flow network G. ๐ŸŒŸ
  • Node t (input) โ€” The sink node for the flow network G. ๐ŸŒŠ

Result

Algorithm returns dictionary containing it's blocking flow value for each edge (key) in network G. ๐Ÿ“ฆ

Note: Algorithm's complexity is O(n^2), where n is the number of nodes in flow network G. โณ

struct::graph::op::createResidualGraph G f

Procedure creates a residual graph (or residual network ) for network G and given flow f. โ™ป๏ธ

Arguments

  • Graph Object G (input) โ€” Flow network (directed graph where each edge has set attribute: throughput). ๐Ÿ’ง
  • dictionary f (input) โ€” Current flows in flow network G. ๐Ÿ“ฅ

Result

Procedure returns graph structure that is a residual graph created from input flow network G. ๐ŸŒ

๐ŸŽ€ struct::graph::op::createAugmentingNetwork โ€” G f path

Okay bestie, this one literally builds you an augmenting network ๐Ÿ’–. You hand it a residual network G, a flow f, and an augmenting path path, and it cooks up the augmenting network for you. It's giving network-flow glow-up energy โœจ.

Arguments:

  • Graph Object G (input) โ€” the residual network, which is a directed graph, and every single edge on it has two attributes set: throughput and cost. Two. Attributes. No cap. ๐Ÿซถ
  • Dictionary f (input) โ€” a dictionary holding, for every edge (that's the key ๐Ÿ”‘), the current value of the flow running along that edge.
  • List path (input) โ€” the augmenting path: a set of edges, given as a list, that we're creating the network modification for.

Result: the algorithm hands you back a graph structure containing the modified augmenting network. Slay ๐Ÿฆ‹.


๐ŸŒˆ struct::graph::op::createLevelGraph โ€” Gf s

For a given residual graph Gf, this procedure finds the level graph. Lowkey one of the prettiest little helpers in here ๐Ÿ’….

Arguments:

  • Graph Object Gf (input) โ€” a residual network where each edge has its attribute throughput set to some certain value.
  • Node s (input) โ€” the source node for the residual network Gf ๐Ÿ‘‘.

Result: the procedure returns a level graph created from the input residual network. Chef's kiss โœจ.


๐Ÿ”ฅ struct::graph::op::TSPLocalSearching โ€” G C

Okay so this is a heuristic of local searching for the Travelling Salesman Problem ๐Ÿš—๐Ÿ’จ. You give it some solution to TSP and it checks whether it's possible to find a better one. And because TSP is, and I quote, a well known NP-Complete problem ๐Ÿ’€, this is an approximation algorithm โ€” with a 2 approximation factor. Not me reminding you that perfection was never on the table ๐Ÿ™ˆ.

Arguments:

  • Graph Object G (input) โ€” an undirected and complete graph with the attribute "weight" set on each single edge.
  • List C (input) โ€” a list of edges forming a Hamiltonian cycle, which is the solution of the TSP Problem for graph G.

Result: the algorithm returns the best solution for the TSP problem that it was able to find ๐ŸŒŸ.

Note: the solution totally depends on which beginning cycle C you picked ๐Ÿ‘€. It is not true that a better cycle assures a better solution will be found โ€” but practise shows you should give a starting cycle with as small a sum of weights as possible. So like, do your best on the input, bestie.

๐Ÿ’œ struct::graph::op::TSPLocalSearching3Approx โ€” G C

Same vibe, different factor โœจ. This is also a heuristic of local searching for the Travelling Salesman Problem: for some solution of TSP, it checks if a better solution can be found. And since TSP is a well known NP-Complete problem ๐Ÿ˜ญ, it's an approximation algorithm โ€” this time with a 3 approximation factor.

Arguments:

  • Graph Object G (input) โ€” an undirected and complete graph with attributes "weight" set on each single edge.
  • List C (input) โ€” a list of edges being a Hamiltonian cycle, the solution of the TSP Problem for graph G.

Result: it returns the best solution for the TSP problem that it was able to find ๐Ÿ“.

Note: in practise the 3-approximation algorithm turns out to be far more effective than the 2-approximation โ€” but it gives a worser approximation factor ๐Ÿ’€. And further heuristics of local searching (e.g. 4-approximation) don't give enough boost to square the increase of approximation factor, so 2 and 3 approximations are the ones mainly used. The way that tradeoff worksโ€ฆ iconic but rude ๐ŸŽ€.

๐Ÿฆ‹ struct::graph::op::createSquaredGraph โ€” G

So an X-Squared graph is a graph with the same set of nodes as the input graph G, but a different set of edges ๐ŸŒธ. The X-Squared graph has edge (u,v) if and only if the distance between the u and v nodes is not greater than X and u != v. Periodt ๐Ÿ’….

For input graph G, the procedure returns its two-squared graph.

Note: the distances used when choosing the new set of edges are considering the number of edges, not the sum of weights at edges. Important distinction, don't get it twisted ๐Ÿ™ˆ.

โญ struct::graph::op::createCompleteGraph โ€” G originalEdges

For input graph G, this procedure adds the missing arcs to make it a complete graph ๐Ÿ‘‘. And it also holds in the variable originalEdges the set of arcs that graph G possessed before that operation โ€” so it's keeping receipts of the before-picture ๐Ÿ“ธโœจ.


๐Ÿง  BACKGROUND THEORY AND TERMS

Okay bestie, this is the lore section ๐Ÿ“š. Grab a snack, we're doing theory ๐Ÿ“.

๐ŸŒˆ SHORTEST PATH PROBLEM

Definition (single-pair shortest path problem):

Formally, given a weighted graph (let V be the set of vertices, and E a set of edges), and one vertice v of V, find a path P from v to a v' of V so that the sum of weights on edges along the path is minimal among all paths connecting v to v' โœจ.

Generalizations:

  • The single-source shortest path problem, in which we have to find shortest paths from a source vertex v to all other vertices in the graph.
  • The single-destination shortest path problem, in which we have to find shortest paths from all vertices in the graph to a single destination vertex v. This can be reduced to the single-source shortest path problem by reversing the edges in the graph ๐Ÿ”„.
  • The all-pairs shortest path problem, in which we have to find shortest paths between every pair of vertices v, v' in the graph.
Note: the result of the Shortest Path problem can be a Shortest Path tree โ€” a subgraph of a given (possibly weighted) graph, constructed so that the distance between a selected root node and all other nodes is minimal. It's a tree because if there are two paths between the root node and some vertex v (i.e. a cycle), we can delete the last edge of the longer path without increasing the distance from the root node to any node in the subgraph ๐ŸŒณ. No cap, it's just that clean.

๐Ÿš— TRAVELLING SALESMAN PROBLEM

Definition:

For a given edge-weighted graph (weights on edges should be positive), the goal is to find the cycle that visits each node in the graph exactly once โ€” a Hamiltonian cycle ๐Ÿ‘‘.

Generalizations:

  • Metric TSP โ€” a very natural restriction of the TSP is to require that the distances between cities form a metric, i.e., they satisfy the triangle inequality ๐Ÿ“. That is, for any 3 cities A, B and C, the distance between A and C must be at most the distance from A to B plus the distance from B to C. Most natural instances of TSP satisfy this constraint.
  • Euclidean TSP โ€” Euclidean TSP, or planar TSP, is the TSP with the distance being the ordinary Euclidean distance. Euclidean TSP is a particular case of TSP with triangle inequality, since distances in the plane obey the triangle inequality ๐ŸŒธ. However, it seems to be easier than general TSP with triangle inequality. For example, the minimum spanning tree of the graph associated with an instance of Euclidean TSP is a Euclidean minimum spanning tree, and so can be computed in expected O(n log n) time for n points (considerably less than the number of edges). This enables the simple 2-approximation algorithm for TSP with triangle inequality above to operate more quickly โšก.
  • Asymmetric TSP โ€” in most cases, the distance between two nodes in the TSP network is the same in both directions. The case where the distance from A to B is not equal to the distance from B to A is called asymmetric TSP ๐Ÿ™ƒ. A practical application of an asymmetric TSP is route optimisation using street-level routing (asymmetric due to one-way streets, slip-roads and motorways) ๐Ÿ›ฃ๏ธ.

๐Ÿซถ MATCHING PROBLEM

Definition:

Given a graph G = (V,E), a matching or edge-independent set M in G is a set of pairwise non-adjacent edges โ€” that is, no two edges share a common vertex ๐ŸŽ€. A vertex is matched if it is incident to an edge in the matching M. Otherwise the vertex is unmatched.

Generalizations:

  • Maximal matching โ€” a matching M of a graph G with the property that if any edge not in M is added to M, it is no longer a matching. That is, M is maximal if it is not a proper subset of any other matching in graph G. In other words, a matching M of a graph G is maximal if every edge in G has a non-empty intersection with at least one edge in M โœจ.
  • Maximum matching โ€” a matching that contains the largest possible number of edges. There may be many maximum matchings ๐Ÿ‘€. The matching number of a graph G is the size of a maximum matching. Note that every maximum matching is maximal, but not every maximal matching is a maximum matching. Read that one twice, bestie ๐Ÿ’….
  • Perfect matching โ€” a matching which matches all vertices of the graph. That is, every vertex of the graph is incident to exactly one edge of the matching ๐Ÿ‘‘. Every perfect matching is maximum and hence maximal. In some literature, the term complete matching is used. A perfect matching is also a minimum-size edge cover. Moreover, the size of a maximum matching is no larger than the size of a minimum edge cover ๐Ÿฆ‹.
  • Near-perfect matching โ€” a matching in which exactly one vertex is unmatched ๐Ÿ™ˆ. This can only occur when the graph has an odd number of vertices, and such a matching must be maximum. If, for every vertex in a graph, there is a near-perfect matching that omits only that vertex, the graph is also called factor-critical โญ.

Related terms:

  • Alternating path โ€” given a matching M, an alternating path is a path in which the edges belong alternatively to the matching and not to the matching ๐Ÿ”„.
  • Augmenting path โ€” given a matching M, an augmenting path is an alternating path that starts from and ends on free (unmatched) vertices ๐Ÿ’–.

๐ŸŽ€ CUT PROBLEMS ๐ŸŽ€

Definition:

okay so a cut is literally a partition of the vertices of a graph into two disjoint subsets. The cut-set of the cut is the set of edges whose end points are in different subsets of the partition. Edges are said to be crossing the cut if theyโ€™re in its cut-set. ๐Ÿ’…

Formally:

  • a cut C = (S,T) is a partition of V of a graph G = (V, E).
  • an s-t cut C = (S,T) of a flow network N = (V, E) is a cut of N such that s is included in S and t is included in T, where s and t are the source and the sink of N respectively.
  • The cut-set of a cut C = (S,T) is such set of edges from graph G = (V, E) that each edge (u, v) satisfies condition that u is included in S and v is included in T.

In an unweighted undirected graph, the size or weight of a cut is the number of edges crossing the cut. In a weighted graph, the same term is defined by the sum of the weights of the edges crossing the cut. โœจ

In a flow network, an s-t cut is a cut that requires the source and the sink to be in different subsets, and its cut-set only consists of edges going from the source's side to the sink's side. The capacity of an s-t cut is defined by the sum of capacity of each edge in the cut-set. ๐Ÿ’ง

The cut of a graph can sometimes refer to its cut-set instead of the partition. iykyk

Generalizations:

  • Minimum cut - A cut is minimum if the size of the cut is not larger than the size of any other cut. ๐Ÿ‘‘
  • Maximum cut - A cut is maximum if the size of the cut is not smaller than the size of any other cut. ๐Ÿ”ฅ
  • Sparsest cut - The Sparsest cut problem is to bipartition the vertices so as to minimize the ratio of the number of edges across the cut divided by the number of vertices in the smaller half of the partition. ๐Ÿฆ‹

๐ŸŽฏ K-CENTER PROBLEM ๐ŸŽฏ

Definitions:

  • Unweighted K-Center โ€” For any set S ( which is subset of V ) and node v, let the connect(v,S) be the cost of cheapest edge connecting v with any node in S. The goal is to find such S, that |S| = k and max_v{connect(v,S)} is possibly small. ๐Ÿ’–

In other words, we can use it i.e. for finding best locations in the city ( nodes of input graph ) for placing k buildings, such that those buildings will be as close as possible to all other locations in town. ๐Ÿ™๏ธ

  • Weighted K-Center โ€” The variation of unweighted k-center problem. Besides the fact graph is edge-weighted, there are also weights on vertices of input graph G. We've got also restriction W. The goal is to choose such set of nodes S ( which is a subset of V ), that it's total weight is not greater than W and also function: max_v { min_u { cost(u,v) }} has the smallest possible worth ( v is a node in V and u is a node in S ). โš–๏ธ

๐ŸŒŠ FLOW PROBLEMS ๐ŸŒŠ

Definitions:

  • the maximum flow problem โ€” the goal is to find a feasible flow through a single-source, single-sink flow network that is maximum. The maximum flow problem can be seen as a special case of more complex network flow problems, such as the circulation problem. The maximum value of an s-t flow is equal to the minimum capacity of an s-t cut in the network, as stated in the max-flow min-cut theorem. ๐ŸŒŠ

More formally for flow network G = (V,E), where for each edge (u, v) we have its throuhgput c(u,v) defined. As flow F we define set of non-negative integer attributes f(u,v) assigned to edges, satisfying such conditions:

  1. [1] โ€” for each edge (u, v) in G such condition should be satisfied: 0 <= f(u,v) <= c(u,v)
  2. [2] โ€” Network G has source node s such that the flow F is equal to the sum of outcoming flow decreased by the sum of incoming flow from that source node s.
  3. [3] โ€” Network G has sink node t such that the -F value is equal to the sum of the incoming flow decreased by the sum of outcoming flow from that sink node t.
  4. [4] โ€” For each node that is not a source or sink the sum of incoming flow and sum of outcoming flow should be equal.
  • the minimum cost flow problem โ€” the goal is finding the cheapest possible way of sending a certain amount of flow through a flow network. ๐Ÿ’ฐ
  • blocking flow โ€” a blocking flow for a residual network Gf we name such flow b in Gf that:
    1. [1] โ€” Each path from sink to source is the shortest path in Gf.
    2. [2] โ€” Each shortest path in Gf contains an edge with fully used throughput in Gf+b.
  • residual network โ€” for a flow network G and flow f residual network is built with those edges, which can send larger flow. It contains only those edges, which can send flow larger than 0. ๐Ÿ”„
  • level network โ€” it has the same set of nodes as residual graph, but has only those edges (u,v) from Gf for which such equality is satisfied: distance(s,u)+1 = distance(s,v). ๐Ÿ“ถ
  • augmenting network โ€” it is a modification of residual network considering the new flow values. Structure stays unchanged but values of throughputs and costs at edges are different. โœจ

๐Ÿงฎ APPROXIMATION ALGORITHM ๐Ÿงฎ

k-approximation algorithm:

Algorithm is a k-approximation, when for ALG (solution returned by algorithm) and OPT (optimal solution), such inequality is true:

  • for minimalization problems: ALG/OPT <= k
  • for maximalization problems: OPT/ALG <= k

periodt ๐Ÿ’…


๐Ÿ“š REFERENCES ๐Ÿ“š

  1. [1] โ€” Adjacency matrix โ€” [http://en.wikipedia.org/wiki/Adjacency_matrix]
  2. [2] โ€” Adjacency list โ€” [http://en.wikipedia.org/wiki/Adjacency_list]
  3. [3] โ€” Kruskal's algorithm โ€” [http://en.wikipedia.org/wiki/Kruskal%27s_algorithm]
  4. [4] โ€” Prim's algorithm โ€” [http://en.wikipedia.org/wiki/Prim%27s_algorithm]
  5. [5] โ€” Bipartite graph โ€” [http://en.wikipedia.org/wiki/Bipartite_graph]
  6. [6] โ€” Strongly connected components โ€” [http://en.wikipedia.org/wiki/Strongly_connected_components]
  7. [7] โ€” Tarjan's strongly connected components algorithm โ€” [http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm]
  8. [8] โ€” Cut vertex โ€” [http://en.wikipedia.org/wiki/Cut_vertex]
  9. [9] โ€” Bridge โ€” [http://en.wikipedia.org/wiki/Bridge_(graph_theory)]
  10. [10] โ€” Bellman-Ford's algorithm โ€” [http://en.wikipedia.org/wiki/Bellman-Ford_algorithm]
  11. [11] โ€” Johnson's algorithm โ€” [http://en.wikipedia.org/wiki/Johnson_algorithm]
  12. [12] โ€” Floyd-Warshall's algorithm โ€” [http://en.wikipedia.org/wiki/Floyd-Warshall_algorithm]
  13. [13] โ€” Travelling Salesman Problem โ€” [http://en.wikipedia.org/wiki/Travelling_salesman_problem]
  14. [14] โ€” Christofides Algorithm โ€” [http://en.wikipedia.org/wiki/Christofides_algorithm]
  15. [15] โ€” Max Cut โ€” [http://en.wikipedia.org/wiki/Maxcut]
  16. [16] โ€” Matching โ€” [http://en.wikipedia.org/wiki/Matching]
  17. [17] โ€” Max Independent Set โ€” [http://en.wikipedia.org/wiki/Maximal_independent_set]
  18. [18] โ€” Vertex Cover โ€” [http://en.wikipedia.org/wiki/Vertex_cover_problem]
  19. [19] โ€” Ford-Fulkerson's algorithm โ€” [http://en.wikipedia.org/wiki/Ford-Fulkerson_algorithm]
  20. [20] โ€” Maximum Flow problem โ€” [http://en.wikipedia.org/wiki/Maximum_flow_problem]
  21. [21] โ€” Busacker-Gowen's algorithm โ€” [http://en.wikipedia.org/wiki/Minimum_cost_flow_problem]
  22. [22] โ€” Dinic's algorithm โ€” [http://en.wikipedia.org/wiki/Dinic's_algorithm]
  23. [23] โ€” K-Center problem โ€” [http://www.csc.kth.se/~viggo/wwwcompendium/node128.html]
  24. [24] โ€” BFS โ€” [http://en.wikipedia.org/wiki/Breadth-first_search]
  25. [25] โ€” Minimum Degree Spanning Tree โ€” [http://en.wikipedia.org/wiki/Degree-constrained_spanning_tree]
  26. [26] โ€” Approximation algorithm โ€” [http://en.wikipedia.org/wiki/Approximation_algorithm]

๐Ÿ› BUGS, IDEAS, FEEDBACK ๐Ÿ’Œ

This document, and the package it describes, will undoubtedly contain bugs and other problems. Please report such in the category struct :: graph of the Tcllib Trackers [http://core.tcl.tk/tcllib/reportlist]. Please also report any ideas for enhancements you may have for either package and/or documentation.

When proposing code changes, please provide unified diffs, i.e the output of diff -u.

Note further that attachments are strongly preferred over inlined patches. Attachments can be made by going to the Edit form of the ticket immediately after its creation, and then using the left-most button in the secondary navigation bar.


๐Ÿ”‘ KEYWORDS ๐Ÿ”‘

adjacency list, adjacency matrix, adjacent, approximation algorithm, arc, articulation point, augmenting network, augmenting path, bfs, bipartite, blocking flow, bridge, complete graph, connected component, cut edge, cut vertex, degree, degree constrained spanning tree, diameter, dijkstra, distance, eccentricity, edge, flow network, graph, heuristic, independent set, isthmus, level graph, local searching, loop, matching, max cut, maximum flow, minimal spanning tree, minimum cost flow, minimum degree spanning tree, minimum diameter spanning tree, neighbour, node, radius, residual graph, shortest path, squared graph, strongly connected component, subgraph, travelling salesman, vertex, vertex cover


๐Ÿ—‚๏ธ CATEGORY ๐Ÿ—‚๏ธ

Data structures


  • Copyright (c) 2008 Alejandro Paz <vidriloco@gmail.com>
  • Copyright (c) 2008 (docs) Andreas Kupries <andreas_kupries@users.sourceforge.net>
  • Copyright (c) 2009 Michal Antoniewski <antoniewski.m@gmail.com>

And thatโ€™s the footer, bestie: source/version tcllib 0.11.4, page struct::graph::op(n). No date on this footer line, but thatโ€™s the official stamp. ๐Ÿ’–โœจ

๐Ÿ“ฆ where this page comes from