
    wg8                         d Z dgZddlmZ ddlmZ ddlZddlm	Z	m
Z
mZ d Z ed	      d
        Zd Z ej                  d ed      dd      ddde	fd       Zy)z/
Capacity scaling minimum cost flow algorithm.
capacity_scaling    )chain)logN   )
BinaryHeaparbitrary_elementnot_implemented_forc                    t        j                         }|j                  |        | j                  d   }t	        d      }| D ]i  }| |   j                         D ]Q  \  }}|}|j                         D ]  \  }}|d   |k(  st        ||d         } ||k7  s>|j                  |||       S k t        j                  |      rt        j                  d      y)z)Detect infinite-capacity negative cycles.infcapacityweight)r   UNegative cost cycle of infinite capacity found. Min cost flow may be unbounded below.N)
nxDiGraphadd_nodes_fromgraphfloatitemsminadd_edgenegative_edge_cycleNetworkXUnbounded)	RGr   f_infuvewks	            m/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/networkx/algorithms/flow/capacityscaling.py_detect_unboundednessr"      s    


AQ ''%.C%LE +aDJJL 	+DAqA	 ,1Z=C'Aq{+A, Ez

1a
*	++ 
a ""4
 	
 !    
undirectedc           
      x    t         fd D              dk7  rt        j                  d      t        j                         j	                   fd D               t        d      t        j                   d      D ]F  \  }}}|j                  |d      dk  s|j                        k(  s3t        j                  d        j                         rJ j                  dd	      D cg c]'  \  }}}}||k7  r|j                        dkD  r||||f) }}}}}nE j                  d      D cg c]&  \  }}}||k7  r|j                        dkD  r||d|f( }}}}t        t        fd
D              dt        fd|D              z        xs d|D ]h  \  }}}}t        |j                              }	|j                  |d      }
j                  |||df|	|
d       j                  |||dfd|
 d       j j                  d<   t               S c c}}}}w c c}}}w )z4Build a residual network and initialize a zero flow.c              3   \   K   | ]#  }j                   |   j                  d        % ywr   Nnodesget.0r   r   demands     r!   	<genexpr>z*_build_residual_network.<locals>.<genexpr>,   s$     
01771:>>&!$
0s   ),r   zSum of the demands should be 0.c              3   h   K   | ])  }|j                   |   j                  d        d df + yw)r   )excess	potentialNr(   r+   s     r!   r.   z*_build_residual_network.<locals>.<genexpr>0   s6      HI
vq11BCs   /2r   Tdatar   )r3   keysc              3   T   K   | ]  }t        j                  |   d           ! yw)r0   N)absr)   r,   r   r   s     r!   r.   z*_build_residual_network.<locals>.<genexpr>Q   s#     5aAGGAJx()5s   %(   c              3   J   K   | ]  \  }}}}|v r|   k7  r|     y w)N )r,   r   r   r    r   r   r   s        r!   r.   z*_build_residual_network.<locals>.<genexpr>S   s7      Aq!Qq=Qx[C%7 (s    #   )keyr   r   flowF)sumr   NetworkXUnfeasibleMultiDiGraphr   r   selfloop_edgesr*   r   is_multigraphedgesmaxr   r   r   r"   )r   r-   r   r   r   r   r   r    	edge_listrr   r   r   s   ```        @@r!   _build_residual_networkrG   )   s`    
0a
00A5##$EFF
A MN  ,C$$QT2 1a55aAEE(C$8C$?&&8  	  gg4dg;
 
1aAv!%%#.2 1aL
	 
 777-
 
1aAv!%%#.2 1aL
	 
 	5155 "+ 	
 		     H
1ah$c*EE&! 	


1aaY11
E	

1aaZ!QBQ
GH AGGEN!HU

s   5,H-
=+H5c                 &   t        d      }i }| j                         r| D ]  }i ||<   | |   j                         D ]c  \  }}|j                         D 	
ci c]<  \  }	}
|	||k7  s*|
j                  ||      dk  s|
j                  |d      dk\  rdn|
|   > c}
}	||   |<   e ||   j                         D ]9  \  }}|||   v s||   |   j	                  d |j                         D               ;  |S | D ]  }| |   j                         D 
ci c]<  \  }}
|||k7  s*|
j                  ||      dk  s|
j                  |d      dk\  rdn|
|   > c}
}||<   ||   j	                  d ||   j                         D                |S c c}
}	w c c}
}w )z0Build a flow dictionary from a residual network.r   r   c              3   H   K   | ]  \  }}|d    dkD  s|d   |d    f  ywr=   r   Nr:   )r,   r    r   s      r!   r.   z#_build_flow_dict.<locals>.<genexpr>   s1      +.2aAfIPQM1qy)+s   ""c              3   j   K   | ]+  \  }}|j                         D ]  }|d    dkD  r	||d    f  - ywrJ   )values)r,   r   esr   s       r!   r.   z#_build_flow_dict.<locals>.<genexpr>   sJ       Ar  V9q= AfI  s   13)r   rB   r   r*   update)r   r   r   r   r   	flow_dictr   r   rM   r    r   s              r!   _build_flow_dictrP   l   s   
,CI 	AIaL1 2 !#

# 1  FaeeHc&:a&?155QRCSWXCX  x[)
#	!Q 1 2	!$aLO** +68hhj+ 	H !  	A aDJJL Aq Q!%%#"6!";quuVQ?OST?T 8%IaL aL  qTZZ\  	  C
#$s   AF
AFr-   r   )r   r   )
node_attrs
edge_attrsr   r   c           	      |  &' t        | |      &t        d      't        'fdt        j                  | d      D              }t        t        ' gd &j                  d      D                    }|' k(  r|t        | &      fS &j                  }&j                  }dt        t        |d            z  }	|	dk\  r&D ]  }
||
   d   }||
   j                         D ]  \  }}|j                         D ]  \  }}|d	   |d
   z
  }|d   |z
  ||   d   z   dk  s&|d	   |d
   z
  }||	k\  s7|d
