
    wgab                         d Z dgZddlmZmZmZ ddlmZmZ ddl	Z
ddlmZ  G d d      Z ed	       e
j                  d
 ed      dd      dd              Zy)z<
Minimum cost flow algorithms on directed connected graphs.
network_simplex    )chainislicerepeat)ceilsqrtN)not_implemented_forc                   j    e Zd Z	 ddZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zy)_DataEssentialsAndFunctionsc                 b  
 t        |      | _        t        | j                        D ci c]  \  }}||
 c}}| _        | j                  D cg c]!  }|j                  |   j                  |d      # c}| _        g | _        g | _        |rg | _	        i | _
        g | _        g | _        |s|j                  d      }n|j                  dd      }t        d      

fd|D        }t        |      D ]  \  }}	| j                  j                  | j                  |	d             | j                  j                  | j                  |	d             |r| j                  j                  |	d          || j                  |	d d	 <   | j                  j                  |	d	   j                  
             | j                  j                  |	d	   j                  |d              d | _        d | _        d | _        d | _        d | _        d | _        d | _        d | _        d | _        d
| _        y c c}}w c c}w )Nr   Tdatar   keysinfc              3   l   K   | ]+  }|d    |d   k7  s|d   j                        d k7  s(| - yw)r      Nget).0ecapacityr   s     l/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/networkx/algorithms/flow/networksimplex.py	<genexpr>z7_DataEssentialsAndFunctions.__init__.<locals>.<genexpr>'   s6     TqQqTQqT\aeii#6NRS6STs   444r      r   F)list	node_list	enumeratenode_indicesnodesr   node_demandsedge_sourcesedge_targets	edge_keysedge_indicesedge_capacitiesedge_weightsedgesfloatappend
edge_count	edge_flownode_potentialsparentparent_edgesubtree_sizenext_node_dftprev_node_dftlast_descendent_dft_spanning_tree_initialized)selfG
multigraphdemandr   weightiur)   r   r   s       `     @r   __init__z$_DataEssentialsAndFunctions.__init__   s     a.7.GHdaQTH/3~~
*+AGGAJNN61%
 DN!GGG&EGGDG1EElTETe$ 	;DAq$$T%6%6qt%<=$$T%6%6qt%<=%%ad+()Daf%  ''"		(C(@A$$QrUYYvq%9:	; # !!#'  	'Q I
s   H&&H,c                    t        | j                        | _        t        t	        t        d| j                        d | j                  D                    | _        | j                  D cg c]  }|dk  r|n|  c}| _        t        t	        t        d|      d g            | _	        t        t        | j                  | j                  |z               | _        t        t	        t        d|      |dz   g            | _        t        t	        t        d|      ddg            | _        t        t        d|            | _        t        t	        t        |      |dz
  g            | _        d| _        y c c}w )Nr   c              3   2   K   | ]  }t        |        y wNabsr   ds     r   r   zG_DataEssentialsAndFunctions.initialize_spanning_tree.<locals>.<genexpr>C   s     .Q!s1v.Q   r   r   T)lenr&   r,   r   r   r   r"   r-   r.   r/   ranger0   r1   r2   r3   r4   r5   )r6   nfaux_infrD   s       r   initialize_spanning_treez4_DataEssentialsAndFunctions.initialize_spanning_tree@   s7   d//0&DOO,.Qt?P?P.QR
 8<7H7H 
23QHXI- 
 5A78$//4??Q#67
 !va|a!eW!=>!%1+Aw'
 "%A,/#'%(QUG$$
  +/' 
s   (E.c                 x   | j                   |   }| j                   |   }	 ||k  r$| j                  |   }| j                   |   }||k  r$||kD  r$| j                  |   }| j                   |   }||kD  r$||k(  rD||k7  r=| j                  |   }| j                   |   }| j                  |   }| j                   |   }n|S )zX
        Find the lowest common ancestor of nodes p and q in the spanning tree.
        )r1   r/   )r6   pqsize_psize_qs        r   	find_apexz%_DataEssentialsAndFunctions.find_apexV   s     ""1%""1%6/KKN**1- 6/ 6/KKN**1- 6/ 6AA!..q1FAA!..q1FH     c                     |g}g }||k7  rD|j                  | j                  |          | j                  |   }|j                  |       ||k7  rD||fS )zX
        Returns the nodes and edges on the path from node p to its ancestor w.
        )r+   r0   r/   )r6   rL   wWnWes        r   
trace_pathz&_DataEssentialsAndFunctions.trace_pathl   sZ     S1fIId&&q)*AAIIaL 1f 2vrQ   c                 
   | j                  ||      }| j                  ||      \  }}|j                          |j                          ||gk7  r|j                  |       | j                  ||      \  }}|d= ||z  }||z  }||fS )z
        Returns the nodes and edges on the cycle containing edge i == (p, q)
        when the latter is added to the spanning tree.

        The cycle is oriented in the direction from p to q.
        r   )rP   rV   reverser+   )	r6   r;   rL   rM   rS   rT   rU   WnRWeRs	            r   
find_cyclez&_DataEssentialsAndFunctions.find_cyclex   s     NN1a A&B





!9IIaL??1a(SG
c	
c	2vrQ   c                     t        ||      D ]F  \  }}| j                  |   |k(  r| j                  |xx   |z  cc<   0| j                  |xx   |z  cc<   H y)zQ
        Augment f units of flow along a cycle represented by Wn and We.
        N)zipr#   r-   )r6   rT   rU   fr;   rL   s         r   augment_flowz(_DataEssentialsAndFunctions.augment_flow   sX     BK 	'DAq  #q(q!Q&!q!Q&!		'rQ   c              #   p   K   | | j                   |   }||k7  r| j                  |   }| ||k7  ryyw)zD
        Yield the nodes in the subtree rooted at a node p.
        N)r4   r2   )r6   rL   ls      r   trace_subtreez)_DataEssentialsAndFunctions.trace_subtree   sB      $$Q'1f""1%AG 1fs   166c                    | j                   |   }| j                  |   }| j                  |   }| j                  |   }d| j                  |<   d| j
                  |<   || j                  |<   || j                  |<   || j                  |<   || j                  |<   |K| j                   |xx   |z  cc<   | j                  |   |k(  r|| j                  |<   | j                  |   }|Jyy)zT
        Remove an edge (s, t) where parent[t] == s from the spanning tree.
        N)r1   r3   r4   r2   r/   r0   )r6   stsize_tprev_tlast_tnext_last_ts          r   remove_edgez'_DataEssentialsAndFunctions.remove_edge   s     ""1%##A&))!,((0A"%06"*0;'%&6" &1 ma F* ''*f4.4((+AA	 mrQ   c                 r   g }|#|j                  |       | j                  |   }|#|j                          t        |t	        |dd            D ]e  \  }}| j
                  |   }| j                  |   }| j                  |   }| j                  |   }| j                  |   }|| j                  |<   d| j                  |<   | j                  |   | j                  |<   d| j                  |<   || j
                  |   z
  | j
                  |<   || j
                  |<   || j                  |<   || j                  |<   || j                  |<   || j                  |<   ||k(  r|| j                  |<   |}|| j                  |<   || j                  |<   || j                  |<   || j                  |<   || j                  |<   h y)zC
        Make a node q the root of its containing subtree.
        Nr   )
r+   r/   rX   r]   r   r1   r4   r3   r2   r0   )	r6   rM   	ancestorsrL   rN   last_pprev_qlast_qnext_last_qs	            r   	make_rootz%_DataEssentialsAndFunctions.make_root   s    	mQAA m 		6)Q#=> 	1DAq&&q)F--a0F''*F--a0F,,V4KDKKN!DKKN"&"2"21"5DQ"&DQ#)D,=,=a,@#@Da #)Da )4Dv&.4D{+)*Dv&$*Dq!.4((+ %+Dq!)*Dv&)*Dv&$*Dq!*0D$$Q'7	1rQ   c                    | j                   |   }| j                  |   }| j                  |   }| j                   |   }|| j                  |<   || j                  |<   || j                  |<   || j
                  |<   || j
                  |<   || j                  |<   |K| j                  |xx   |z  cc<   | j                   |   |k(  r|| j                   |<   | j                  |   }|Jyy)z[
        Add an edge (p, q) to the spanning tree where q is the root of a subtree.
        N)r4   r2   r1   r/   r0   r3   )r6   r;   rL   rM   rm   next_last_prO   ro   s           r   add_edgez$_DataEssentialsAndFunctions.add_edge   s     ))!,((0""1%))!,A%&6" &1*0;'%06" ma F* ''*f4.4((+AA	 mrQ   c                 @   || j                   |   k(  r0| j                  |   | j                  |   z
  | j                  |   z
  }n/| j                  |   | j                  |   z   | j                  |   z
  }| j                  |      D ]  }| j                  |xx   |z  cc<    y)z
        Update the potentials of the nodes in the subtree rooted at a node
        q connected to its parent p by an edge i.
        N)r$   r.   r(   rb   )r6   r;   rL   rM   rD   s        r   update_potentialsz-_DataEssentialsAndFunctions.update_potentials   s    
 !!!$$$$Q'$*;*;A*>>AUAUVWAXXA$$Q'$*;*;A*>>AUAUVWAXXA##A& 	)A  #q(#	)rQ   c                     | j                   |   | j                  | j                  |      z
  | j                  | j                  |      z   }| j                  |   dk(  r|S | S )z&Returns the reduced cost of an edge i.r   )r(   r.   r#   r$   r-   )r6   r;   cs      r   reduced_costz(_DataEssentialsAndFunctions.reduced_cost  sr     a ""4#4#4Q#789""4#4#4Q#789 	

 NN1%*q22rQ   c              #     K   | j                   dk(  ryt        t        t        | j                                     }| j                   |z   dz
  |z  }d}d}||k  r||z   }|| j                   k  rt	        ||      }n8|| j                   z  }t        t	        || j                         t	        |            }|}t        || j                        }| j                  |      }|dk\  r|dz  }nX| j                  |   dk(  r| j                  |   }	| j                  |   }
n| j                  |   }	| j                  |   }
||	|
f d}||k  ryyw)z-Yield entering edges until none can be found.r   Nr   key)r,   intr   r   rG   r   minry   r-   r#   r$   )r6   BMmr^   ra   r)   r;   rx   rL   rM   s              r   find_entering_edgesz/_DataEssentialsAndFunctions.find_entering_edges
  sD    ??a T$//*+,__q 1$*!eAADOO#aT__$eAt7qBAEt001A!!!$AAvQ >>!$)))!,A))!,A))!,A))!,AAg1 !es   EEEc                     | j                   |   |k(  r| j                  |   | j                  |   z
  S | j                  |   S )zfReturns the residual capacity of an edge i in the direction away
        from its endpoint p.
        )r#   r'   r-   )r6   r;   rL   s      r   residual_capacityz-_DataEssentialsAndFunctions.residual_capacity4  sM       #q(   #dnnQ&77	
 "	
rQ   c                      t        t        t        |      t        |             fd      \  }} j                  |   |k(  r j                  |   n j                  |   }|||fS )z=Returns the leaving edge in a cycle represented by Wn and We.c                 "     j                   |  S r@   )r   )i_pr6   s    r   <lambda>z?_DataEssentialsAndFunctions.find_leaving_edge.<locals>.<lambda>B  s    2D22C8 rQ   r{   )r~   r]   reversedr#   r$   )r6   rT   rU   jrd   re   s   `     r   find_leaving_edgez-_DataEssentialsAndFunctions.find_leaving_edge>  sc    hrl+8
1 %)$5$5a$8A$=Da 4CTCTUVCW!QwrQ   Nr9   r   r:   )__name__
__module____qualname__r=   rJ   rP   rV   r[   r_   rb   rj   rq   rt   rv   ry   r   r   r    rQ   r   r   r      sS    JR/
b/,,
&'0$1L0
)3&T
rQ   r   
undirectedr9   r   )r   r:   )
node_attrs
edge_attrsc           
         t        |       dk(  rt        j                  d      | j                         }t	        | ||      t        d      t        j                  j                        D ],  \  }}t        |      k(  st        j                  d|d       t        j                  j                        D ],  \  }}t        |      k(  st        j                  d|d       |st        j                  | d	
      }	nt        j                  | d	d	      }	|	D ]?  }t        |d   j                  d            k(  s%t        j                  d|dd d       t        j                        dk7  rt        j                  d      t        j                  j                         D ]#  \  }}
