
    wgi=                         d Z ddlmZ ddlmZ ddlZddlmZ ddlm	Z	m
Z
mZmZmZ d	gZd
 Z ej                   d ed      id      	 dd       Zy)zA
Highest-label preflow-push algorithm for maximum flow problems.
    )deque)isliceN   )arbitrary_element   )CurrentEdgeGlobalRelabelThresholdLevelbuild_residual_networkdetect_unboundednesspreflow_pushc                    | vr"t        j                  dt               d      | vr"t        j                  dt               d      k(  rt        j                  d      |d}|dk  rt        j                  d      |t        | |      n|t	               j
                  j                  j                  D ]'  }d|   d<   |   j                         D ]  }d|d<   	 ) fd       vrdj                  d	<   S t              t        fd
D              <   t        j                         |      D ]*  }|v r|   ndz   |   d<   t        |         |   d<   , fd   j                         D ]  \  }}	|	d   }
|
dkD  s ||
        t!        dz        D cg c]  }t#                c}D ][  }|k7  s	|k7  s|   d      }|   d   dkD  r|j$                  j'                  |       A|j(                  j'                  |       ] fdfdfd}fd}fd}}|dkD  r	 |   }|j$                  s|dz  }n|}|}t+        |j$                        } ||d      }j-                         r |d      }|j/                          n4|j$                  s|j(                  s ||       |dz
  }|nt        |      |dkD  r|r   d   j                  d	<   S  |d      }j/                          |kD  re	 |   }|j$                  s|dz  }nGt+        |j$                        } ||d      }j-                         r |d      }j/                          ^|kD  re   d   j                  d	<   S c c}w )z;Implementation of the highest-label preflow-push algorithm.znode z not in graphz!source and sink are the same noder   z(global_relabel_freq must be nonnegative.excessflowc                     | di}t        | dfg      }|r_|j                         \  }}|dz  }|   j                         D ].  \  }}||vs|d   |d   k  s|||<   |j                  ||f       0 |r_|S )zYPerform a reverse breadth-first search from src in the residual
        network.
        r   r   r   capacity)r   popleftitemsappend)srcheightsquheightvattrR_preds          i/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/networkx/algorithms/flow/preflowpush.pyreverse_bfsz&preflow_push_impl.<locals>.reverse_bfs5   s     (C8*		IAvaKF!!9??, *4G#VtJ7G(G!'GAJHHa[)*      
flow_valuec              3   4   K   | ]  }|k7  s	|     y w)N ).0r   r   ss     r   	<genexpr>z$preflow_push_impl.<locals>.<genexpr>P   s     ;AAFWQZ;s   

r   r   	curr_edgec                     |    |   dxx   |z  cc<   |   |    dxx   |z  cc<   |    dxx   |z  cc<   |   dxx   |z  cc<   y)z$Push flow units of flow from u to v.r   r   Nr#   )r   r   r   R_nodesR_succs      r   pushzpreflow_push_impl.<locals>.pushZ   s[    q	!V$q	!V$
8$
8$r    r      c                     | k7  rW| k7  rQ|    d      }| |j                   v r7|j                   j                  |        |j                  j                  |        yyyy)zAMove a node from the inactive set to the active set of its level.r   N)inactiveremoveactiveadd)r   levelr)   levelsr%   ts     r   activatez#preflow_push_impl.<locals>.activater   s_    6a1f71:h/0EENN"%%a(  # # 6r    c                     j                  t        |                 t        fd|    j                         D              dz   S )z,Relabel a node to create an admissible edge.c              3   J   K   | ]  \  }}|d    |d   k  r
|   d     yw)r   r   r   Nr#   )r$   r   r   r)   s      r   r&   z5preflow_push_impl.<locals>.relabel.<locals>.<genexpr>~   s7      At<$z"22 
8$s    #r   )add_worklenminr   )r   r)   r*   grts    r   relabelz"preflow_push_impl.<locals>.relabelz   sF    S^$ %ay0 
 	
r    c                 *   |    d   }|    d   }|}
|   j                   j                  |        	 |j                         \  }}||   d   dz   k(  rb|d   |d   k  rWt        |    d   |d   |d   z
        } | ||        	|       |    d   dk(  r
|   j                  j                  |        n	 |j                          ||    d<   |S # t        $ r7  |       }|r(|dz
  k\  r 
|   j                   j                  |        Y E|}Y Jw xY w)zDischarge a node until it becomes inactive or, during phase 1 (see
        below), its height reaches at least n. The node is known to have the
        largest height among active nodes.
        r   r'   r   r   r   r   r   )r0   r/   getr:   r.   r1   move_to_nextStopIteration)r   	is_phase1r   r'   next_heightr   r   r   r)   r5   r3   nr+   r<   s           r   	dischargez$preflow_push_impl.<locals>.discharge   sS   
 H%AJ{+	 v$$Q'mmoGAtH-11d6lT*EU6U71:h/j1ADL1PQQ4 1:h'1,6N++//2%&&( 6  &
8! ! % !1q5 6N))--a0
 %%s   7C 9DDDc                    t        | dz   dz         D ]  }|j                  D ]  }dz   |   d<    |j                  D ]  }dz   |   d<    dz      j                  j                  |j                         |j                  j	                          dz      j                  j                  |j                         |j                  j	                           y)zApply the gap heuristic.r   r   N)r   r0   r.   updateclear)r   r2   r   r)   r3   
