
    h4                         S r SSKJr  SSKJr  SSKrSSKJr  S/r	\R                  " S\" S5      0S	S
9 SS j5       rS rg)z8
Boykov-Kolmogorov algorithm for maximum flow problems.
    )deque)
itemgetterN)build_residual_networkboykov_kolmogorovcapacityinfT)
edge_attrsreturns_graphc                 j    [        XX#XF5      nSUR                  S'   [        R                  " U5        U$ )a  Find a maximum single-commodity flow using Boykov-Kolmogorov algorithm.

This function returns the residual network resulting after computing
the maximum flow. See below for details about the conventions
NetworkX uses for defining residual networks.

This algorithm has worse case complexity $O(n^2 m |C|)$ for $n$ nodes, $m$
edges, and $|C|$ the cost of the minimum cut [1]_. This implementation
uses the marking heuristic defined in [2]_ which improves its running
time in many practical problems.

Parameters
----------
G : 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'.

residual : NetworkX graph
    Residual network on which the algorithm is to be executed. If None, a
    new residual network is created. Default value: None.

value_only : bool
    If True compute only the value of the maximum flow. This parameter
    will be ignored by this algorithm because it is not applicable.

cutoff : integer, float
    If specified, the algorithm will terminate when the flow value reaches
    or exceeds the cutoff. In this case, it may be unable to immediately
    determine a minimum cut. Default value: None.

Returns
-------
R : NetworkX DiGraph
    Residual network after computing the maximum flow.

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:`preflow_push`
:meth:`shortest_augmenting_path`

Notes
-----
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']`. If :samp:`cutoff` is not
specified, 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.

Examples
--------
>>> from networkx.algorithms.flow import boykov_kolmogorov

The functions that implement flow algorithms and output a residual
network, such as this one, are not imported to the base NetworkX
namespace, so you have to explicitly import them from the flow package.

>>> 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)
>>> R = boykov_kolmogorov(G, "x", "y")
>>> flow_value = nx.maximum_flow_value(G, "x", "y")
>>> flow_value
3.0
>>> flow_value == R.graph["flow_value"]
True

A nice feature of the Boykov-Kolmogorov algorithm is that a partition
of the nodes that defines a minimum cut can be easily computed based
on the search trees used during the algorithm. These trees are stored
in the graph attribute `trees` of the residual network.

>>> source_tree, target_tree = R.graph["trees"]
>>> partition = (set(source_tree), set(G) - set(source_tree))

Or equivalently:

>>> partition = (set(G) - set(target_tree), set(target_tree))

References
----------
.. [1] Boykov, Y., & Kolmogorov, V. (2004). An experimental comparison
       of min-cut/max-flow algorithms for energy minimization in vision.
       Pattern Analysis and Machine Intelligence, IEEE Transactions on,
       26(9), 1124-1137.
       https://doi.org/10.1109/TPAMI.2004.60

.. [2] Vladimir Kolmogorov. Graph-based Algorithms for Multi-camera
       Reconstruction Problem. PhD thesis, Cornell University, CS Department,
       2003. pp. 109-114.
       https://web.archive.org/web/20170809091249/https://pub.ist.ac.at/~vnk/papers/thesis.pdf

r   	algorithm)boykov_kolmogorov_implgraphnx_clear_cache)Gstr   residual
value_onlycutoffRs           [/var/www/html/env/lib/python3.13/site-packages/networkx/algorithms/flow/boykovkolmogorov.pyr   r      s2    ` 	qQ(CA.AGGKOOAH    c           
      t  ^^^^^^^^^^^^^^ TU ;  a#  [         R                  " S[        T5       S35      eTU ;  a#  [         R                  " S[        T5       S35      eTT:X  a  [         R                  " S5      eUc  [        X5      nOUnU H!  nXg   R	                  5        H  nSUS'   M
     M#     UR
                  S   mUc  TnUR                  mUR                  mUUUUUUUU4S jn	UUUUUUUUU4	S jn
UUUUUUUUUU4
S	 jnUUUUU4S
 jmUU4S jmTS 0mTS 0m[        TT/5      m[        5       mSnSmTTTT0mTSTS0mX:  a*  U	" 5       u  p}Uc  OTS-  mX" X}5      -  nU" 5         X:  a  M*  US-  T:  a  [         R                  " S5      eTT4UR
                  S'   XR
                  S'   U$ )Nznode z not in graphz!source and sink are the same noder   flowr   c                    > T
(       a  T
S   n U T;   a  TnTnTnOTnTnTnX0   R                  5        H  u  pEUS   US   -
  S:  d  M  XA;  a>  XB;   a  UTL a  X4s  $ X@4s  $ XU'   TU    S-   TU'   TU    TU'   T
R                  U5        MY  XA;   d  M`  T	" X5      (       d  Mo  XU'   TU    S-   TU'   TU    TU'   M     T
R                  5       nT
(       a  M  g)a-  Bidirectional breadth-first search for the growth stage.

Returns a connecting edge, that is and edge that connects
a node from the source search tree with a node from the
target search tree.
The first node in the connecting edge is always from the
source tree and the last node from the target tree.
r   r   r      )NN)itemsappendpopleft)u	this_tree
other_tree	neighborsvattr_R_predR_succ
_is_closeractivedistsource_treetarget_tree	timestamps          r   grow$boykov_kolmogorov_impl.<locals>.grow   s    q	AK'	(
"	'	(
"	$<--/
#d6l2Q6)?-6+-EA6QA6Q'(!"&q'A+Q'0|	!a(Jq,<,<'(!"&q'A+Q'0|	! 0  A/ f0 r   c                   >	 TU    U   n[        T	US   US   -
  5      nU /nU nUT:w  a<  UnTU   nT
