o
    3ήc=                     @   s   d Z ddlZddlmZ ddlmZ g dZeddd Zd	d
 Z	dddZ
dddZdddZdddZdddZededdd Zededdd ZdS )u  
Find the k-cores of a graph.

The k-core is found by recursively pruning nodes with degrees less than k.

See the following references for details:

An O(m) Algorithm for Cores Decomposition of Networks
Vladimir Batagelj and Matjaz Zaversnik, 2003.
https://arxiv.org/abs/cs.DS/0310049

Generalized Cores
Vladimir Batagelj and Matjaz Zaversnik, 2002.
https://arxiv.org/pdf/cs/0202039

For directed graphs a more general notion is that of D-cores which
looks at (k, l) restrictions on (in, out) degree. The (k, k) D-core
is the k-core.

D-cores: Measuring Collaboration of Directed Graphs Based on Degeneracy
Christos Giatsidis, Dimitrios M. Thilikos, Michalis Vazirgiannis, ICDM 2011.
http://www.graphdegeneracy.org/dcores_ICDM_2011.pdf

Multi-scale structure and topological anomaly detection via a new network statistic: The onion decomposition
L. Hébert-Dufresne, J. A. Grochow, and A. Allard
Scientific Reports 6, 31708 (2016)
http://doi.org/10.1038/srep31708

    N)NetworkXError)not_implemented_for)core_number
find_coresk_corek_shellk_crustk_coronak_trussonion_layers
multigraphc                    sD  t  dkrd}t|t  }t||jd}dg}d}t|D ]\}}|| |kr=||g|| |   || }q#dd t|D }|}	 fdd D }
|D ]K}|
| D ]D}|	| |	| kr|
| 	| || }||	|  }|||< |||| < || || ||< ||< ||	|   d7  < |	|  d8  < qZqT|	S )a  Returns the core number for each vertex.

    A k-core is a maximal subgraph that contains nodes of degree k or more.

    The core number of a node is the largest value k of a k-core containing
    that node.

    Parameters
    ----------
    G : NetworkX graph
       A graph or directed graph

    Returns
    -------
    core_number : dictionary
       A dictionary keyed by node to the core number.

    Raises
    ------
    NetworkXError
        The k-core is not implemented for graphs with self loops
        or parallel edges.

    Notes
    -----
    Not implemented for graphs with parallel edges or self loops.

    For directed graphs the node degree is defined to be the
    in-degree + out-degree.

    References
    ----------
    .. [1] An O(m) Algorithm for Cores Decomposition of Networks
       Vladimir Batagelj and Matjaz Zaversnik, 2003.
       https://arxiv.org/abs/cs.DS/0310049
    r   zlInput graph has self loops which is not permitted; Consider using G.remove_edges_from(nx.selfloop_edges(G)).keyc                 S   s   i | ]\}}||qS  r   ).0posvr   r   ?/tmp/pip-target-vg8gfxp4/lib/python/networkx/algorithms/core.py
<dictcomp>d   s    zcore_number.<locals>.<dictcomp>c                       i | ]}|t t |qS r   listnxall_neighborsr   r   Gr   r   r   g          )
r   number_of_selfloopsr   dictdegreesortedget	enumerateextendremove)r   msgdegreesnodesbin_boundariescurr_degreeir   node_poscorenbrsur   	bin_startr   r   r   r   /   s<   &
r   c                 C   s&   dd l }d}|j|tdd t| S )Nr   z
find_cores is deprecated as of version 2.7 and will be removed in version 3.0.
The find_cores function is renamed core_number
   )
stacklevel)warningswarnDeprecationWarningr   r   )r   r4   r'   r   r   r   r   v   s
   