|
dk  st        j                  d|d       |st        j                  | d	
      }	nt        j                  | d	d	      }	|	D ]6  }|d   j                        dk  st        j                  d|dd d       t#        j                        D ]w  \  }}|dkD  r7j$                  j'                  d       j(                  j'                  |       Bj$                  j'                  |       j(                  j'                  d       y dt+        t-        t        fdj                   D              t        d j                  D              gd j                  D                    z  xs dt        j                        }j                  j/                  t1        |             j                   j/                  t1        |             j3                  |       j5                         D ]  \  }}}j7                  |||      \  }}j9                  ||      \  }}}j;                  ||j=                  ||             ||k7  s\j>                  |   |k7  r||}}|jA                  |      |jA                  |      kD  r||}}jC                  ||       jE                  |       jG                  |||       jI                  |||        tK        fdtM        | d      D              rt        j                  d      tK        fdtM        jN                        D              s+tK        fdt        j                  | d	
      D              rt        jP                  d      jR                  jN                  d= t        d t        j                  jR                        D              }j                  D ci c]  }|i  c}fd}fdj$                  D        _        fdj(                  D        _        |sKt        j$                  j(                  jR                        D ]
  } ||        | jU                  d	
      }	nVt        j$                  j(                  jV                  jR                        D ]
  } ||        | jU                  d	d	      }	|	D ]}  }|d   |d   k7  r(|d   j                        dk(  s' ||dd dz          6|d   j                  d      }|dk\  r ||dd dz          _|d      }
|||
z  z  } ||dd |
fz           |fS c c}w )ad  Find a minimum cost flow satisfying all demands in digraph G.

    This is a primal network simplex algorithm that uses the leaving
    arc rule to prevent cycling.

    G is a digraph with edge costs and capacities and in which nodes
    have demand, i.e., they want to send or receive some amount of
    flow. A negative demand means that the node wants to send flow, a
    positive demand means that the node want to receive flow. A flow on
    the digraph G satisfies all demand if the net flow into each node
    is equal to the demand of that node.

    Parameters
    ----------
    G : NetworkX graph
        DiGraph on which a minimum cost flow satisfying all demands is
        to be found.

    demand : string
        Nodes of the graph G are expected to have an attribute demand
        that indicates how much flow a node wants to send (negative
        demand) or receive (positive demand). Note that the sum of the
        demands should be 0 otherwise the problem in not feasible. If
        this attribute is not present, a node is considered to have 0
        demand. Default value: 'demand'.

    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'.

    weight : string
        Edges of the graph G are expected to have an attribute weight
        that indicates the cost incurred by sending one unit of flow on
        that edge. If not present, the weight is considered to be 0.
        Default value: 'weight'.

    Returns
    -------
    flowCost : integer, float
        Cost of a minimum cost flow satisfying all demands.

    flowDict : dictionary
        Dictionary of dictionaries keyed by nodes such that
        flowDict[u][v] is the flow edge (u, v).

    Raises
    ------
    NetworkXError
        This exception is raised if the input graph is not directed or
        not connected.

    NetworkXUnfeasible
        This exception is raised in the following situations:

            * The sum of the demands is not zero. Then, there is no
              flow satisfying all demands.
            * There is no flow satisfying all demand.

    NetworkXUnbounded
        This exception is raised if the digraph G has a cycle of
        negative cost and infinite capacity. Then, the cost of a flow
        satisfying all demands is unbounded below.

    Notes
    -----
    This algorithm is not guaranteed to work if edge weights or demands
    are floating point numbers (overflows and roundoff errors can
    cause problems). As a workaround you can use integer numbers by
    multiplying the relevant edge attributes by a convenient
    constant factor (eg 100).

    See also
    --------
    cost_of_flow, max_flow_min_cost, min_cost_flow, min_cost_flow_cost

    Examples
    --------
    A simple example of a min cost flow problem.

    >>> G = nx.DiGraph()
    >>> G.add_node("a", demand=-5)
    >>> G.add_node("d", demand=5)
    >>> G.add_edge("a", "b", weight=3, capacity=4)
    >>> G.add_edge("a", "c", weight=6, capacity=10)
    >>> G.add_edge("b", "d", weight=1, capacity=9)
    >>> G.add_edge("c", "d", weight=2, capacity=5)
    >>> flowCost, flowDict = nx.network_simplex(G)
    >>> flowCost
    24
    >>> flowDict
    {'a': {'b': 4, 'c': 1}, 'd': {}, 'b': {'d': 4}, 'c': {'d': 1}}

    The mincost flow algorithm can also be used to solve shortest path
    problems. To find the shortest path between two nodes u and v,
    give all edges an infinite capacity, give node u a demand of -1 and
    node v a demand a 1. Then run the network simplex. The value of a
    min cost flow will be the distance between u and v and edges
    carrying positive flow will indicate the path.

    >>> G = nx.DiGraph()
    >>> G.add_weighted_edges_from(
    ...     [
    ...         ("s", "u", 10),
    ...         ("s", "x", 5),
    ...         ("u", "v", 1),
    ...         ("u", "x", 2),
    ...         ("v", "y", 1),
    ...         ("x", "u", 3),
    ...         ("x", "v", 5),
    ...         ("x", "y", 2),
    ...         ("y", "s", 7),
    ...         ("y", "v", 6),
    ...     ]
    ... )
    >>> G.add_node("s", demand=-1)
    >>> G.add_node("v", demand=1)
    >>> flowCost, flowDict = nx.network_simplex(G)
    >>> flowCost == nx.shortest_path_length(G, "s", "v", weight="weight")
    True
    >>> sorted([(u, v) for u in flowDict for v in flowDict[u] if flowDict[u][v] > 0])
    [('s', 'x'), ('u', 'v'), ('x', 'u')]
    >>> nx.shortest_path(G, "s", "v", weight="weight")
    ['s', 'x', 'u', 'v']

    It is possible to change the name of the attributes used for the
    algorithm.

    >>> G = nx.DiGraph()
    >>> G.add_node("p", spam=-4)
    >>> G.add_node("q", spam=2)
    >>> G.add_node("a", spam=-2)
    >>> G.add_node("d", spam=-1)
    >>> G.add_node("t", spam=2)
    >>> G.add_node("w", spam=3)
    >>> G.add_edge("p", "q", cost=7, vacancies=5)
    >>> G.add_edge("p", "a", cost=1, vacancies=4)
    >>> G.add_edge("q", "d", cost=2, vacancies=3)
    >>> G.add_edge("t", "q", cost=1, vacancies=2)
    >>> G.add_edge("a", "t", cost=2, vacancies=4)
    >>> G.add_edge("d", "w", cost=3, vacancies=4)
    >>> G.add_edge("t", "w", cost=4, vacancies=1)
    >>> flowCost, flowDict = nx.network_simplex(
    ...     G, demand="spam", capacity="vacancies", weight="cost"
    ... )
    >>> flowCost
    37
    >>> flowDict
    {'p': {'q': 2, 'a': 2}, 'q': {'d': 1}, 'a': {'t': 4}, 'd': {'w': 2}, 't': {'q': 1, 'w': 1}, 'w': {}}

    References
    ----------
    .. [1] Z. Kiraly, P. Kovacs.
           Efficient implementation of minimum-cost flow algorithms.
           Acta Universitatis Sapientiae, Informatica 4(1):67--118. 2012.
    .. [2] R. Barr, F. Glover, D. Klingman.
           Enhancement of spanning tree labeling procedures for network
           optimization.
           INFOR 17(1):16--34. 1979.
    r   zgraph has no nodesr   r   znode z has infinite demandzedge z has infinite weightTr   r   r   Nztotal node demand is not zeroz has negative capacity   c              3   .   K   | ]  }|k  s	|  y wr@   r   )r   rx   r   s     r   r   z"network_simplex.<locals>.<genexpr>7  s     Ca1s7Cs   