U   U   n[        X2S   US   -
  5      nUR                  U5        UT:w  a  M<  UR                  5         UR                  U5        UnUT:w  a<  UnTU   nTU   U   n[        X2S   US   -
  5      nUR                  U5        UT:w  a  M<  [        U5      n[	        U5      n / nU H{  nTU    U   S==   U-  ss'   TU   U    S==   U-  ss'   TU    U   S   TU    U   S   :X  a8  UT;   a  STU'   UR                  U5        U T;   a  STU '   UR                  U 5        Un M}     TR                  [        UTR                  S95        U$ )a  Augmentation stage.

Reconstruct path and determine its residual capacity.
We start from a connecting edge, which links a node
from the source tree to a node from the target tree.
The connecting edge is the output of the grow function
and the input of this function.
r   r   Nkey)minr   reverseiternextextendsortedget)r!   r%   r&   r   pathwnitthese_orphansINFr(   r)   r,   orphansr   r-   r   r.   s            r   augment'boykov_kolmogorov_impl.<locals>.augment   s    ay|3Z(4<78s1fAAA!9Q<Dt*-V<=DKKN 1f 	A1fAAA!9Q<Dt*-V<=DKKN 1f $ZHA1IaL D( 1IaL D( ay|F#vay|J'??#%)KN!((+#%)KN!((+A  	vm:;r   c                    >
^ T(       Ga5  TR                  5       n U T;   a  TmTnOTmTnUU4S jX   R                  5        5       n[        U[        S5      S9 H<  u  p4nUS   US   -
  S:  d  M  T	" UT5      (       d  M'  UTU '   TU   S-   TU '   TTU '     O   UU4S jX   R                  5        5       n[        U[        S5      S9 HM  u  p4nUS   US   -
  S:  a  UT
;  a  T
R	                  U5        TU   U :X  d  M7  S	TU'   TR                  U5        MO     U T
;   a  T
R                  U 5        TU 	 T(       a  GM4  g	g	)
aR  Adoption stage.

Reconstruct search trees by adopting or discarding orphans.
During augmentation stage some edges got saturated and thus
the source and target search trees broke down to forests, with
orphans as roots of some of its trees. We have to reconstruct
the search trees rooted to source and target before we can grow
them again.
c              3   F   >#    U  H  u  pUT;   d  M  XTU   4v   M     g 7fN .0r>   r&   r,   trees      r   	<genexpr>8boykov_kolmogorov_impl.<locals>.adopt.<locals>.<genexpr>'  s(     X6J71aSWi&Qd1g&6J   !!   r3   r   r   r   r   c              3   F   >#    U  H  u  pUT;   d  M  XTU   4v   M     g 7frG   rH   rI   s      r   rL   rM   0  s*      6J71aSWi&Qd1g&6JrN   N)r    r   r:   r   r   
appendleftremove)r!   r$   nbrsr%   r&   drK   r(   r)   _has_valid_rootr+   r,   rB   r-   r.   timer/   s         @r   adopt%boykov_kolmogorov_impl.<locals>.adopt  sK    !AK""	""	Xil6H6H6JXD$Tz!}=

#d6l2Q6&q$//"#Q"&q'A+Q'+	! >6?l6H6H6J #):a="AJAQJ'$v,6:F?"MM!,Aw!|"&Q**1- #B ;MM!$G; gr   c                    > / nU nUb4  UR                  U5        UT	T
4;   a  SnOTU   T:X  a  TU   nO
X   nUb  M4  g[        U5      n[        US5       H  u  pgXE-   U-
  TU'   TTU'   M     g)Nr   Fr   T)r   len	enumerate)r>   rK   r<   r%   	base_distlengthir!   r,   r   r   rV   r/   s           r   rU   /boykov_kolmogorov_impl.<locals>._has_valid_root>  s    mKKNQF{	1% G	A m TdA&DA(1,DGIaL ' r   c                 D   > TU   TU    :*  =(       a    TU   TU    S-   :  $ )Nr   rH   )r!   r%   r,   r/   s     r   r*   *boykov_kolmogorov_impl.<locals>._is_closerR  s,    |y|+EQ$q'A+0EEr   r   rO   z-Infinite capacity path, flow unbounded above.trees
flow_value)
r   NetworkXErrorstrr   valuesr   succpredr   NetworkXUnbounded)r   r   r   r   r   r   r   r!   er0   rC   rW   rc   r%   rA   r(   r)   rU   r*   r+   r,   rB   r-   r.   rV   r/   s    ``           @@@@@@@@@@@@r   r   r      s   zs1vhm<==zs1vhm<==AvBCC"1/
 AAfI   ''%.C~VVFVVF! !F. .`' 'R (F d)Kd)KAq6]FgGJDD!T"Iq!Q<D

v9	gam#
 
 A~""#RSS
 $[1AGGG&GGLHr   )r   NFN)__doc__collectionsr   operatorr   networkxr   networkx.algorithms.flow.utilsr   __all___dispatchablefloatr   r   rH   r   r   <module>rs      sW       A
 j%,7tLJNR MRjNr   