
    wgT                        d Z ddlZddlZddlZddlmZ ddlm	Z	 g dZ
 ed      Zej                  dd       Zej                  dd       Zd	 Zd
 Zej                  dd       ZeZ ej                  d      dd       Zy)a'  Provides functions for computing maximum cardinality matchings and minimum
weight full matchings in a bipartite graph.

If you don't care about the particular implementation of the maximum matching
algorithm, simply use the :func:`maximum_matching`. If you do care, you can
import one of the named maximum matching algorithms directly.

For example, to find a maximum matching in the complete bipartite graph with
two vertices on the left and three vertices on the right:

>>> G = nx.complete_bipartite_graph(2, 3)
>>> left, right = nx.bipartite.sets(G)
>>> list(left)
[0, 1]
>>> list(right)
[2, 3, 4]
>>> nx.bipartite.maximum_matching(G)
{0: 2, 1: 3, 2: 0, 3: 1}

The dictionary returned by :func:`maximum_matching` includes a mapping for
vertices in both the left and right vertex sets.

Similarly, :func:`minimum_weight_full_matching` produces, for a complete
weighted bipartite graph, a matching whose cardinality is the cardinality of
the smaller of the two partitions, and for which the sum of the weights of the
edges included in the matching is minimal.

    N)sets)biadjacency_matrix)maximum_matchinghopcroft_karp_matchingeppstein_matchingto_vertex_coverminimum_weight_full_matchinginfc                 Z   	
  	
fd} 
fdt         |      \  	}	D ci c]  }|d c}
|D ci c]  }|d c}i t        j                         d} |       r#	D ]  }
|   	 |      s|dz  }  |       r#
j                         D ci c]  \  }}|	|| c}}
j                         D ci c]  \  }}|	|| c}}t	        t        j                  
j                         j                                     S c c}w c c}w c c}}w c c}}w )a  Returns the maximum cardinality matching of the bipartite graph `G`.

    A matching is a set of edges that do not share any nodes. A maximum
    cardinality matching is a matching with the most edges possible. It
    is not always unique. Finding a matching in a bipartite graph can be
    treated as a networkx flow problem.

    The functions ``hopcroft_karp_matching`` and ``maximum_matching``
    are aliases of the same function.

    Parameters
    ----------
    G : NetworkX graph

      Undirected bipartite graph

    top_nodes : container of nodes

      Container with all nodes in one bipartite node set. If not supplied
      it will be computed. But if more than one solution exists an exception
      will be raised.

    Returns
    -------
    matches : dictionary

      The matching is returned as a dictionary, `matches`, such that
      ``matches[v] == w`` if node `v` is matched to node `w`. Unmatched
      nodes do not occur as a key in `matches`.

    Raises
    ------
    AmbiguousSolution
      Raised if the input bipartite graph is disconnected and no container
      with all nodes in one bipartite set is provided. When determining
      the nodes in each bipartite set more than one valid solution is
      possible if the input graph is disconnected.

    Notes
    -----
    This function is implemented with the `Hopcroft--Karp matching algorithm
    <https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithm>`_ for
    bipartite graphs.

    See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
    for further details on how bipartite graphs are handled in NetworkX.

    See Also
    --------
    maximum_matching
    hopcroft_karp_matching
    eppstein_matching

    References
    ----------
    .. [1] John E. Hopcroft and Richard M. Karp. "An n^{5 / 2} Algorithm for
       Maximum Matchings in Bipartite Graphs" In: **SIAM Journal of Computing**
       2.4 (1973), pp. 225--231. <https://doi.org/10.1137/0202019>.

    c                  :   D ]'  } |    d| <   j                  |        t        | <   ) t        d <   rYj                         } |    d    k  r;|    D ]3  }|      t        u s|    dz   |   <   j                  |          5 rYd    t        uS )Nr      )appendINFINITYpopleft)vuG	distancesleftleftmatchesqueuerightmatchess     k/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/networkx/algorithms/bipartite/matching.pybreadth_first_searchz4hopcroft_karp_matching.<locals>.breadth_first_search   s     	(A1~% 	!Q'	!	( #	$A|io-1 6A a1X=5>q\A5E	,q/2\!_56  h..    c                     | =|    D ]+  }|      |    dz   k(  s |         s!| |<   || <    y t         | <   yy)Nr   TF)r   )r   r   r   depth_first_searchr   r   r   s     r   r   z2hopcroft_karp_matching.<locals>.depth_first_search   sg    =qT $\!_-11AA),q/:*+Q)*A#$ $IaLr   Nr   r   )bipartite_setscollectionsdequeitemsdict	itertoolschain)r   	top_nodesr   rightr   num_matched_pairskr   r   r   r   r   r   s   `      @@@@@@r   r   r   :   s.   J/ /"
 
 !I.KD%$()q1d7)K%*+AtG+LIE 

  	+A1~%%a(%*%	+ 
  %0$5$5$7IDAq1=1a4IK%1%7%7%9KTQQ]AqDKL 	 1 1 3\5G5G5IJKK1 *+ JKs"   
