
    wg3                         d Z ddlZddlm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 ddlmZ d	gZ ed
       e	j"                  d      dd              Zd ZddZ G d de	j*                        Zy)z,Fast approximation for k-component structure    N)defaultdict)Mapping)cached_property)local_node_connectivity)NetworkXError)not_implemented_fork_componentsdirectedapproximate_k_components)namec           
         t        t              }t        }t        j                  }t        j
                  }t        j                  }t        j                  }t        j                  |       D ]0  }t        |      }	t        |	      dkD  s|d   j                  |	       2 t        j                  |       D ]0  }
t        |
      }t        |      dkD  s|d   j                  |       2  ||       }t        |j                               }t        d|dz         D ]9  } || ||      } ||      D ]  }t        |      |k  r| j!                  |      }t#               }|j%                  |j'                                 ||d      D ])  \  }} |||||      }||kD  s|j)                  ||       +  ||      D ]  }t        |      |k  r|j!                  |      }t+        ||||      D ]`  } ||      D ]S  }t        j                  |j!                  |      |      }t        |      |k  r7||   j                  t        |             U b  " < |S )a  Returns the approximate k-component structure of a graph G.

    A `k`-component is a maximal subgraph of a graph G that has, at least,
    node connectivity `k`: we need to remove at least `k` nodes to break it
    into more components. `k`-components have an inherent hierarchical
    structure because they are nested in terms of connectivity: a connected
    graph can contain several 2-components, each of which can contain
    one or more 3-components, and so forth.

    This implementation is based on the fast heuristics to approximate
    the `k`-component structure of a graph [1]_. Which, in turn, it is based on
    a fast approximation algorithm for finding good lower bounds of the number
    of node independent paths between two nodes [2]_.

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

    min_density : Float
        Density relaxation threshold. Default value 0.95

    Returns
    -------
    k_components : dict
        Dictionary with connectivity level `k` as key and a list of
        sets of nodes that form a k-component of level `k` as values.

    Raises
    ------
    NetworkXNotImplemented
        If G is directed.

    Examples
    --------
    >>> # Petersen graph has 10 nodes and it is triconnected, thus all
    >>> # nodes are in a single component on all three connectivity levels
    >>> from networkx.algorithms import approximation as apxa
    >>> G = nx.petersen_graph()
    >>> k_components = apxa.k_components(G)

    Notes
    -----
    The logic of the approximation algorithm for computing the `k`-component
    structure [1]_ is based on repeatedly applying simple and fast algorithms
    for `k`-cores and biconnected components in order to narrow down the
    number of pairs of nodes over which we have to compute White and Newman's
    approximation algorithm for finding node independent paths [2]_. More
    formally, this algorithm is based on Whitney's theorem, which states
    an inclusion relation among node connectivity, edge connectivity, and
    minimum degree for any graph G. This theorem implies that every
    `k`-component is nested inside a `k`-edge-component, which in turn,
    is contained in a `k`-core. Thus, this algorithm computes node independent
    paths among pairs of nodes in each biconnected part of each `k`-core,
    and repeats this procedure for each `k` from 3 to the maximal core number
    of a node in the input graph.

    Because, in practice, many nodes of the core of level `k` inside a
    bicomponent actually are part of a component of level k, the auxiliary
    graph needed for the algorithm is likely to be very dense. Thus, we use
    a complement graph data structure (see `AntiGraph`) to save memory.
    AntiGraph only stores information of the edges that are *not* present
    in the actual auxiliary graph. When applying algorithms to this
    complement graph data structure, it behaves as if it were the dense
    version.

    See also
    --------
    k_components

    References
    ----------
    .. [1]  Torrents, J. and F. Ferraro (2015) Structural Cohesion:
            Visualization and Heuristics for Fast Computation.
            https://arxiv.org/pdf/1503.04476v1

    .. [2]  White, Douglas R., and Mark Newman (2001) A Fast Algorithm for
            Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
            https://www.santafe.edu/research/results/working-papers/fast-approximation-algorithms-for-finding-node-ind

    .. [3]  Moody, J. and D. White (2003). Social cohesion and embeddedness:
            A hierarchical conception of social groups.
            American Sociological Review 68(1), 103--28.
            https://doi.org/10.2307/3088904

             )core_number)cutoff)r   listr   nxk_corer   biconnected_components	itertoolscombinationsconnected_componentssetlenappendmaxvaluesrangesubgraph
_AntiGraphadd_nodes_fromnodesadd_edge_cliques_heuristic)Gmin_densityr	   node_connectivityr   r   r   r   	componentcompbicomponentbicomp	g_cnumbermax_corekCr#   SGHuvKh_nodesSHGck_nodesGks                              r/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/networkx/algorithms/approximation/kcomponents.pyr	   r	      s;   v t$L/YYF..K66))L ,,Q/ )	9~t9q=O""4(	)
 003 +[!v;?O""6*	+ AI9##%&H1hl# 81aY/+A. 	8E 5zA~E"BARXXZ($R+ %1%b!Qq9q5JJq!$% 2!4 	8w<1$ZZ(,RQD 8B#9"#= 8YYr{{7';Q?r7a<$$Q..s2w7	88		8	882     c              #     K   t        j                  |      }t        t        t	        |j                               d            D ]  \  }}|j                         D ch c]  \  }}||k(  s| }	}}|dk(  rd}
n8t	        j                  |	D cg c]  }||   D ch c]	  }||	vs| c} c}} }
|
r#t        |
      |k  r|j                  |	|