r   c                    sH    du rt |  du rt   fdd D }| | S )a  Returns the subgraph induced by nodes passing filter `k_filter`.

    Parameters
    ----------
    G : NetworkX graph
       The graph or directed graph to process
    k_filter : filter function
       This function filters the nodes chosen. It takes three inputs:
       A node of G, the filter's cutoff, and the core dict of the graph.
       The function should return a Boolean value.
    k : int, optional
      The order of the core. If not specified use the max core number.
      This value is used as the cutoff for the filter.
    core : dict, optional
      Precomputed core numbers keyed by node for the graph `G`.
      If not specified, the core numbers will be computed from `G`.

    Nc                 3   s     | ]}| r|V  qd S Nr   r   r.   kk_filterr   r   	<genexpr>       z!_core_subgraph.<locals>.<genexpr>)r   maxvaluessubgraphcopy)r   r:   r9   r.   r)   r   r8   r   _core_subgraph   s   rA   c                 C      dd }t | |||S )aJ  Returns the k-core of G.

    A k-core is a maximal subgraph that contains nodes of degree k or more.

    Parameters
    ----------
    G : NetworkX graph
      A graph or directed graph
    k : int, optional
      The order of the core.  If not specified return the main core.
    core_number : dictionary, optional
      Precomputed core numbers for the graph G.

    Returns
    -------
    G : NetworkX graph
      The k-core subgraph

    Raises
    ------
    NetworkXError
      The k-core is not defined for graphs with self loops or parallel edges.

    Notes
    -----
    The main core is the core with the largest degree.

    Not implemented for graphs with parallel edges or self loops.

    For directed graphs the node degree is defined to be the
    in-degree + out-degree.

    Graph, node, and edge attributes are copied to the subgraph.

    See Also
    --------
    core_number

    References
    ----------
    .. [1] An O(m) Algorithm for Cores Decomposition of Networks
       Vladimir Batagelj and Matjaz Zaversnik,  2003.
       https://arxiv.org/abs/cs.DS/0310049
    c                 S   s   ||  |kS r7   r   r   r9   cr   r   r   r:         zk_core.<locals>.k_filterrA   r   r9   r   r:   r   r   r   r      s   .r   c                 C   rB   )a7  Returns the k-shell of G.

    The k-shell is the subgraph induced by nodes with core number k.
    That is, nodes in the k-core that are not in the (k+1)-core.

    Parameters
    ----------
    G : NetworkX graph
      A graph or directed graph.
    k : int, optional
      The order of the shell. If not specified return the outer shell.
    core_number : dictionary, optional
      Precomputed core numbers for the graph G.


    Returns
    -------
    G : NetworkX graph
       The k-shell subgraph

    Raises
    ------
    NetworkXError
        The k-shell is not implemented for graphs with self loops
        or parallel edges.

    Notes
    -----
    This is similar to k_corona but in that case only neighbors in the
    k-core are considered.

    Not implemented for graphs with parallel edges or self loops.

    For directed graphs the node degree is defined to be the
    in-degree + out-degree.

    Graph, node, and edge attributes are copied to the subgraph.

    See Also
    --------
    core_number
    k_corona


    References
    ----------
    .. [1] A model of Internet topology using k-shell decomposition
       Shai Carmi, Shlomo Havlin, Scott Kirkpatrick, Yuval Shavitt,
       and Eran Shir, PNAS  July 3, 2007   vol. 104  no. 27  11150-11154
       http://www.pnas.org/content/104/27/11150.full
    c                 S   s   ||  |kS r7   r   rC   r   r   r   r:     rE   zk_shell.<locals>.k_filterrF   rG   r   r   r   r      s   5r   c                    sL    du r	t |  du rt  d  fdd D }| | S )ab  Returns the k-crust of G.

    The k-crust is the graph G with the edges of the k-core removed
    and isolated nodes found after the removal of edges are also removed.

    Parameters
    ----------
    G : NetworkX graph
       A graph or directed graph.
    k : int, optional
      The order of the shell.  If not specified return the main crust.
    core_number : dictionary, optional
      Precomputed core numbers for the graph G.

    Returns
    -------
    G : NetworkX graph
       The k-crust subgraph

    Raises
    ------
    NetworkXError
        The k-crust is not implemented for graphs with self loops
        or parallel edges.

    Notes
    -----
    This definition of k-crust is different than the definition in [1]_.
    The k-crust in [1]_ is equivalent to the k+1 crust of this algorithm.

    Not implemented for graphs with parallel edges or self loops.

    For directed graphs the node degree is defined to be the
    in-degree + out-degree.

    Graph, node, and edge attributes are copied to the subgraph.

    See Also
    --------
    core_number

    References
    ----------
    .. [1] A model of Internet topology using k-shell decomposition
       Shai Carmi, Shlomo Havlin, Scott Kirkpatrick, Yuval Shavitt,
       and Eran Shir, PNAS  July 3, 2007   vol. 104  no. 27  11150-11154
       http://www.pnas.org/content/104/27/11150.full
    Nr   c                 3   s     | ]} | kr|V  qd S r7   r   r   r   r9   r   r   r;   C  r<   zk_crust.<locals>.<genexpr>)r   r   r=   r>   r?   r@   )r   r9   r   r)   r   rH   r   r     s   3
r   c                    s    fdd}t  |||S )a  Returns the k-corona of G.

    The k-corona is the subgraph of nodes in the k-core which have
    exactly k neighbours in the k-core.

    Parameters
    ----------
    G : NetworkX graph
       A graph or directed graph
    k : int
       The order of the corona.
    core_number : dictionary, optional
       Precomputed core numbers for the graph G.

    Returns
    -------
    G : NetworkX graph
       The k-corona subgraph

    Raises
    ------
    NetworkXError
        The k-cornoa is not defined for graphs with self loops or
        parallel edges.

    Notes
    -----
    Not implemented for graphs with parallel edges or self loops.

    For directed graphs the node degree is defined to be the
    in-degree + out-degree.

    Graph, node, and edge attributes are copied to the subgraph.

    See Also
    --------
    core_number

    References
    ----------
    .. [1]  k -core (bootstrap) percolation on complex networks:
       Critical phenomena and nonlocal effects,
       A. V. Goltsev, S. N. Dorogovtsev, and J. F. F. Mendes,
       Phys. Rev. E 73, 056101 (2006)
       http://link.aps.org/doi/10.1103/PhysRevE.73.056101
    c                    s,    |  kot  fdd|  D kS )Nc                 3   s     | ]} | krd V  qdS )r   Nr   )r   wrD   r9   r   r   r;   x  r<   z)k_corona.<locals>.func.<locals>.<genexpr>)sumrC   r   rJ   r   funcw  s   ,zk_corona.<locals>.funcrF   )r   r9   r   rL   r   r   r   r	   G  s   0r	   directedc           	         s   |   }d}|dkr[d}g }t  |D ]0}t|| } |  fdd|D }|D ]}t|t|| @ |d k rB|||f q+q|| t|}|tt	| |dks