D
D!
D!,D!
D'D'c                   	
 t        | |      \  }}t        j                  | j                  |            } i 	| D ]  }| |   D ]  }|	vs|	|<      	 i g | D ci c]  }| c}
	D ]  }
	|   = 
 t	        
      }|rsi }|D ]2  }| |   D ](  }|vs|j                  |g       j                  |       * 4 g }|D ]<  }||   |<   |	v r|j                  	|          |
	|   <   ,j                  |       > |rss	j                         D ]
  }|		|   <    	S 	
fdD ]
  } |        c c}w )a  Returns the maximum cardinality matching of the bipartite graph `G`.

    Parameters
    ----------
    G : NetworkX graph

      Undirected bipartite graph

    top_nodes : container

      Container with all nodes in one bipartite node set. If not supplied
      it will be computed. But if more than one solution exists an exception
      will be raised.

    Returns
    -------
    matches : dictionary

      The matching is returned as a dictionary, `matching`, such that
      ``matching[v] == w`` if node `v` is matched to node `w`. Unmatched
      nodes do not occur as a key in `matching`.

    Raises
    ------
    AmbiguousSolution
      Raised if the input bipartite graph is disconnected and no container
      with all nodes in one bipartite set is provided. When determining
      the nodes in each bipartite set more than one valid solution is
      possible if the input graph is disconnected.

    Notes
    -----
    This function is implemented with David Eppstein's version of the algorithm
    Hopcroft--Karp algorithm (see :func:`hopcroft_karp_matching`), which
    originally appeared in the `Python Algorithms and Data Structures library
    (PADS) <http://www.ics.uci.edu/~eppstein/PADS/ABOUT-PADS.txt>`_.

    See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
    for further details on how bipartite graphs are handled in NetworkX.

    See Also
    --------

    hopcroft_karp_matching

    c                     | v rAj                  |       }|D ]+  }|v sj                  |      }|u s	 |      s&|| <    y y)NTF)pop)	r   Lr   pumatchingpredpredsrecurse	unmatcheds	       r   r1   z"eppstein_matching.<locals>.recurse5  sX    EzIIaL (ADy!XXa[?gbk*+HQK#'( r   )r   nxDiGraphedgeslist
setdefaultr   copy)r   r%   r   r&   r   r   layernewLayerkeyr.   r/   r0   r1   r2   s            @@@@@r   r   r      s   d !I.KD%