xx   |z  cc<   ||   |
   |d   |d    f   d
xx   |z  cc<   ||
   dxx   |z  cc<   ||   dxx   |z  cc<      t               }t               }|j                  }|j                   }|j                  }|j                   }&D ]'  }
||
   d   }||	k\  r	 ||
       ||	 k  s  ||
       ) |r|rt#        |      }d}i }|di} |       }|j$                  }|j&                  } ||d       |r|j)                         \  }
}|||
<   |
|v r|
}n||
   d   }||
   j                         D ]m  \  }}||v r'} |j                         D ]%  \  }}|d	   |d
   z
  |	k\  s|d   }!|!| k  s |!} |}"|}#' | 'k(  rK|| z   |z
  ||   d   z   }$ |||$      sf|
"#f||<   o |r|
|k7  r=|
}||   \  }
}}|d
xx   |	z  cc<   ||   |
   |d   |d    f   d
xx   |	z  cc<   |
|k7  r=||   dxx   |	z  cc<   ||   dxx   |	z  cc<   ||   d   |	k  r ||       ||   d   |	 kD  r ||       ||   }%|j                         D ]  \  }
}||
   dxx   ||%z
  z  cc<    n ||       |r|r|	dz  }	|	dk\  rt+        &fd&D              rt        j,                  d      &D ]H  }
||
   j                         D ]0  \  }}|j/                         D ]  }|d
   }|dkD  s|||d   z  z  } 2 J |t        | &      fS )a  Find a minimum cost flow satisfying all demands in digraph G.

    This is a capacity scaling successive shortest augmenting path algorithm.

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

    heap : class
        Type of heap to be used in the algorithm. It should be a subclass of
        :class:`MinHeap` or implement a compatible interface.

        If a stock heap implementation is to be used, :class:`BinaryHeap` is
        recommended over :class:`PairingHeap` for Python implementations without
        optimized attribute accesses (e.g., CPython) despite a slower
        asymptotic running time. For Python implementations with optimized
        attribute accesses (e.g., PyPy), :class:`PairingHeap` provides better
        performance. Default value: :class:`BinaryHeap`.

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

    flowDict : dictionary
        If G is a digraph, a dict-of-dicts keyed by nodes such that
        flowDict[u][v] is the flow on edge (u, v).
        If G is a MultiDiGraph, a dict-of-dicts-of-dicts keyed by nodes
        so that flowDict[u][v][key] is the flow on edge (u, v, key).

    Raises
    ------
    NetworkXError
        This exception is raised if the input graph is not directed,
        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 does not work if edge weights are floating-point numbers.

    See also
    --------
    :meth:`network_simplex`

    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.capacity_scaling(G)
    >>> flowCost
    24
    >>> flowDict
    {'a': {'b': 4, 'c': 1}, 'd': {}, 'b': {'d': 4}, 'c': {'d': 1}}

    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.capacity_scaling(
    ...     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': {}}
    r   c              3      K   | ]?  \  }}}|j                        d k  s|j                  d       d k\  rd n
|   |   z   A ywr'   )r*   )r,   r   r   r   r   r   r   s       r!   r.   z#capacity_scaling.<locals>.<genexpr>!  s]       Aq! 5531$fa(8A(= 	
x[1V9$	%s   AATr2   c              3   .   K   | ]  \  }}}|d      yw)r   Nr:   )r,   r   r   r   s       r!   r.   z#capacity_scaling.<locals>.<genexpr>)  s     N1aa
mNs   r8   r;   r1   r   r=   r   r   r0   Nc              3   H   K   | ]  }j                   |   d    dk7    yw)r0   r   N)r)   r7   s     r!   r.   z#capacity_scaling.<locals>.<genexpr>  s#     
01771:h1$
0s   "zNo flow satisfying all demands.)rG   r   r>   r   rA   rD   r   rC   rP   r)   succintr   r   setaddremover   insertr*   popanyr?   rL   )(r   r-   r   r   heap	flow_costwmaxR_nodesR_succdeltar   p_ur   rM   r    r   r=   STS_addS_removeT_addT_remover0   stdpredhh_inserth_getd_uwminr   kminemind_vd_tr   r   s(     ``                                  @@r!   r   r      s2   J 	 68V<A
,C  ((6	 I usdVN1777;MNOPDt|*1a6BBBggGVVFSq\""E
1*  	9A!*[)C* 	92HHJ 9DAqZ=1V94D{S(71:k+BBQF }qy85=fI-I"1IaL!A$AaD)9:6BdJB#AJx0D80#AJx0D809	9	9 EE8888 	AQZ)FaE6!a	 A!!$AA At9DAxxHEEEQN3!6Aaj-#AY__. 2EArAv D "
 )1Z=1V94= !(A 4x'('('() s{ *s*WQZ-DDC3'#$dD/Q#2 4 }1fA"1gGAq!fI&I1IaL!A$AaD!126:eC:	 1f 
8$-$
8$-$1:h'%/QK1:h'5&0QKdggi 9FAsAJ{+sSy8+9 s At 	!q 1*t 
0a
00##$EFF  4AY__& 	4EArYY[ 4y!8(!33I4	44 &q!Xv>>>r#   )__doc____all__	itertoolsr   mathr   networkxr   utilsr   r   r	   r"   rG   rP   _dispatchabler   r   r:   r#   r!   <module>r      s    
    G G
4 \"? #?D)X u$K H:|?|?r#   