|S )at  Returns the k-truss of `G`.

    The k-truss is the maximal induced subgraph of `G` which contains at least
    three vertices where every edge is incident to at least `k-2` triangles.

    Parameters
    ----------
    G : NetworkX graph
      An undirected graph
    k : int
      The order of the truss

    Returns
    -------
    H : NetworkX graph
      The k-truss subgraph

    Raises
    ------
    NetworkXError

      The k-truss is not defined for graphs with self loops or parallel edges
      or directed graphs.

    Notes
    -----
    A k-clique is a (k-2)-truss and a k-truss is a (k+1)-core.

    Not implemented for digraphs or graphs with parallel edges or self loops.

    Graph, node, and edge attributes are copied to the subgraph.

    K-trusses were originally defined in [2] which states that the k-truss
    is the maximal induced subgraph where each edge belongs to at least
    `k-2` triangles. A more recent paper, [1], uses a slightly different
    definition requiring that each edge belong to at least `k` triangles.
    This implementation uses the original definition of `k-2` triangles.

    References
    ----------
    .. [1] Bounds and Algorithms for k-truss. Paul Burkhardt, Vance Faber,
       David G. Harris, 2018. https://arxiv.org/abs/1806.05523v2
    .. [2] Trusses: Cohesive Subgraphs for Social Network Analysis. Jonathan
       Cohen, 2005.
    r   r   c                    s   g | ]}| vr|qS r   r   r   seenr   r   
<listcomp>  s    zk_truss.<locals>.<listcomp>r2   )
r@   setaddlenappendremove_edges_fromremove_nodes_fromr   r   isolates)	r   r9   H	n_droppedto_dropr0   nbrs_unew_nbrsr   r   rN   r   r
   }  s(   0

r
   c                    s>  t  dkrd}t|i } fdd D }t  }d}d}dd t  D }t|dkrB|D ]}|||< || q4d}t|dkrt||j	d	}	||	d  }
|
|kr[|
}g }|	D ]}|| |kri n|
| q_|D ]!}|||< || D ]}|| | || d ||< q{|| qq|d }t|dksH|S )
ul  Returns the layer of each vertex in an onion decomposition of the graph.

    The onion decomposition refines the k-core decomposition by providing
    information on the internal organization of each k-shell. It is usually
    used alongside the `core numbers`.

    Parameters
    ----------
    G : NetworkX graph
        A simple graph without self loops or parallel edges

    Returns
    -------
    od_layers : dictionary
        A dictionary keyed by vertex to the onion layer. The layers are
        contiguous integers starting at 1.

    Raises
    ------
    NetworkXError
        The onion decomposition is not implemented for graphs with self loops
        or parallel edges or for directed graphs.

    Notes
    -----
    Not implemented for graphs with parallel edges or self loops.

    Not implemented for directed graphs.

    See Also
    --------
    core_number

    References
    ----------
    .. [1] Multi-scale structure and topological anomaly detection via a new
       network statistic: The onion decomposition
       L. Hébert-Dufresne, J. A. Grochow, and A. Allard
       Scientific Reports 6, 31708 (2016)
       http://doi.org/10.1038/srep31708
    .. [2] Percolation and the effective structure of complex networks
       A. Allard and L. Hébert-Dufresne
       Physical Review X 9, 011023 (2019)
       http://doi.org/10.1103/PhysRevX.9.011023
    r   zqInput graph contains self loops which is not permitted; Consider using G.remove_edges_from(nx.selfloop_edges(G)).c                    r   r   r   r   r   r   r   r     r   z onion_layers.<locals>.<dictcomp>r   c                 S   s   g | ]}|qS r   r   r   r   r   r   rP     s    z onion_layers.<locals>.<listcomp>r2   r   )r   r   r   r    r!   rW   rS   popr"   r#   rT   r&   )r   r'   	od_layers	neighborsr(   current_corecurrent_layerisolated_nodesr   r)   
min_degree
this_layernr   r   r   r     sD   0r   )NNr7   )__doc__networkxr   networkx.exceptionr   networkx.utilsr   __all__r   r   rA   r   r   r   r	   r
   r   r   r   r   r   <module>   s&    
F


4
;
;6C