1774=!AH 1 	A 	
  	&'(9( 	"AXa[!	"T
 IH =1 =A~ ++Ar299!<== E (#A;a=LL!-()D!%$$Q'( I  8  }} .*-#'.O		 		  	AAJ	Y  )s    
Ec                 H     d fd	} ||d      xs
  ||d      S )a  Returns True if and only if the vertex `v` is connected to one of
    the target vertices by an alternating path in `G`.

    An *alternating path* is a path in which every other edge is in the
    specified maximum matching (and the remaining edges in the path are not in
    the matching). An alternating path may have matched edges in the even
    positions or in the odd positions, as long as the edges alternate between
    'matched' and 'unmatched'.

    `G` is an undirected bipartite NetworkX graph.

    `v` is a vertex in `G`.

    `matched_edges` is a set of edges present in a maximum matching in `G`.

    `unmatched_edges` is a set of edges not present in a maximum
    matching in `G`.

    `targets` is a set of vertices.

    Tc                 `   t               }|rdnd}| t        
|          |fg}|rj|d   \  }}}|dz  rn}	 t        |      }	|	|vrE||	f|v s|	|f|v r9|	v ry|j                  |	       |j	                  |	t        
|	         |dz   f       |rjy# t
        $ r |j                          Y w xY w)at  Returns True if and only if `u` is connected to one of the
        targets by an alternating path.

        `u` is a vertex in the graph `G`.

        If `along_matched` is True, this step of the depth-first search
        will continue only through edges in the given matching. Otherwise, it
        will continue only through edges *not* in the given matching.

        r   r      TF)setiternextaddr   StopIterationr+   )r   along_matchedvisitedinitial_depthstackparentchildrendepthvalid_edgeschildr   matched_edgestargetsunmatched_edgess             r   _alternating_dfsz;_is_connected_by_alternating_path.<locals>._alternating_dfs[  s     % +T!A$Z/0&+Bi#FHe+019-/K	X'+5%K9W G+#'E*eT!E(^UQY%GH   ! 		s   B 4B B-,B-)rE   F)T )r   r   rN   rP   rO   rQ   s   ` ``` r   !_is_connected_by_alternating_pathrS   D  s1    . D AT2 6F	7 r   c           
      f   |j                         D ch c]  \  }}t        ||f       }}}|D ch c]  }t        |       }}| j                         D ch c]  \  }}t        ||f      |vs||f }}}| D ch c]  }||v st	        | ||||      r| c}S c c}}w c c}w c c}}w c c}w )a  Returns the set of vertices that are connected to one of the target
    vertices by an alternating path in `G` or are themselves a target.

    An *alternating path* is a path in which every other edge is in the
    specified maximum matching (and the remaining edges in the path are not in
    the matching). An alternating path may have matched edges in the even
    positions or in the odd positions, as long as the edges alternate between
    'matched' and 'unmatched'.

    `G` is an undirected bipartite NetworkX graph.

    `matching` is a dictionary representing a maximum matching in `G`, as
    returned by, for example, :func:`maximum_matching`.

    `targets` is a set of vertices.

    )r!   	frozensettupler5   rS   )	r   r.   rO   r   r   	edge_setsedgerN   rP   s	            r   _connected_by_alternating_pathsrY     s    , 08~~/?@tq!Aq6"@I@-67TU4[7M7WWYAq)QF*;9*LAO  <,q-'
 	
  A7s   BB#B(1B(>B.c                     t        | |      \  }}t        |       t        |      z
  }||z  }t        | ||      }||z
  ||z  z  S )a  Returns the minimum vertex cover corresponding to the given maximum
    matching of the bipartite graph `G`.

    Parameters
    ----------
    G : NetworkX graph

      Undirected bipartite graph

    matching : dictionary

      A dictionary whose keys are vertices in `G` and whose values are the
      distinct neighbors comprising the maximum matching for `G`, as returned
      by, for example, :func:`maximum_matching`. The dictionary *must*
      represent the maximum matching.

    top_nodes : container

      Container with all nodes in one bipartite node set. If not supplied
      it will be computed. But if more than one solution exists an exception
      will be raised.

    Returns
    -------
    vertex_cover : :class:`set`

      The minimum vertex cover in `G`.

    Raises
    ------
    AmbiguousSolution
      Raised if the input bipartite graph is disconnected and no container
      with all nodes in one bipartite set is provided. When determining
      the nodes in each bipartite set more than one valid solution is
      possible if the input graph is disconnected.

    Notes
    -----
    This function is implemented using the procedure guaranteed by `Konig's
    theorem
    <https://en.wikipedia.org/wiki/K%C3%B6nig%27s_theorem_%28graph_theory%29>`_,
    which proves an equivalence between a maximum matching and a minimum vertex
    cover in bipartite graphs.

    Since a minimum vertex cover is the complement of a maximum independent set
    for any graph, one can compute the maximum independent set of a bipartite
    graph this way:

    >>> G = nx.complete_bipartite_graph(2, 3)
    >>> matching = nx.bipartite.maximum_matching(G)
    >>> vertex_cover = nx.bipartite.to_vertex_cover(G, matching)
    >>> independent_set = set(G) - vertex_cover
    >>> print(list(independent_set))
    [2, 3, 4]

    See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
    for further details on how bipartite graphs are handled in NetworkX.

    )r   r@   rY   )r   r.   r%   r,   Runmatched_verticesUZs           r   r   r     sW    ~ !Y'DAqQ#h-/QA 	(8Q7A Ea!er   weight)