max_heightrC   s      r   gap_heuristicz(preflow_push_impl.<locals>.gap_heuristic   s     FFQJ
Q? 	#E\\ -'(1u
8$-^^ -'(1u
8$-1q5M  ''5LL 1q5M""))%..9NN  "	#r    c                 N   | rn} |      }| s|= t        |j                               }| r!D ]  }||vs|   d   
k  s
dz   ||<    n|D ]  }||xx   
z  cc<    |
z  }||= |j                         D ]  \  }}|   d   }||k7  s|	|   j                  v r=	|   j                  j	                  |       	|   j                  j                  |       n<	|   j                  j	                  |       	|   j                  j                  |       ||   d<    |S )z&Apply the global relabeling heuristic.r   r   )maxvaluesr   r0   r/   r1   r.   )	from_sinkr   r   rH   r   
new_height
old_heightRr)   r3   rC   r   r%   r4   s          r   global_relabelz)preflow_push_impl.<locals>.global_relabel   sT   a!c"
)*
  'G#
8(<q(@!"QGAJ'
   
a
 !OJCL$]]_ 		2MAz H-JZ'z*111:&--44Q7:&--11!4:&//66q9:&//33A6'1
8$		2 r    TF)nxNetworkXErrorstrr   r   nodespredsuccrL   graphr9   rK   r	   sizer   r   ranger
   r0   r1   r.   r   
is_reached
clear_work) Gr%   r4   r   residualglobal_relabel_freq
value_onlyr   er   r   ir2   rD   rI   rQ   r   rO   	old_levelrP   r)   r   r*   r5   r;   r   r3   rH   rC   r+   r<   r   s     ``                @@@@@@@@@@@@@r   preflow_push_implrd      s+   zs1vhm<==zs1vhm<==AvBCC"QIJJ"1h/Aq!ggGVVFVVF   
8!!# 	AAfI	
  !nG !"AA ;;;JGAJ
 AFFH.A
BC  9-.'\wqzq1u
8"-fQi"8
;9% !9??$ 4J!8At  %QU|,!eg,F &6a1f71:h/0Eqz(#a'  #""1%&$

' 'R# F F
1*6NE<< !JI!%,,/Aq$'F~~ (-#
 %%i.@.@
 j)#a#
 !V4
;  1*F  '
8 4 E"FNN 1*6NE<< !!%,,/Aq%(F~~'.   1*  $AJx0AGGLHo -s   Or   infT)
edge_attrsreturns_graphc           	      p    t        | ||||||      }d|j                  d<   t        j                  |       |S )a  Find a maximum single-commodity flow using the highest-label
    preflow-push 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 a running time of $O(n^2 \sqrt{m})$ for $n$ nodes and
    $m$ edges.


    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.

    global_relabel_freq : integer, float
        Relative frequency of applying the global relabeling heuristic to speed
        up the algorithm. If it is None, the heuristic is disabled. Default
        value: 1.

    value_only : bool
        If False, compute a maximum flow; otherwise, compute a maximum preflow
        which is enough for computing the maximum flow value. Default value:
        False.

    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:`edmonds_karp`
    :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 node :samp:`u` in :samp:`R`,
    :samp:`R.nodes[u]['excess']` represents the difference between flow into
    :samp:`u` and flow out of :samp:`u`.

    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.

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

    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 = preflow_push(G, "x", "y")
    >>> flow_value = nx.maximum_flow_value(G, "x", "y")
    >>> flow_value == R.graph["flow_value"]
    True
    >>> # preflow_push also stores the maximum flow value
    >>> # in the excess attribute of the sink node t
    >>> flow_value == R.nodes["y"]["excess"]
    True
    >>> # For some problems, you might only want to compute a
    >>> # maximum preflow.
    >>> R = preflow_push(G, "x", "y", value_only=True)
    >>> flow_value == R.graph["flow_value"]
    True
    >>> flow_value == R.nodes["y"]["excess"]
    True

    r   	algorithm)rd   rX   rR   _clear_cache)r]   r%   r4   r   r^   r_   r`   rP   s           r   r   r   #  s;    F 	!Q8X7JJWA)AGGKOOAHr    )r   Nr   F)__doc__collectionsr   	itertoolsr   networkxrR   utilsr   r   r	   r
   r   r   __all__rd   _dispatchablefloatr   r#   r    r   <module>rs      se       &  
JZ j%,7tLSXE MEr    