z        }n|j                  |	      }t        j                  |      }t        j                  | j                  |      |      }t        |      rt        j                  |      |k\  s|j                  |      j                         }t        |      |k  r1t        j                  |      }t        |j                               }t!        |j                               |j#                  fd|j                         D               t        j                  | j                  |      |      }t        |      st        j                  |      |k\  s|  y c c}}w c c}w c c}}w w)NT)reverser   Fc              3   4   K   | ]  \  }}|k(  s|  y wN ).0ndmin_degs      r;   	<genexpr>z%_cliques_heuristic.<locals>.<genexpr>   s      Ntq!g Ns   )r   r   	enumeratesortedr   r   itemsintersectionr   r    r   _samedensitycopydictdegreeminremove_nodes_from)r&   r2   r/   r'   	h_cnumberic_valuerC   ccandsoverlapxr7   
sh_cnumberr1   sh_degrE   s                   @r;   r%   r%      s    q!Is9+;+;+='> MN 
7(0Atq!ALAA6G&&?DE!ad5aun15EG s7|a'EGO,BE"B^^B'
YYqzz"~q)$B;)FB$$&B2w!|+J"))+&F&--/*G   Nv||~ NN1::b>1-B $B;)F H5A 6EsO   AI	 H8.H82I	I	H>'H>+I0E&I	I	0I	>II	c                 l    t        | j                               }t        |      t        |      z
  |k  ryy)NTF)r   r   r   rP   )measuretolvalss      r;   rK   rK      s.    w~~ DD	CI#%r<   c                       e Zd ZdZddiZd ZeZd Zd Z G d de	      Z
 G d	 d
e
      Zed        Zd Z G d dej                   j"                        Zed        Zd Zy)r!   a  
    Class for complement graphs.

    The main goal is to be able to work with big and dense graphs with
    a low memory footprint.

    In this class you add the edges that *do not exist* in the dense graph,
    the report methods of the class return the neighbors, the edges and
    the degree as if it was the dense graph. Thus it's possible to use
    an instance of this class with some of NetworkX functions. In this
    case we only use k-core, connected_components, and biconnected_components.
    weightr   c                     | j                   S r@   )all_edge_dictselfs    r;   single_edge_dictz_AntiGraph.single_edge_dict   s    !!!r<   c                     | j                   }t        | j                        t        | j                  |         z
  |hz
  D ci c]  }|| c}S c c}w )a  Returns a dict of neighbors of node n in the dense graph.

        Parameters
        ----------
        n : node
           A node in the graph.

        Returns
        -------
        adj_dict : dictionary
           The adjacency dictionary for nodes connected to n.

        )rb   r   _adj)rd   rC   rb   nodes       r;   __getitem__z_AntiGraph.__getitem__   sT     **,/		NS1=N,NRSQT,T
$(D-
 	
 
s   
Ac                     	 t        t        | j                        t        | j                  |         z
  |hz
        S # t        $ r}t	        d| d      |d}~ww xY w)zUReturns an iterator over all neighbors of node n in the
        dense graph.
        z	The node z is not in the graph.N)iterr   rg   KeyErrorr   )rd   rC   errs      r;   	neighborsz_AntiGraph.neighbors   s]    	ODIITYYq\)::aS@AA 	O)A3.C DE3N	Os   := 	AAAc                   (    e Zd ZdZd Zd Zd Zd Zy)_AntiGraph.AntiAtlasViewz%An adjacency inner dict for AntiGraphc                 H    || _         |j                  |   | _        || _        y r@   )_graphrg   _atlas_node)rd   graphrh   s      r;   __init__z!_AntiGraph.AntiAtlasView.__init__   s     DK**T*DKDJr<   c                 ^    t        | j                        t        | j                        z
  dz
  S )Nr   )r   rr   rs   rc   s    r;   __len__z _AntiGraph.AntiAtlasView.__len__   s$    t{{#c$++&66::r<   c                 .      fd j                   D        S )Nc              3   `   K   | ]%  }|j                   vs|j                  k7  s"| ' y wr@   )rs   rt   )rB   rC   rd   s     r;   rF   z4_AntiGraph.AntiAtlasView.__iter__.<locals>.<genexpr>  s&     W!at{{.BqDJJAWs   ...)rr   rc   s   `r;   __iter__z!_AntiGraph.AntiAtlasView.__iter__  s    Wt{{WWr<   c                     t        | j                  j                        t        | j                        z
  | j                  hz
  }||v r| j                  j
                  S t        |      r@   )r   rr   rg   rs   rt   rb   rl   )rd   nbrnbrss      r;   ri   z$_AntiGraph.AntiAtlasView.__getitem__  sP    t{{''(3t{{+;;tzzlJDd{{{0003-r<   N__name__
__module____qualname____doc__rv   rx   r{   ri   rA   r<   r;   AntiAtlasViewrp      s    3	
	;	X	 r<   r   c                   (    e Zd ZdZd Zd Zd Zd Zy)_AntiGraph.AntiAdjacencyViewz%An adjacency outer dict for AntiGraphc                 4    || _         |j                  | _        y r@   )rr   rg   rs   )rd   ru   s     r;   rv   z%_AntiGraph.AntiAdjacencyView.__init__  s    DK**DKr<   c                 ,    t        | j                        S r@   )r   rs   rc   s    r;   rx   z$_AntiGraph.AntiAdjacencyView.__len__  s    t{{##r<   c                 ,    t        | j                        S r@   )rk   rr   rc   s    r;   r{   z%_AntiGraph.AntiAdjacencyView.__iter__  s    $$r<   c                     || j                   vrt        |      | j                   j                  | j                   |      S r@   )rr   rl   r   )rd   rh   s     r;   ri   z(_AntiGraph.AntiAdjacencyView.__getitem__  s3    4;;&tn$;;,,T[[$??r<   Nr   rA   r<   r;   AntiAdjacencyViewr   
  s    3	%	$	%	@r<   r   c                 $    | j                  |       S r@   )r   rc   s    r;   adjz_AntiGraph.adj  s    %%d++r<   c                 V   t        |      }t               }|j                  |       |D ]l  }|j                         }||j                  |<   | j                  |   j                         D ]+  \  }}||j                  v s|||<   ||j                  |   |<   - n | j                  |_        |S )z9This subgraph method returns a full AntiGraph. Not a View)r   r!   r"   adjlist_inner_dict_factoryrg   rI   ru   )rd   r#   r&   rC   Gnbrsr}   rD   s          r;   r    z_AntiGraph.subgraph   s    E
L	 	'A002EAFF1I))A,,,. 'Q!&&=!"E#J%&AFF3KN'	' **r<   c                       e Zd Zd Zd Zy)_AntiGraph.AntiDegreeViewc              #      K   t        | j                        }| j                  D ]0  }|t        | j                  |         z
  |hz
  }|t        |      f 2 y wr@   )r   _succ_nodesr   )rd   	all_nodesrC   r~   s       r;   r{   z"_AntiGraph.AntiDegreeView.__iter__0  sR     DJJI[[ % 3tzz!}#55;#d)n$%s   AAc                     t        | j                        t        | j                  |         z
  |hz
  }t        |      ||v z   S r@   )r   r   r   )rd   rC   r~   s      r;   ri   z%_AntiGraph.AntiDegreeView.__getitem__6  s;    tzz?SA%771#=Dt9T	**r<   N)r   r   r   r{   ri   rA   r<   r;   AntiDegreeViewr   /  s    	%	+r<   r   c                 $    | j                  |       S )a  Returns an iterator for (node, degree) and degree for single node.

        The node degree is the number of edges adjacent to the node.

        Parameters
        ----------
        nbunch : iterable container, optional (default=all nodes)
            A container of nodes.  The container will be iterated
            through once.

        weight : string or None, optional (default=None)
           The edge attribute that holds the numerical value used
           as a weight.  If None, then each edge has weight 1.
           The degree is the sum of the edge weights adjacent to the node.

        Returns
        -------
        deg:
            Degree of the node, if a single node is passed as argument.
        nd_iter : an iterator
            The iterator returns two-tuples of (node, degree).

        See Also
        --------
        degree

        Examples
        --------
        >>> G = nx.path_graph(4)
        >>> G.degree(0)  # node 0 with degree 1
        1
        >>> list(G.degree([0, 1]))
        [(0, 1), (1, 2)]

        )r   rc   s    r;   rO   z_AntiGraph.degree;  s    J ""4((r<   c              #      K   | j                   D ]8  }|t        | j                         t        | j                   |         z
  |hz
  f : yw)a{  Returns an iterator of (node, adjacency set) tuples for all nodes
           in the dense graph.

        This is the fastest way to look at every edge.
        For directed graphs, only outgoing adjacencies are included.

        Returns
        -------
        adj_iter : iterator
           An iterator of (node, adjacency set) for all nodes in
           the graph.

        N)rg   r   )rd   rC   s     r;   	adjacencyz_AntiGraph.adjacencyb  sI       	@Ac$))ns499Q<'88A3>??	@s   A	AN)r   r   r   r   rb   re   edge_attr_dict_factoryri   rn   r   r   r   r   r   r    r   reportviews
DegreeViewr   rO   r   rA   r<   r;   r!   r!      s     qMM" .
&O   (@M @$ , ,
+22 
+ $) $)L@r<   r!   )gffffff?)r   )r   r   collectionsr   collections.abcr   	functoolsr   networkxr   !networkx.algorithms.approximationr   networkx.exceptionr   networkx.utilsr   __all___dispatchabler	   r%   rK   Graphr!   rA   r<   r;   <module>r      sx    2  # # %  E , .
 Z 12J 3 !JZ>l@ l@r<   