edge_attrsc                 4   ddl }ddl}t        j                  j	                  | |      \  }}t        |      }t        |      }t        | |||d      }	|j                  |	j                  |j                        }
|	j                  |
|	j                  |	j                  f<   |j                  j                  |
      }t        | D ci c]  \  }}||   ||    }}}|j!                  |j#                         D ci c]  \  }}||
 c}}       |S c c}}w c c}}w )u  Returns a minimum weight full matching of the bipartite graph `G`.

    Let :math:`G = ((U, V), E)` be a weighted bipartite graph with real weights
    :math:`w : E \to \mathbb{R}`. This function then produces a matching
    :math:`M \subseteq E` with cardinality

    .. math::
       \lvert M \rvert = \min(\lvert U \rvert, \lvert V \rvert),

    which minimizes the sum of the weights of the edges included in the
    matching, :math:`\sum_{e \in M} w(e)`, or raises an error if no such
    matching exists.

    When :math:`\lvert U \rvert = \lvert V \rvert`, this is commonly
    referred to as a perfect matching; here, since we allow
    :math:`\lvert U \rvert` and :math:`\lvert V \rvert` to differ, we
    follow Karp [1]_ and refer to the matching as *full*.

    Parameters
    ----------
    G : NetworkX graph

      Undirected bipartite graph

    top_nodes : container

      Container with all nodes in one bipartite node set. If not supplied
      it will be computed.

    weight : string, optional (default='weight')

       The edge data key used to provide each value in the matrix.
       If None, then each edge has weight 1.

    Returns
    -------
    matches : dictionary

      The matching is returned as a dictionary, `matches`, such that
      ``matches[v] == w`` if node `v` is matched to node `w`. Unmatched
      nodes do not occur as a key in `matches`.

    Raises
    ------
    ValueError
      Raised if no full matching exists.

    ImportError
      Raised if SciPy is not available.

    Notes
    -----
    The problem of determining a minimum weight full matching is also known as
    the rectangular linear assignment problem. This implementation defers the
    calculation of the assignment to SciPy.

    References
    ----------
    .. [1] Richard Manning Karp:
       An algorithm to Solve the m x n Assignment Problem in Expected Time
       O(mn log n).
       Networks, 10(2):143–152, 1980.

    r   Ncoo)	row_ordercolumn_orderr_   format)numpyscipyr3   	bipartiter   r6   r   fullshaper
   datarowcoloptimizelinear_sum_assignmentzipupdater!   )r   r%   r_   npspr   r&   r]   Vweights_sparseweightsleft_matchesr   r   ds                  r   r	   r	     s    D ,,##Ay1KD%T
AUA (	QQveN ggn**BFF3G6D6I6IGN 2 223;;44W=L #\ 2311qt3A3 HHqwwy)tq!ad)*H	 	4 *s   D7D
)N)Nr_   )__doc__r   r#   networkxr3   networkx.algorithms.bipartiter   r   $networkx.algorithms.bipartite.matrixr   __all__floatr   _dispatchabler   r   rS   rY   r   r   r	   rR   r   r   <module>r      s   :    @ C < {L {L| G GT;|#L G GZ *  X&T 'Tr   