c              3   2   K   | ]  }t        |        y wr@   rA   )r   rS   s     r   r   z"network_simplex.<locals>.<genexpr>8  s     :1A:rE   c              3   2   K   | ]  }t        |        y wr@   rA   rC   s     r   r   z"network_simplex.<locals>.<genexpr>:  s     3AQ3rE   r   c              3   B   K   | ]  }j                   |   d k7    yw)r   Nr-   )r   r;   DEAFs     r   r   z"network_simplex.<locals>.<genexpr>`  s     
8a4>>!!
8s   z"no flow satisfies all node demandsc              3   H   K   | ]  }j                   |   d z  k\    yw)r   Nr   )r   r;   r   rI   s     r   r   z"network_simplex.<locals>.<genexpr>c  s$     
M4>>!q H,
Ms   "c              3      K   | ]6  }|d    j                        k(  xr |d    j                  d      dk   8 yw)r   r   Nr   )r   r   r   r   r:   s     r   r   z"network_simplex.<locals>.<genexpr>c  sK      U 	
"		(C C'DAbEIIfa,@1,DDUs   <?z+negative cycle with infinite capacity foundc              3   ,   K   | ]  \  }}||z    y wr@   r   )r   rS   xs      r   r   z"network_simplex.<locals>.<genexpr>n  s     MdaAEMs   c                 |    | d      }| dd D ]  }	 ||   }
 | d   || d   <   y# t         $ r i }|||<   |}Y +w xY w)zAdd a flow dict entry.r   r   r   N)KeyError)r   rD   kre   	flow_dicts       r   	add_entryz"network_simplex.<locals>.add_entryq  sj    adO1R 	AaD	 R5!B%	  !s   &;;c              3   <   K   | ]  }j                   |     y wr@   r   )r   rd   r   s     r   r   z"network_simplex.<locals>.<genexpr>}        q   c              3   <   K   | ]  }j                   |     y wr@   r   )r   re   r   s     r   r   z"network_simplex.<locals>.<genexpr>  r   r   )r   ),rF   nxNetworkXErroris_multigraphr   r*   r]   r   r"   rB   r&   r(   selfloop_edgesr   sumNetworkXUnfeasibler'   r   r#   r+   r$   maxr   extendr   rJ   r   r[   r   r_   r   r/   indexrj   rq   rt   rv   anyrG   r,   NetworkXUnboundedr-   r)   r%   )r7   r9   r   r:   r8   r<   rD   r   rS   r)   rx   r;   rH   rL   rM   rT   rU   r   rd   re   	flow_costr   r   rI   r   r   s     ``                  @@@@r   r   r   H  s   T 1v{344"J '	:fxD ,CDNND$5$56 F1q6S=""U1%/C#DEEF D%%t'8'89 F1q6S=""U1%/C#DEEF !!!$/!!!$T: Kquyy#$+""U1Sb6*4H#IJJK 4"##$CDDD%%t';';< M1q5''%u4J(KLLM !!!$/!!!$T: RR599Xs#a'''%#2z9O(PQQR $++, )1 q5$$R($$Q'$$Q'$$R() 	

C4#7#7CC:(9(9:: 4!2!23
		
 
	   	DNNAVHa01x 34 	!!!X. ++- ,1aAq)B((R01a"b$"8"8A">?6{{1~"!1xx{RXXa[(!1Q"NN1MM!Q"""1a+,* 
85!Q<
88##$HII

MeDOO6L
MMQT U""140U R ""#PQQ 	t()Mc$*;*;T^^&LMMI $/1B/I
#'#4#4D#'#4#4D T&&(9(94>>J 	AaL	T"t00$..$..
 	A aL	 T- )Q41Q4<uyy3'1,!CR&4-("		&!$AAv!CR&4-(bE(OQU"	!CR&A4-() iW 0s   
\r   )__doc____all__	itertoolsr   r   r   mathr   r   networkxr   networkx.utilsr	   r   _dispatchabler*   r   r   rQ   r   <module>r      sn    
 + +   .w wt	 \"u$KN  #N rQ   