
    hab                         S r S/rSSKJrJrJr  SSKJrJr  SSK	r
SSKJr   " S S5      r\" S	5      \
R                  " S
\" S5      SS.S9SS j5       5       rg)z<
Minimum cost flow algorithms on directed connected graphs.
network_simplex    )chainislicerepeat)ceilsqrtN)not_implemented_forc                   t    \ rS rSr SS jrS rS rS rS rS r	S r
S	 rS
 rS rS rS rS rS rS rSrg)_DataEssentialsAndFunctions   c                 |  ^^
 [        U5      U l        [        U R                  5       VVs0 s H  u  pgXv_M	     snnU l        U R                   Vs/ s H!  oqR                  U   R                  US5      PM#     snU l        / U l        / U l        U(       a  / U l	        0 U l
        / U l        / U l        U(       d  UR                  SS9nOUR                  SSS9n[        S5      m
UU
4S jU 5       n[        U5       H  u  piU R                  R                  U R                  U	S      5        U R                  R                  U R                  U	S      5        U(       a  U R                  R                  U	S   5        X`R                  U	S S	 '   U R                  R                  U	S	   R                  TT
5      5        U R                  R                  U	S	   R                  US5      5        M     S U l        S U l        S U l        S U l        S U l        S U l        S U l        S U l        S U l        S
U l        g s  snnf s  snf )Nr   Tdatar   keysinfc              3   x   >#    U  H/  oS    US   :w  d  M  US   R                  TT5      S :w  d  M+  Uv   M1     g7f)r      Nget).0ecapacityr   s     Y/var/www/html/env/lib/python3.13/site-packages/networkx/algorithms/flow/networksimplex.py	<genexpr>7_DataEssentialsAndFunctions.__init__.<locals>.<genexpr>'   s8     TEqqTQqT\aeii#6NRS6SEs   ::	: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__$_DataEssentialsAndFunctions.__init__   s    a.7.GH.GdaQT.GH/3~~
/=!GGAJNN61%~
 DN!GGG&EGGDG1EElTETe$DA$$T%6%6qt%<=$$T%6%6qt%<=%%ad+()af%  ''"		(C(@A$$QrUYYvq%9: % # !!#'  	'Q I
s   H3(H9c                    [        U R                  5      U l        [        [	        [        SU R                  5      S U R                   5       5      5      U l        U R                   Vs/ s H  o3S::  a  UOU* PM     snU l        [        [	        [        SU5      S /5      5      U l	        [        [        U R                  U R                  U-   5      5      U l        [        [	        [        SU5      US-   /5      5      U l        [        [	        [        SU5      SS/5      5      U l        [        [        SU5      5      U l        [        [	        [        U5      US-
  /5      5      U l        SU l        g s  snf )Nr   c              3   8   #    U  H  n[        U5      v   M     g 7fNabsr   ds     r   r   G_DataEssentialsAndFunctions.initialize_spanning_tree.<locals>.<genexpr>C   s     .Q?P!s1vv?P   r   r   T)lenr(   r.   r   r   r   r$   r/   r0   r1   ranger2   r3   r4   r5   r6   r7   )r8   nfaux_infrG   s       r   initialize_spanning_tree4_DataEssentialsAndFunctions.initialize_spanning_tree@   s:   d//0&DOO,.Qt?P?P.QR
 8<7H7H 
7H!QHXI-7H 
 5A78$//4??Q#67
 !va|a!eW!=>!%1+Aw'
 "%A,/#'%(QUG$$
  +/' 
s   (E1c                 ~   U R                   U   nU R                   U   n X4:  a%  U R                  U   nU R                   U   nX4:  a  M%  X4:  a%  U R                  U   nU R                   U   nX4:  a  M%  X4:X  aD  X:w  a=  U R                  U   nU R                   U   nU R                  U   nU R                   U   nOU$ M  )zH
Find the lowest common ancestor of nodes p and q in the spanning tree.
)r3   r1   )r8   pqsize_psize_qs        r   	find_apex%_DataEssentialsAndFunctions.find_apexV   s     ""1%""1%/KKN**1- / /KKN**1- / 6AA!..q1FAA!..q1FH     c                     U/n/ nX:w  aE  UR                  U R                  U   5        U R                  U   nUR                  U5        X:w  a  ME  X44$ )zH
Returns the nodes and edges on the path from node p to its ancestor w.
)r-   r2   r1   )r8   rQ   wWnWes        r   
trace_path&_DataEssentialsAndFunctions.trace_pathl   sT     SfIId&&q)*AAIIaL f vrW   c                     U R                  X#5      nU R                  X$5      u  pVUR                  5         UR                  5         Xa/:w  a  UR                  U5        U R                  X45      u  pxUS	 XW-  nXh-  nXV4$ )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   )rU   r\   reverser-   )	r8   r=   rQ   rR   rY   rZ   r[   WnRWeRs	            r   
find_cycle&_DataEssentialsAndFunctions.find_cyclex   sr     NN1 &





9IIaL??1(G
	
	vrW   c                     [        X!5       HH  u  pEU R                  U   U:X  a  U R                  U==   U-  ss'   M1  U R                  U==   U-  ss'   MJ     g)zA
Augment f units of flow along a cycle represented by Wn and We.
N)zipr%   r/   )r8   rZ   r[   fr=   rQ   s         r   augment_flow(_DataEssentialsAndFunctions.augment_flow   sO     KDA  #q(q!Q&!q!Q&!	  rW   c              #   r   #    Uv   U R                   U   nX:w  a  U R                  U   nUv   X:w  a  M  gg7f)z4
Yield the nodes in the subtree rooted at a node p.
N)r6   r4   )r8   rQ   ls      r   trace_subtree)_DataEssentialsAndFunctions.trace_subtree   s=      $$Q'f""1%AG fs   177c                    U R                   U   nU R                  U   nU R                  U   nU R                  U   nSU R                  U'   SU R
                  U'   X`R                  U'   X@R                  U'   X R                  U'   XPR                  U'   UbM  U R                   U==   U-  ss'   U R                  U   U:X  a  X@R                  U'   U R                  U   nUb  ML  gg)zD
Remove an edge (s, t) where parent[t] == s from the spanning tree.
N)r3   r5   r6   r4   r1   r2   )r8   stsize_tprev_tlast_tnext_last_ts          r   remove_edge'_DataEssentialsAndFunctions.remove_edge   s     ""1%##A&))!,((0A"%06"*0;'%&6" &1 ma F* ''*f4.4((+AA	 mrW   c                 `   / nUb%  UR                  U5        U R                  U   nUb  M%  UR                  5         [        U[	        USS5      5       GHX  u  p1U R
                  U   nU R                  U   nU R                  U   nU R                  U   nU R                  U   nXR                  U'   SU R                  U'   U R                  U   U R                  U'   SU R                  U'   X@R
                  U   -
  U R
                  U'   X@R
                  U'   XR                  U'   X`R                  U'   XR                  U'   XpR                  U'   XW:X  a  X`R                  U'   UnXpR                  U'   X0R                  U'   XR                  U'   XPR                  U'   XPR                  U'   GM[     g)z3
Make a node q the root of its containing subtree.
Nr   )
r-   r1   r_   re   r   r3   r6   r5   r4   r2   )	r8   rR   	ancestorsrQ   rS   last_pprev_qlast_qnext_last_qs	            r   	make_root%_DataEssentialsAndFunctions.make_root   s    	mQAA m 		6)Q#=>DA&&q)F--a0F''*F--a0F,,V4KKKN!DKKN"&"2"21"5DQ"&DQ#),=,=a,@#@Da #)a )4v&.4{+)*v&$*q!.4((+ %+q!)*v&)*v&$*q!*0$$Q'7 ?rW   c                    U R                   U   nU R                  U   nU R                  U   nU R                   U   nX R                  U'   XR                  U'   X0R                  U'   X@R
                  U'   XpR
                  U'   XPR                  U'   UbM  U R                  U==   U-  ss'   U R                   U   U:X  a  XpR                   U'   U R                  U   nUb  ML  gg)zK
