In PyMaxflow, the source node ($s$) and sink node ($t$) are always implicitly present in the network. You cannot declare them explicitly. Instead, you work with non-terminal nodes and define their relationship to the implicit terminals using two types of edges:
- Non-terminal edges: Connect non-terminal nodes to each other. Use
add_edge to create these. These edges are created with both forward and backward capacities. - Terminal edges: Connect non-terminal nodes to the implicit source or sink. Use
add_tedge to create these. This allows you to assign weights (penalties) for a node belonging to the source or sink partition.
When using add_edge(node_a, node_b, cap_forward, cap_backward), you define the capacity between two non-terminal nodes. When using add_tedge(node, cap_source, cap_sink), you define the connection to the implicit terminals.
import maxflow
# Create a graph with integer capacities
# (2, 2) are initial estimations for number of nodes and non-terminal edges
g = maxflow.Graph[int](2, 2)
# Add non-terminal nodes
nodes = g.add_nodes(2)
# Add non-terminal edge between node 0 and 1
# capacities: forward=1, backward=2
g.add_edge(nodes[0], nodes[1], 1, 2)
# Add terminal edges
# node 0: capacity to source=2, capacity to sink=5
g.add_tedge(nodes[0], 2, 5)
# node 1: capacity to source=9, capacity to sink=4
g.add_tedge(nodes[1], 9, 4)
# Compute maxflow
flow = g.maxflow()
# Get partition (0 for source, 1 for sink)
print(f"Segment of node 0: {g.get_segment(nodes[0])}")