Spaces:
Running
Running
File size: 22,809 Bytes
b200bda |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 |
"""
Maximum flow (and minimum cut) algorithms on capacitated graphs.
"""
import networkx as nx
from .boykovkolmogorov import boykov_kolmogorov
from .dinitz_alg import dinitz
from .edmondskarp import edmonds_karp
from .preflowpush import preflow_push
from .shortestaugmentingpath import shortest_augmenting_path
from .utils import build_flow_dict
# Define the default flow function for computing maximum flow.
default_flow_func = preflow_push
__all__ = ["maximum_flow", "maximum_flow_value", "minimum_cut", "minimum_cut_value"]
@nx._dispatch(graphs="flowG", edge_attrs={"capacity": float("inf")})
def maximum_flow(flowG, _s, _t, capacity="capacity", flow_func=None, **kwargs):
"""Find a maximum single-commodity flow.
Parameters
----------
flowG : NetworkX graph
Edges of the graph are expected to have an attribute called
'capacity'. If this attribute is not present, the edge is
considered to have infinite capacity.
_s : node
Source node for the flow.
_t : node
Sink node for the flow.
capacity : string
Edges of the graph G are expected to have an attribute capacity
that indicates how much flow the edge can support. If this
attribute is not present, the edge is considered to have
infinite capacity. Default value: 'capacity'.
flow_func : function
A function for computing the maximum flow among a pair of nodes
in a capacitated graph. The function has to accept at least three
parameters: a Graph or Digraph, a source node, and a target node.
And return a residual network that follows NetworkX conventions
(see Notes). If flow_func is None, the default maximum
flow function (:meth:`preflow_push`) is used. See below for
alternative algorithms. The choice of the default function may change
from version to version and should not be relied on. Default value:
None.
kwargs : Any other keyword parameter is passed to the function that
computes the maximum flow.
Returns
-------
flow_value : integer, float
Value of the maximum flow, i.e., net outflow from the source.
flow_dict : dict
A dictionary containing the value of the flow that went through
each edge.
Raises
------
NetworkXError
The algorithm does not support MultiGraph and MultiDiGraph. If
the input graph is an instance of one of these two classes, a
NetworkXError is raised.
NetworkXUnbounded
If the graph has a path of infinite capacity, the value of a
feasible flow on the graph is unbounded above and the function
raises a NetworkXUnbounded.
See also
--------
:meth:`maximum_flow_value`
:meth:`minimum_cut`
:meth:`minimum_cut_value`
:meth:`edmonds_karp`
:meth:`preflow_push`
:meth:`shortest_augmenting_path`
Notes
-----
The function used in the flow_func parameter has to return a residual
network that follows NetworkX conventions:
The residual network :samp:`R` from an input graph :samp:`G` has the
same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
in :samp:`G`.
For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
in :samp:`G` or zero otherwise. If the capacity is infinite,
:samp:`R[u][v]['capacity']` will have a high arbitrary finite value
that does not affect the solution of the problem. This value is stored in
:samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
:samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
The flow value, defined as the total flow into :samp:`t`, the sink, is
stored in :samp:`R.graph['flow_value']`. Reachability to :samp:`t` using
only edges :samp:`(u, v)` such that
:samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
:samp:`s`-:samp:`t` cut.
Specific algorithms may store extra data in :samp:`R`.
The function should supports an optional boolean parameter value_only. When
True, it can optionally terminate the algorithm as soon as the maximum flow
value and the minimum cut can be determined.
Examples
--------
>>> G = nx.DiGraph()
>>> G.add_edge("x", "a", capacity=3.0)
>>> G.add_edge("x", "b", capacity=1.0)
>>> G.add_edge("a", "c", capacity=3.0)
>>> G.add_edge("b", "c", capacity=5.0)
>>> G.add_edge("b", "d", capacity=4.0)
>>> G.add_edge("d", "e", capacity=2.0)
>>> G.add_edge("c", "y", capacity=2.0)
>>> G.add_edge("e", "y", capacity=3.0)
maximum_flow returns both the value of the maximum flow and a
dictionary with all flows.
>>> flow_value, flow_dict = nx.maximum_flow(G, "x", "y")
>>> flow_value
3.0
>>> print(flow_dict["x"]["b"])
1.0
You can also use alternative algorithms for computing the
maximum flow by using the flow_func parameter.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> flow_value == nx.maximum_flow(G, "x", "y", flow_func=shortest_augmenting_path)[
... 0
... ]
True
"""
if flow_func is None:
if kwargs:
raise nx.NetworkXError(
"You have to explicitly set a flow_func if"
" you need to pass parameters via kwargs."
)
flow_func = default_flow_func
if not callable(flow_func):
raise nx.NetworkXError("flow_func has to be callable.")
R = flow_func(flowG, _s, _t, capacity=capacity, value_only=False, **kwargs)
flow_dict = build_flow_dict(flowG, R)
return (R.graph["flow_value"], flow_dict)
@nx._dispatch(graphs="flowG", edge_attrs={"capacity": float("inf")})
def maximum_flow_value(flowG, _s, _t, capacity="capacity", flow_func=None, **kwargs):
"""Find the value of maximum single-commodity flow.
Parameters
----------
flowG : NetworkX graph
Edges of the graph are expected to have an attribute called
'capacity'. If this attribute is not present, the edge is
considered to have infinite capacity.
_s : node
Source node for the flow.
_t : node
Sink node for the flow.
capacity : string
Edges of the graph G are expected to have an attribute capacity
that indicates how much flow the edge can support. If this
attribute is not present, the edge is considered to have
infinite capacity. Default value: 'capacity'.
flow_func : function
A function for computing the maximum flow among a pair of nodes
in a capacitated graph. The function has to accept at least three
parameters: a Graph or Digraph, a source node, and a target node.
And return a residual network that follows NetworkX conventions
(see Notes). If flow_func is None, the default maximum
flow function (:meth:`preflow_push`) is used. See below for
alternative algorithms. The choice of the default function may change
from version to version and should not be relied on. Default value:
None.
kwargs : Any other keyword parameter is passed to the function that
computes the maximum flow.
Returns
-------
flow_value : integer, float
Value of the maximum flow, i.e., net outflow from the source.
Raises
------
NetworkXError
The algorithm does not support MultiGraph and MultiDiGraph. If
the input graph is an instance of one of these two classes, a
NetworkXError is raised.
NetworkXUnbounded
If the graph has a path of infinite capacity, the value of a
feasible flow on the graph is unbounded above and the function
raises a NetworkXUnbounded.
See also
--------
:meth:`maximum_flow`
:meth:`minimum_cut`
:meth:`minimum_cut_value`
:meth:`edmonds_karp`
:meth:`preflow_push`
:meth:`shortest_augmenting_path`
Notes
-----
The function used in the flow_func parameter has to return a residual
network that follows NetworkX conventions:
The residual network :samp:`R` from an input graph :samp:`G` has the
same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
in :samp:`G`.
For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
in :samp:`G` or zero otherwise. If the capacity is infinite,
:samp:`R[u][v]['capacity']` will have a high arbitrary finite value
that does not affect the solution of the problem. This value is stored in
:samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
:samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
The flow value, defined as the total flow into :samp:`t`, the sink, is
stored in :samp:`R.graph['flow_value']`. Reachability to :samp:`t` using
only edges :samp:`(u, v)` such that
:samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
:samp:`s`-:samp:`t` cut.
Specific algorithms may store extra data in :samp:`R`.
The function should supports an optional boolean parameter value_only. When
True, it can optionally terminate the algorithm as soon as the maximum flow
value and the minimum cut can be determined.
Examples
--------
>>> G = nx.DiGraph()
>>> G.add_edge("x", "a", capacity=3.0)
>>> G.add_edge("x", "b", capacity=1.0)
>>> G.add_edge("a", "c", capacity=3.0)
>>> G.add_edge("b", "c", capacity=5.0)
>>> G.add_edge("b", "d", capacity=4.0)
>>> G.add_edge("d", "e", capacity=2.0)
>>> G.add_edge("c", "y", capacity=2.0)
>>> G.add_edge("e", "y", capacity=3.0)
maximum_flow_value computes only the value of the
maximum flow:
>>> flow_value = nx.maximum_flow_value(G, "x", "y")
>>> flow_value
3.0
You can also use alternative algorithms for computing the
maximum flow by using the flow_func parameter.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> flow_value == nx.maximum_flow_value(
... G, "x", "y", flow_func=shortest_augmenting_path
... )
True
"""
if flow_func is None:
if kwargs:
raise nx.NetworkXError(
"You have to explicitly set a flow_func if"
" you need to pass parameters via kwargs."
)
flow_func = default_flow_func
if not callable(flow_func):
raise nx.NetworkXError("flow_func has to be callable.")
R = flow_func(flowG, _s, _t, capacity=capacity, value_only=True, **kwargs)
return R.graph["flow_value"]
@nx._dispatch(graphs="flowG", edge_attrs={"capacity": float("inf")})
def minimum_cut(flowG, _s, _t, capacity="capacity", flow_func=None, **kwargs):
"""Compute the value and the node partition of a minimum (s, t)-cut.
Use the max-flow min-cut theorem, i.e., the capacity of a minimum
capacity cut is equal to the flow value of a maximum flow.
Parameters
----------
flowG : NetworkX graph
Edges of the graph are expected to have an attribute called
'capacity'. If this attribute is not present, the edge is
considered to have infinite capacity.
_s : node
Source node for the flow.
_t : node
Sink node for the flow.
capacity : string
Edges of the graph G are expected to have an attribute capacity
that indicates how much flow the edge can support. If this
attribute is not present, the edge is considered to have
infinite capacity. Default value: 'capacity'.
flow_func : function
A function for computing the maximum flow among a pair of nodes
in a capacitated graph. The function has to accept at least three
parameters: a Graph or Digraph, a source node, and a target node.
And return a residual network that follows NetworkX conventions
(see Notes). If flow_func is None, the default maximum
flow function (:meth:`preflow_push`) is used. See below for
alternative algorithms. The choice of the default function may change
from version to version and should not be relied on. Default value:
None.
kwargs : Any other keyword parameter is passed to the function that
computes the maximum flow.
Returns
-------
cut_value : integer, float
Value of the minimum cut.
partition : pair of node sets
A partitioning of the nodes that defines a minimum cut.
Raises
------
NetworkXUnbounded
If the graph has a path of infinite capacity, all cuts have
infinite capacity and the function raises a NetworkXError.
See also
--------
:meth:`maximum_flow`
:meth:`maximum_flow_value`
:meth:`minimum_cut_value`
:meth:`edmonds_karp`
:meth:`preflow_push`
:meth:`shortest_augmenting_path`
Notes
-----
The function used in the flow_func parameter has to return a residual
network that follows NetworkX conventions:
The residual network :samp:`R` from an input graph :samp:`G` has the
same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
in :samp:`G`.
For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
in :samp:`G` or zero otherwise. If the capacity is infinite,
:samp:`R[u][v]['capacity']` will have a high arbitrary finite value
that does not affect the solution of the problem. This value is stored in
:samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
:samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
The flow value, defined as the total flow into :samp:`t`, the sink, is
stored in :samp:`R.graph['flow_value']`. Reachability to :samp:`t` using
only edges :samp:`(u, v)` such that
:samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
:samp:`s`-:samp:`t` cut.
Specific algorithms may store extra data in :samp:`R`.
The function should supports an optional boolean parameter value_only. When
True, it can optionally terminate the algorithm as soon as the maximum flow
value and the minimum cut can be determined.
Examples
--------
>>> G = nx.DiGraph()
>>> G.add_edge("x", "a", capacity=3.0)
>>> G.add_edge("x", "b", capacity=1.0)
>>> G.add_edge("a", "c", capacity=3.0)
>>> G.add_edge("b", "c", capacity=5.0)
>>> G.add_edge("b", "d", capacity=4.0)
>>> G.add_edge("d", "e", capacity=2.0)
>>> G.add_edge("c", "y", capacity=2.0)
>>> G.add_edge("e", "y", capacity=3.0)
minimum_cut computes both the value of the
minimum cut and the node partition:
>>> cut_value, partition = nx.minimum_cut(G, "x", "y")
>>> reachable, non_reachable = partition
'partition' here is a tuple with the two sets of nodes that define
the minimum cut. You can compute the cut set of edges that induce
the minimum cut as follows:
>>> cutset = set()
>>> for u, nbrs in ((n, G[n]) for n in reachable):
... cutset.update((u, v) for v in nbrs if v in non_reachable)
>>> print(sorted(cutset))
[('c', 'y'), ('x', 'b')]
>>> cut_value == sum(G.edges[u, v]["capacity"] for (u, v) in cutset)
True
You can also use alternative algorithms for computing the
minimum cut by using the flow_func parameter.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> cut_value == nx.minimum_cut(G, "x", "y", flow_func=shortest_augmenting_path)[0]
True
"""
if flow_func is None:
if kwargs:
raise nx.NetworkXError(
"You have to explicitly set a flow_func if"
" you need to pass parameters via kwargs."
)
flow_func = default_flow_func
if not callable(flow_func):
raise nx.NetworkXError("flow_func has to be callable.")
if kwargs.get("cutoff") is not None and flow_func is preflow_push:
raise nx.NetworkXError("cutoff should not be specified.")
R = flow_func(flowG, _s, _t, capacity=capacity, value_only=True, **kwargs)
# Remove saturated edges from the residual network
cutset = [(u, v, d) for u, v, d in R.edges(data=True) if d["flow"] == d["capacity"]]
R.remove_edges_from(cutset)
# Then, reachable and non reachable nodes from source in the
# residual network form the node partition that defines
# the minimum cut.
non_reachable = set(dict(nx.shortest_path_length(R, target=_t)))
partition = (set(flowG) - non_reachable, non_reachable)
# Finally add again cutset edges to the residual network to make
# sure that it is reusable.
if cutset is not None:
R.add_edges_from(cutset)
return (R.graph["flow_value"], partition)
@nx._dispatch(graphs="flowG", edge_attrs={"capacity": float("inf")})
def minimum_cut_value(flowG, _s, _t, capacity="capacity", flow_func=None, **kwargs):
"""Compute the value of a minimum (s, t)-cut.
Use the max-flow min-cut theorem, i.e., the capacity of a minimum
capacity cut is equal to the flow value of a maximum flow.
Parameters
----------
flowG : NetworkX graph
Edges of the graph are expected to have an attribute called
'capacity'. If this attribute is not present, the edge is
considered to have infinite capacity.
_s : node
Source node for the flow.
_t : node
Sink node for the flow.
capacity : string
Edges of the graph G are expected to have an attribute capacity
that indicates how much flow the edge can support. If this
attribute is not present, the edge is considered to have
infinite capacity. Default value: 'capacity'.
flow_func : function
A function for computing the maximum flow among a pair of nodes
in a capacitated graph. The function has to accept at least three
parameters: a Graph or Digraph, a source node, and a target node.
And return a residual network that follows NetworkX conventions
(see Notes). If flow_func is None, the default maximum
flow function (:meth:`preflow_push`) is used. See below for
alternative algorithms. The choice of the default function may change
from version to version and should not be relied on. Default value:
None.
kwargs : Any other keyword parameter is passed to the function that
computes the maximum flow.
Returns
-------
cut_value : integer, float
Value of the minimum cut.
Raises
------
NetworkXUnbounded
If the graph has a path of infinite capacity, all cuts have
infinite capacity and the function raises a NetworkXError.
See also
--------
:meth:`maximum_flow`
:meth:`maximum_flow_value`
:meth:`minimum_cut`
:meth:`edmonds_karp`
:meth:`preflow_push`
:meth:`shortest_augmenting_path`
Notes
-----
The function used in the flow_func parameter has to return a residual
network that follows NetworkX conventions:
The residual network :samp:`R` from an input graph :samp:`G` has the
same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
in :samp:`G`.
For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
in :samp:`G` or zero otherwise. If the capacity is infinite,
:samp:`R[u][v]['capacity']` will have a high arbitrary finite value
that does not affect the solution of the problem. This value is stored in
:samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
:samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
The flow value, defined as the total flow into :samp:`t`, the sink, is
stored in :samp:`R.graph['flow_value']`. Reachability to :samp:`t` using
only edges :samp:`(u, v)` such that
:samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
:samp:`s`-:samp:`t` cut.
Specific algorithms may store extra data in :samp:`R`.
The function should supports an optional boolean parameter value_only. When
True, it can optionally terminate the algorithm as soon as the maximum flow
value and the minimum cut can be determined.
Examples
--------
>>> G = nx.DiGraph()
>>> G.add_edge("x", "a", capacity=3.0)
>>> G.add_edge("x", "b", capacity=1.0)
>>> G.add_edge("a", "c", capacity=3.0)
>>> G.add_edge("b", "c", capacity=5.0)
>>> G.add_edge("b", "d", capacity=4.0)
>>> G.add_edge("d", "e", capacity=2.0)
>>> G.add_edge("c", "y", capacity=2.0)
>>> G.add_edge("e", "y", capacity=3.0)
minimum_cut_value computes only the value of the
minimum cut:
>>> cut_value = nx.minimum_cut_value(G, "x", "y")
>>> cut_value
3.0
You can also use alternative algorithms for computing the
minimum cut by using the flow_func parameter.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> cut_value == nx.minimum_cut_value(
... G, "x", "y", flow_func=shortest_augmenting_path
... )
True
"""
if flow_func is None:
if kwargs:
raise nx.NetworkXError(
"You have to explicitly set a flow_func if"
" you need to pass parameters via kwargs."
)
flow_func = default_flow_func
if not callable(flow_func):
raise nx.NetworkXError("flow_func has to be callable.")
if kwargs.get("cutoff") is not None and flow_func is preflow_push:
raise nx.NetworkXError("cutoff should not be specified.")
R = flow_func(flowG, _s, _t, capacity=capacity, value_only=True, **kwargs)
return R.graph["flow_value"]
|