Add an edge (p, q) to the spanning tree where q is the root of a subtree.
N)r6   r4   r3   r1   r2   r5   )r8   r=   rQ   rR   rx   next_last_prT   rz   s           r   add_edge$_DataEssentialsAndFunctions.add_edge   s     ))!,((0""1%))!,A%&6" &1*0;'%06" ma F* ''*f4.4((+AA	 mrW   c                 D   X0R                   U   :X  a0  U R                  U   U R                  U   -
  U R                  U   -
  nO/U R                  U   U R                  U   -   U R                  U   -
  nU R                  U5       H  nU R                  U==   U-  ss'   M     g)zn
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&   r0   r*   rk   )r8   r=   rQ   rR   rG   s        r   update_potentials-_DataEssentialsAndFunctions.update_potentials   s    
 !!!$$$$Q'$*;*;A*>>AUAUVWAXXA$$Q'$*;*;A*>>AUAUVWAXXA##A&A  #q(# 'rW   c                     U R                   U   U R                  U R                  U      -
  U R                  U R                  U      -   nU R                  U   S:X  a  U$ U* $ )z&Returns the reduced cost of an edge i.r   )r*   r0   r%   r&   r/   )r8   r=   cs      r   reduced_cost(_DataEssentialsAndFunctions.reduced_cost  sr     a ""4#4#4Q#789""4#4#4Q#789 	

 NN1%*q22rW   c              #     #    U R                   S:X  a  g[        [        [        U R                   5      5      5      nU R                   U-   S-
  U-  nSnSnX2:  a  XA-   nXPR                   ::  a  [	        XE5      nO6XPR                   -  n[        [	        X@R                   5      [	        U5      5      nUn[        X`R                  S9nU R                  U5      nUS:  a  US-  nOXU R                  U   S:X  a  U R                  U   n	U R                  U   n
OU R                  U   n	U R                  U   n
XyU
4v   SnX2:  a  M  gg7f)z-Yield entering edges until none can be found.r   Nr   key)r.   intr   r   rK   r   minr   r/   r%   r&   )r8   BMmrf   rj   r+   r=   r   rQ   rR   s              r   find_entering_edges/_DataEssentialsAndFunctions.find_entering_edges
  s1    ??a T$//*+,__q 1$*eAOO#a__$eA7qBAE001A!!!$AAvQ >>!$)))!,A))!,A))!,A))!,AAg1 es   D;E?Ec                     U R                   U   U:X  a  U R                  U   U R                  U   -
  $ U R                  U   $ )zVReturns the residual capacity of an edge i in the direction away
from its endpoint p.
)r%   r)   r/   )r8   r=   rQ   s      r   residual_capacity-_DataEssentialsAndFunctions.residual_capacity4  sM       #q(   #dnnQ&77	
 "	
rW   c                    ^  [        [        [        U5      [        U5      5      U 4S jS9u  p4T R                  U   U:X  a  T R                  U   OT R                  U   nX4U4$ )z=Returns the leaving edge in a cycle represented by Wn and We.c                 "   > TR                   " U 6 $ rC   )r   )i_pr8   s    r   <lambda>?_DataEssentialsAndFunctions.find_leaving_edge.<locals>.<lambda>B  s    D22C8rW   r   )r   re   reversedr%   r&   )r8   rZ   r[   jrn   ro   s   `     r   find_leaving_edge-_DataEssentialsAndFunctions.find_leaving_edge>  s_    hrl+8
 %)$5$5a$8A$=Da 4CTCTUVCWQwrW   )r7   r)   r.   r/   r(   r'   r%   r&   r*   r6   r4   r$   r"   r    r0   r1   r2   r5   r3   Nr;   r   r<   )__name__
__module____qualname____firstlineno__r?   rN   rU   r\   rb   rg   rk   rt   r|   r   r   r   r   r   r   __static_attributes__ rW   r   r   r      sS    JR/
b/,,
&'0$1L0
)3&T
rW   r   
undirectedr;   r   )r   r<   )
node_attrs
edge_attrsc           
        ^^^^^^ [        U 5      S:X  a  [        R                  " S5      eU R                  5       n[	        XUTTS9m[        S5      m[        TR                  TR                  5       H/  u  pV[        U5      T:X  d  M  [        R                  " SU< S35      e   [        TR                  TR                  5       H/  u  px[        U5      T:X  d  M  [        R                  " SU< S35      e   U(       d  [        R                  " U S	S
9n	O[        R                  " U S	S	S9n	U	 HC  n[        US   R                  TS5      5      T:X  d  M'  [        R                  " SUSS < S35      e   [        TR                  5      S:w  a  [        R                  " S5      e[        TR                  TR                   5       H&  u  pzU
S:  d  M  [        R                  " SU< S35      e   U(       d  [        R                  " U S	S
9n	O[        R                  " U S	S	S9n	U	 H:  nUS   R                  TT5      S:  d  M  [        R                  " SUSS < S35      e   [#        TR                  5       Hy  u  pUS:  a8  TR$                  R'                  S5        TR(                  R'                  U5        MC  TR$                  R'                  U5        TR(                  R'                  S5        M{     S[+        [-        [        U4S jTR                    5       5      [        S TR                   5       5      /S TR                   5       5      5      -  =(       d    Sm[        TR                  5      nTR                  R/                  [1        TU5      5        TR                   R/                  [1        TU5      5        TR3                  UT5        TR5                  5        H  u  pnTR7                  XU5      u  nnTR9                  UU5      u  nnnTR;                  UUTR=                  UU5      5        UU:w  d  M\  TR>                  U   U:w  a  UUnnURA                  U5      URA                  U5      :  a  XpTRC                  UU5        TRE                  U5        TRG                  XU5        TRI                  XU5        M     [K        U4S j[M        U* S5       5       5      (       a  [        R                  " S5      e[K        UU4S j[M        TRN                  5       5       5      (       d/  [K        UUU4S j[        R                  " U S	S
9 5       5      (       a  [        RP                  " S5      eTRR                  TRN                  S2	 [        S [        TR                  TRR                  5       5       5      nTR                   Vs0 s H  o0 _M     snmU4S jnU4S jTR$                   5       Tl        U4S jTR(                   5       Tl        U(       dJ  [        TR$                  TR(                  TRR                  5       H  nU" U5        M     U RU                  S	S
9n	OU[        TR$                  TR(                  TRV                  TRR                  5       H  nU" U5        M     U RU                  S	S	S9n	U	 H  nUS   US   :w  a+  US   R                  TT5      S:X  a  U" USS S-   5        M8  M:  US   R                  TS5      nUS:  a  U" USS S-   5        Me  US   T   n
UX-  -  nU" USS U
4-   5        M     UT4$ s  snf )a8  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   6   >#    U  H  oT:  d  M
  Uv   M     g 7frC   r   )r   r   r   s     r   r   "network_simplex.<locals>.<genexpr>7  s     C#7as7#7s   		c              3   8   #    U  H  n[        U5      v   M     g 7frC   rD   )r   rY   s     r   r   r   8  s     :(91A(9rI   c              3   8   #    U  H  n[        U5      v   M     g 7frC   rD   rF   s     r   r   r   :  s     3!2AQ!2rI   r   c              3   H   >#    U  H  nTR                   U   S :g  v   M     g7f)r   Nr/   )r   r=   DEAFs     r   r   r   `  s     
8<a4>>!!<s   "z"no flow satisfies all node demandsc              3   N   >#    U  H  nTR                   U   S -  T:  v   M     g7f)r   Nr   )r   r=   r   rM   s     r   r   r   c  s&     
M6L4>>!q H,6Ls   "%c              3      >#    U  H<  nUS    R                  TT5      T:H  =(       a    US    R                  TS5      S:  v   M>     g7f)r   r   Nr   )r   r   r   r   r<   s     r   r   r   c  sI      U0A 	
"		(C C'DAbEIIfa,@1,DD0s   AAz+negative cycle with infinite capacity foundc              3   .   #    U  H  u  pX-  v   M     g 7frC   r   )r   rY   xs      r   r   r   n  s     M&LdaAE&Ls   c                 ~   > TU S      nU SS  H  n X   nM
     U S   XS   '   g! [          a    0 nX1U'   Un M,  f = f)zAdd a flow dict entry.r   r   r   N)KeyError)r   rG   kro   	flow_dicts       r   	add_entry"network_simplex.<locals>.add_entryq  s_    adO1RAD  R5B%	  !s   &<<c              3   B   >#    U  H  nTR                   U   v   M     g 7frC   r    )r   rn   r   s     r   r   r   }        #4aq#4   c              3   B   >#    U  H  nTR                   U   v   M     g 7frC   r   )r   ro   r   s     r   r   r     r   r   )r   ),rJ   nxNetworkXErroris_multigraphr   r,   re   r    r$   rE   r(   r*   selfloop_edgesr   sumNetworkXUnfeasibler)   r!   r%   r-   r&   maxr   extendr   rN   r   rb   r   rg   r   r1   indexrt   r|   r   r   anyrK   r.   NetworkXUnboundedr/   r+   r'   )r9   r;   r   r<   r:   r>   rG   r   rY   r+   r   r=   rL   rQ   rR   rZ   r[   r   rn   ro   	flow_costr   r   rM   r   r   s     ``                  @@@@r   r   r   H  su   T 1v{344"J '	fxD ,CDNND$5$56q6S=""U1%/C#DEE 7 D%%t'8'89q6S=""U1%/C#DEE : !!!$/!!!$T:quyy#$+""U1Sb6*4H#IJJ  4"##$CDDD%%t';';<q5''%u4J(KLL = !!!$/!!!$T:R599Xs#a'''%#2z9O(PQQ  $++, 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. ++-aq)B((R01a"b$"8"8A">?6{{1~"!1xx{RXXa[(1Q"NN1MM!"""1+ .* 
85!Q<
888##$HII

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