
    hV                        S r SSKJr  SSKrSSKJr  / SQrSS jr\" S5      \" S5      \R                  SS	 j5       5       5       r
\" S5      \" S5      \R                  SS
 j5       5       5       r\" S5      \" S5      \R                  SS j5       5       5       r\" S5      \" S5      \R                  SS j5       5       5       r\" S5      \" S5      \R                  SS j5       5       5       r\" S5      \" S5      \R                  " SS9SS j5       5       5       r\" S5      \" S5      \R                  " SS9SS j5       5       5       r\" S5      \" S5      \R                  " SS9SS j5       5       5       rS rg)z
Link prediction algorithms.
    )logN)not_implemented_for)resource_allocation_indexjaccard_coefficientadamic_adar_indexpreferential_attachmentcn_soundarajan_hopcroftra_index_soundarajan_hopcroftwithin_inter_clustercommon_neighbor_centralityc                    ^ Uc  [         R                  " U 5      nOIU HC  u  p4X0;  a  [         R                  " SU S35      eX@;  d  M+  [         R                  " SU S35      e   U4S jU 5       $ )a  Applies the given function to each edge in the specified iterable
of edges.

`G` is an instance of :class:`networkx.Graph`.

`func` is a function on two inputs, each of which is a node in the
graph. The function can return anything, but it should return a
value representing a prediction of the likelihood of a "link"
joining the two nodes.

`ebunch` is an iterable of pairs of nodes. If not specified, all
non-edges in the graph `G` will be used.

zNode z
 not in G.c              3   <   >#    U  H  u  pXT" X5      4v   M     g 7fN ).0uvfuncs      U/var/www/html/env/lib/python3.13/site-packages/networkx/algorithms/link_prediction.py	<genexpr>$_apply_prediction.<locals>.<genexpr>-   s     2641Q4:6s   )nx	non_edgesNodeNotFound)Gr   ebunchr   r   s    `   r   _apply_predictionr      sj     ~aDAzooaS
&;<<zooaS
&;<<	 
 3622    directed
multigraphc                 (   ^  U 4S jn[        T X!5      $ )am  Compute the resource allocation index of all node pairs in ebunch.

Resource allocation index of `u` and `v` is defined as

.. math::

    \sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{1}{|\Gamma(w)|}

where $\Gamma(u)$ denotes the set of neighbors of $u$.

Parameters
----------
G : graph
    A NetworkX undirected graph.

ebunch : iterable of node pairs, optional (default = None)
    Resource allocation index will be computed for each pair of
    nodes given in the iterable. The pairs must be given as
    2-tuples (u, v) where u and v are nodes in the graph. If ebunch
    is None then all nonexistent edges in the graph will be used.
    Default value: None.

Returns
-------
piter : iterator
    An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
    pair of nodes and p is their resource allocation index.

Raises
------
NetworkXNotImplemented
    If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.

NodeNotFound
    If `ebunch` has a node that is not in `G`.

Examples
--------
>>> G = nx.complete_graph(5)
>>> preds = nx.resource_allocation_index(G, [(0, 1), (2, 3)])
>>> for u, v, p in preds:
...     print(f"({u}, {v}) -> {p:.8f}")
(0, 1) -> 0.75000000
(2, 3) -> 0.75000000

References
----------
.. [1] T. Zhou, L. Lu, Y.-C. Zhang.
   Predicting missing links via local information.
   Eur. Phys. J. B 71 (2009) 623.
   https://arxiv.org/pdf/0901.0553.pdf
c                 X   > [        U4S j[        R                  " TX5       5       5      $ )Nc              3   L   >#    U  H  nS TR                  U5      -  v   M     g7f   Ndegreer   wr   s     r   r   =resource_allocation_index.<locals>.predict.<locals>.<genexpr>j   s     I,Hq1qxx{?,Hs   !$sumr   common_neighborsr   r   r   s     r   predict*resource_allocation_index.<locals>.predicti   s!    IB,?,?1,HIIIr   r   r   r   r/   s   `  r   r   r   0   s    rJ Q00r   c                 (   ^  U 4S jn[        T X!5      $ )aY  Compute the Jaccard coefficient of all node pairs in ebunch.

Jaccard coefficient of nodes `u` and `v` is defined as

.. math::

    \frac{|\Gamma(u) \cap \Gamma(v)|}{|\Gamma(u) \cup \Gamma(v)|}

where $\Gamma(u)$ denotes the set of neighbors of $u$.

Parameters
----------
G : graph
    A NetworkX undirected graph.

ebunch : iterable of node pairs, optional (default = None)
    Jaccard coefficient will be computed for each pair of nodes
    given in the iterable. The pairs must be given as 2-tuples
    (u, v) where u and v are nodes in the graph. If ebunch is None
    then all nonexistent edges in the graph will be used.
    Default value: None.

Returns
-------
piter : iterator
    An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
    pair of nodes and p is their Jaccard coefficient.

Raises
------
NetworkXNotImplemented
    If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.

NodeNotFound
    If `ebunch` has a node that is not in `G`.

Examples
--------
>>> G = nx.complete_graph(5)
>>> preds = nx.jaccard_coefficient(G, [(0, 1), (2, 3)])
>>> for u, v, p in preds:
...     print(f"({u}, {v}) -> {p:.8f}")
(0, 1) -> 0.60000000
(2, 3) -> 0.60000000

References
----------
.. [1] D. Liben-Nowell, J. Kleinberg.
       The Link Prediction Problem for Social Networks (2004).
       http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
c                    > [        [        TU    5      [        TU   5      -  5      nUS:X  a  g[        [        R                  " TX5      5      U-  $ Nr   )lensetr   r-   )r   r   
union_sizer   s      r   r/   $jaccard_coefficient.<locals>.predict   sI    QqTS1Y./
?2&&q!/0:==r   r1   r2   s   `  r   r   r   o   s    p> Q00r   c                 (   ^  U 4S jn[        T X!5      $ )a  Compute the Adamic-Adar index of all node pairs in ebunch.

Adamic-Adar index of `u` and `v` is defined as

.. math::

    \sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{1}{\log |\Gamma(w)|}

where $\Gamma(u)$ denotes the set of neighbors of $u$.
This index leads to zero-division for nodes only connected via self-loops.
It is intended to be used when no self-loops are present.

Parameters
----------
G : graph
    NetworkX undirected graph.

ebunch : iterable of node pairs, optional (default = None)
    Adamic-Adar index will be computed for each pair of nodes given
    in the iterable. The pairs must be given as 2-tuples (u, v)
    where u and v are nodes in the graph. If ebunch is None then all
    nonexistent edges in the graph will be used.
    Default value: None.

Returns
-------
piter : iterator
    An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
    pair of nodes and p is their Adamic-Adar index.

Raises
------
NetworkXNotImplemented
    If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.

NodeNotFound
    If `ebunch` has a node that is not in `G`.

Examples
--------
>>> G = nx.complete_graph(5)
>>> preds = nx.adamic_adar_index(G, [(0, 1), (2, 3)])
>>> for u, v, p in preds:
...     print(f"({u}, {v}) -> {p:.8f}")
(0, 1) -> 2.16404256
(2, 3) -> 2.16404256

References
----------
.. [1] D. Liben-Nowell, J. Kleinberg.
       The Link Prediction Problem for Social Networks (2004).
       http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
c                 X   > [        U4S j[        R                  " TX5       5       5      $ )Nc              3   ^   >#    U  H"  nS [        TR                  U5      5      -  v   M$     g7fr$   )r   r'   r(   s     r   r   5adamic_adar_index.<locals>.predict.<locals>.<genexpr>   s%     N1MA1s188A;''1Ms   *-r+   r.   s     r   r/   "adamic_adar_index.<locals>.predict   s!    N1D1DQ1MNNNr   r1   r2   s   `  r   r   r      s    tO Q00r   c                    ^ ^^^ TS:X  a  U 4S jnO3[        [        R                  " T 5      5      m[        S5      mU UUU4S jn[	        T X15      $ )a	  Return the CCPA score for each pair of nodes.

Compute the Common Neighbor and Centrality based Parameterized Algorithm(CCPA)
score of all node pairs in ebunch.

CCPA score of `u` and `v` is defined as

.. math::

    \alpha \cdot (|\Gamma (u){\cap }^{}\Gamma (v)|)+(1-\alpha )\cdot \frac{N}{{d}_{uv}}

where $\Gamma(u)$ denotes the set of neighbors of $u$, $\Gamma(v)$ denotes the
set of neighbors of $v$, $\alpha$ is  parameter varies between [0,1], $N$ denotes
total number of nodes in the Graph and ${d}_{uv}$ denotes shortest distance
between $u$ and $v$.

This algorithm is based on two vital properties of nodes, namely the number
of common neighbors and their centrality. Common neighbor refers to the common
nodes between two nodes. Centrality refers to the prestige that a node enjoys
in a network.

.. seealso::

    :func:`common_neighbors`

Parameters
----------
G : graph
    NetworkX undirected graph.

ebunch : iterable of node pairs, optional (default = None)
    Preferential attachment score will be computed for each pair of
    nodes given in the iterable. The pairs must be given as
    2-tuples (u, v) where u and v are nodes in the graph. If ebunch
    is None then all nonexistent edges in the graph will be used.
    Default value: None.

alpha : Parameter defined for participation of Common Neighbor
        and Centrality Algorithm share. Values for alpha should
        normally be between 0 and 1. Default value set to 0.8
        because author found better performance at 0.8 for all the
        dataset.
        Default value: 0.8


Returns
-------
piter : iterator
    An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
    pair of nodes and p is their Common Neighbor and Centrality based
    Parameterized Algorithm(CCPA) score.

Raises
------
NetworkXNotImplemented
    If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.

NetworkXAlgorithmError
    If self loops exist in `ebunch` or in `G` (if `ebunch` is `None`).

NodeNotFound
    If `ebunch` has a node that is not in `G`.

Examples
--------
>>> G = nx.complete_graph(5)
>>> preds = nx.common_neighbor_centrality(G, [(0, 1), (2, 3)])
>>> for u, v, p in preds:
...     print(f"({u}, {v}) -> {p}")
(0, 1) -> 3.4000000000000004
(2, 3) -> 3.4000000000000004

References
----------
.. [1] Ahmad, I., Akhtar, M.U., Noor, S. et al.
       Missing Link Prediction using Common Neighbor and Centrality based Parameterized Algorithm.
       Sci Rep 10, 364 (2020).
       https://doi.org/10.1038/s41598-019-57304-y
r%   c                 z   > X:X  a  [         R                  " S5      e[        [         R                  " TX5      5      $ )NSelf loops are not supported)r   NetworkXAlgorithmErrorr6   r-   r.   s     r   r/   +common_neighbor_centrality.<locals>.predictG  s2    v//0NOOr**1a344r   infc                    > X:X  a  [         R                  " S5      eTU    R                  UT5      n[        [         R                  " TX5      5      nTU-  ST-
  [        T5      -  U-  -   $ )NrA   r%   )r   rB   getr6   r-   )r   r   path_lenn_nbrsr   alpharD   spls       r   r/   rC   Q  sf    v//0NOO1vzz!S)H,,Q56F6>QY#a&$88$CCCr   )dictr   shortest_path_lengthfloatr   )r   r   rI   r/   rD   rJ   s   ` ` @@r   r   r      sM    j z	5 2**1-.El	D 	D Q00r   c                 (   ^  U 4S jn[        T X!5      $ )aC  Compute the preferential attachment score of all node pairs in ebunch.

Preferential attachment score of `u` and `v` is defined as

.. math::

    |\Gamma(u)| |\Gamma(v)|

where $\Gamma(u)$ denotes the set of neighbors of $u$.

Parameters
----------
G : graph
    NetworkX undirected graph.

ebunch : iterable of node pairs, optional (default = None)
    Preferential attachment score will be computed for each pair of
    nodes given in the iterable. The pairs must be given as
    2-tuples (u, v) where u and v are nodes in the graph. If ebunch
    is None then all nonexistent edges in the graph will be used.
    Default value: None.

Returns
-------
piter : iterator
    An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
    pair of nodes and p is their preferential attachment score.

Raises
------
NetworkXNotImplemented
    If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.

NodeNotFound
    If `ebunch` has a node that is not in `G`.

Examples
--------
>>> G = nx.complete_graph(5)
>>> preds = nx.preferential_attachment(G, [(0, 1), (2, 3)])
>>> for u, v, p in preds:
...     print(f"({u}, {v}) -> {p}")
(0, 1) -> 16
(2, 3) -> 16

References
----------
.. [1] D. Liben-Nowell, J. Kleinberg.
       The Link Prediction Problem for Social Networks (2004).
       http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
c                 J   > TR                  U 5      TR                  U5      -  $ r   r&   r.   s     r   r/   (preferential_attachment.<locals>.predict  s    xx{QXXa[((r   r1   r2   s   `  r   r   r   \  s    p) Q00r   	community)
node_attrsc                 ,   ^ ^ U U4S jn[        T X15      $ )a  Count the number of common neighbors of all node pairs in ebunch
    using community information.

For two nodes $u$ and $v$, this function computes the number of
common neighbors and bonus one for each common neighbor belonging to
the same community as $u$ and $v$. Mathematically,

.. math::

    |\Gamma(u) \cap \Gamma(v)| + \sum_{w \in \Gamma(u) \cap \Gamma(v)} f(w)

where $f(w)$ equals 1 if $w$ belongs to the same community as $u$
and $v$ or 0 otherwise and $\Gamma(u)$ denotes the set of
neighbors of $u$.

Parameters
----------
G : graph
    A NetworkX undirected graph.

ebunch : iterable of node pairs, optional (default = None)
    The score will be computed for each pair of nodes given in the
    iterable. The pairs must be given as 2-tuples (u, v) where u
    and v are nodes in the graph. If ebunch is None then all
    nonexistent edges in the graph will be used.
    Default value: None.

community : string, optional (default = 'community')
    Nodes attribute name containing the community information.
    G[u][community] identifies which community u belongs to. Each
    node belongs to at most one community. Default value: 'community'.

Returns
-------
piter : iterator
    An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
    pair of nodes and p is their score.

Raises
------
NetworkXNotImplemented
    If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.

NetworkXAlgorithmError
    If no community information is available for a node in `ebunch` or in `G` (if `ebunch` is `None`).

NodeNotFound
    If `ebunch` has a node that is not in `G`.

Examples
--------
>>> G = nx.path_graph(3)
>>> G.nodes[0]["community"] = 0
>>> G.nodes[1]["community"] = 0
>>> G.nodes[2]["community"] = 0
>>> preds = nx.cn_soundarajan_hopcroft(G, [(0, 2)])
>>> for u, v, p in preds:
...     print(f"({u}, {v}) -> {p}")
(0, 2) -> 2

References
----------
.. [1] Sucheta Soundarajan and John Hopcroft.
   Using community information to improve the precision of link
   prediction methods.
   In Proceedings of the 21st international conference companion on
   World Wide Web (WWW '12 Companion). ACM, New York, NY, USA, 607-608.
   http://doi.acm.org/10.1145/2187980.2188150
c                    >^ [        TU T5      m[        TUT5      n[        R                  " TX5      nTU:X  a  [        UUU4S jU 5       5      OSn[	        U5      U-   $ )Nc              3   D   >#    U  H  n[        TUT5      T:H  v   M     g 7fr   )
_communityr   r)   Cur   rQ   s     r   r   ;cn_soundarajan_hopcroft.<locals>.predict.<locals>.<genexpr>  s     B6a
1a+r16s    r   )rV   r   r-   r,   r6   )r   r   Cvcnbors	neighborsrX   r   rQ   s        @r   r/   (cn_soundarajan_hopcroft.<locals>.predict  s^    1i(1i($$Q-FHBhCB6BBTU 	 6{Y&&r   r1   r   r   rQ   r/   s   ` ` r   r	   r	     s    T' Q00r   c                 ,   ^ ^ U U4S jn[        T X15      $ )a  Compute the resource allocation index of all node pairs in
ebunch using community information.

For two nodes $u$ and $v$, this function computes the resource
allocation index considering only common neighbors belonging to the
same community as $u$ and $v$. Mathematically,

.. math::

    \sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{f(w)}{|\Gamma(w)|}

where $f(w)$ equals 1 if $w$ belongs to the same community as $u$
and $v$ or 0 otherwise and $\Gamma(u)$ denotes the set of
neighbors of $u$.

Parameters
----------
G : graph
    A NetworkX undirected graph.

ebunch : iterable of node pairs, optional (default = None)
    The score will be computed for each pair of nodes given in the
    iterable. The pairs must be given as 2-tuples (u, v) where u
    and v are nodes in the graph. If ebunch is None then all
    nonexistent edges in the graph will be used.
    Default value: None.

community : string, optional (default = 'community')
    Nodes attribute name containing the community information.
    G[u][community] identifies which community u belongs to. Each
    node belongs to at most one community. Default value: 'community'.

Returns
-------
piter : iterator
    An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
    pair of nodes and p is their score.

Raises
------
NetworkXNotImplemented
    If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.

NetworkXAlgorithmError
    If no community information is available for a node in `ebunch` or in `G` (if `ebunch` is `None`).

NodeNotFound
    If `ebunch` has a node that is not in `G`.

Examples
--------
>>> G = nx.Graph()
>>> G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
>>> G.nodes[0]["community"] = 0
>>> G.nodes[1]["community"] = 0
>>> G.nodes[2]["community"] = 1
>>> G.nodes[3]["community"] = 0
>>> preds = nx.ra_index_soundarajan_hopcroft(G, [(0, 3)])
>>> for u, v, p in preds:
...     print(f"({u}, {v}) -> {p:.8f}")
(0, 3) -> 0.50000000

References
----------
.. [1] Sucheta Soundarajan and John Hopcroft.
   Using community information to improve the precision of link
   prediction methods.
   In Proceedings of the 21st international conference companion on
   World Wide Web (WWW '12 Companion). ACM, New York, NY, USA, 607-608.
   http://doi.acm.org/10.1145/2187980.2188150
c                    >^ [        TU T5      m[        TUT5      nTU:w  a  g[        R                  " TX5      n[        UUU4S jU 5       5      $ )Nr   c              3   r   >#    U  H,  n[        TUT5      T:X  d  M  S TR                  U5      -  v   M.     g7fr$   )rV   r'   rW   s     r   r   Ara_index_soundarajan_hopcroft.<locals>.predict.<locals>.<genexpr>B  s0     XFqjAy6QUW6W?1qxx{?Fs   77)rV   r   r-   r,   )r   r   rZ   r[   rX   r   rQ   s       @r   r/   .ra_index_soundarajan_hopcroft.<locals>.predict<  sL    1i(1i(8$$Q-XFXXXr   r1   r^   s   ` ` r   r
   r
     s    XY Q00r   c                 h   ^ ^^ TS::  a  [         R                  " S5      eU UU4S jn[        T XA5      $ )a[
  Compute the ratio of within- and inter-cluster common neighbors
of all node pairs in ebunch.

For two nodes `u` and `v`, if a common neighbor `w` belongs to the
same community as them, `w` is considered as within-cluster common
neighbor of `u` and `v`. Otherwise, it is considered as
inter-cluster common neighbor of `u` and `v`. The ratio between the
size of the set of within- and inter-cluster common neighbors is
defined as the WIC measure. [1]_

Parameters
----------
G : graph
    A NetworkX undirected graph.

ebunch : iterable of node pairs, optional (default = None)
    The WIC measure will be computed for each pair of nodes given in
    the iterable. The pairs must be given as 2-tuples (u, v) where
    u and v are nodes in the graph. If ebunch is None then all
    nonexistent edges in the graph will be used.
    Default value: None.

delta : float, optional (default = 0.001)
    Value to prevent division by zero in case there is no
    inter-cluster common neighbor between two nodes. See [1]_ for
    details. Default value: 0.001.

community : string, optional (default = 'community')
    Nodes attribute name containing the community information.
    G[u][community] identifies which community u belongs to. Each
    node belongs to at most one community. Default value: 'community'.

Returns
-------
piter : iterator
    An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
    pair of nodes and p is their WIC measure.

Raises
------
NetworkXNotImplemented
    If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.

NetworkXAlgorithmError
    - If `delta` is less than or equal to zero.
    - If no community information is available for a node in `ebunch` or in `G` (if `ebunch` is `None`).

NodeNotFound
    If `ebunch` has a node that is not in `G`.

Examples
--------
>>> G = nx.Graph()
>>> G.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 4), (2, 4), (3, 4)])
>>> G.nodes[0]["community"] = 0
>>> G.nodes[1]["community"] = 1
>>> G.nodes[2]["community"] = 0
>>> G.nodes[3]["community"] = 0
>>> G.nodes[4]["community"] = 0
>>> preds = nx.within_inter_cluster(G, [(0, 4)])
>>> for u, v, p in preds:
...     print(f"({u}, {v}) -> {p:.8f}")
(0, 4) -> 1.99800200
>>> preds = nx.within_inter_cluster(G, [(0, 4)], delta=0.5)
>>> for u, v, p in preds:
...     print(f"({u}, {v}) -> {p:.8f}")
(0, 4) -> 1.33333333

References
----------
.. [1] Jorge Carlos Valverde-Rebaza and Alneu de Andrade Lopes.
   Link prediction in complex networks based on cluster information.
   In Proceedings of the 21st Brazilian conference on Advances in
   Artificial Intelligence (SBIA'12)
   https://doi.org/10.1007/978-3-642-34459-6_10
r   zDelta must be greater than zeroc                   > [        TU T	5      n[        TUT	5      nX#:w  a  g[        R                  " TX5      nU Vs1 s H  n[        TUT	5      U:X  d  M  UiM     nnXF-
  n[        U5      [        U5      T
-   -  $ s  snf r5   )rV   r   r-   r6   )r   r   rX   rZ   r[   r)   withininterr   rQ   deltas           r   r/   %within_inter_cluster.<locals>.predict  s    1i(1i(8$$Q-#IVz!Q	'Bb'H!VI6{c%j5011 Js   A<A<)r   rB   r   )r   r   rh   rQ   r/   s   ` `` r   r   r   G  s3    ` z''(IJJ2 Q00r   c                     U R                   U   n X2   $ ! [         a  n[        R                  " SU 35      UeSnAff = f)z$Get the community of the given node.z,No community information available for Node N)nodesKeyErrorr   rB   )r   r   rQ   node_uerrs        r   rV   rV     sM    WWQZF   '':1#>
	s    
>9>r   )Ng?)NrQ   )NgMbP?rQ   )__doc__mathr   networkxr   networkx.utilsr   __all__r   _dispatchabler   r   r   r   r   r	   r
   r   rV   r   r   r   <module>ru      s     .	34 Z \"91  # !91x Z \";1  # !;1| Z \":1  # !:1z Z \"f1  # !f1R Z \"81  # !81v Z \"[)P1 * # !P1f Z \"[)Q1 * # !Q1h Z \"[)Z1 * # !Z1zr   