
    h<                         S r SSKrSS/rS rS r\R                  " SS0SS	9      SS
 j5       r\R                  " SS0SS	9 SS j5       rg)zG
Functions for constructing matrix-like objects from graph attributes.
    Nattr_matrixattr_sparse_matrixc                 P   ^ ^ Tc  S nU$ [        T5      (       d	  U U4S jnU$ TnU$ )a  Returns a function that returns a value from G.nodes[u].

We return a function expecting a node as its sole argument. Then, in the
simplest scenario, the returned function will return G.nodes[u][node_attr].
However, we also handle the case when `node_attr` is None or when it is a
function itself.

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

node_attr : {None, str, callable}
    Specification of how the value of the node attribute should be obtained
    from the node attribute dictionary.

Returns
-------
value : function
    A function expecting a node as its sole argument. The function will
    returns a value from G.nodes[u] that depends on `edge_attr`.

c                     U $ N )us    L/var/www/html/env/lib/python3.13/site-packages/networkx/linalg/attrmatrix.pyvalue_node_value.<locals>.value$   s    H    c                 (   > TR                   U    T   $ r   )nodes)r	   G	node_attrs    r
   r   r   )   s    771:i((r   )callable)r   r   r   s   `` r
   _node_valuer   
   s<    0 	  L i  	) L Lr   c                 &  ^ ^ Tc#  T R                  5       (       a  U 4S jnU$ S n U$ [        T5      (       dV  TS:X  a(  T R                  5       (       a	  U U4S jnU$ U U4S jn U$ T R                  5       (       a	  U U4S jnU$ U U4S jn U$ TnU$ )ar  Returns a function that returns a value from G[u][v].

Suppose there exists an edge between u and v.  Then we return a function
expecting u and v as arguments.  For Graph and DiGraph, G[u][v] is
the edge attribute dictionary, and the function (essentially) returns
G[u][v][edge_attr].  However, we also handle cases when `edge_attr` is None
and when it is a function itself. For MultiGraph and MultiDiGraph, G[u][v]
is a dictionary of all edges between u and v.  In this case, the returned
function sums the value of `edge_attr` for every edge between u and v.

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

edge_attr : {None, str, callable}
    Specification of how the value of the edge attribute should be obtained
    from the edge attribute dictionary, G[u][v].  For multigraphs, G[u][v]
    is a dictionary of all the edges between u and v.  This allows for
    special treatment of multiedges.

Returns
-------
value : function
    A function expecting two nodes as parameters. The nodes should
    represent the from- and to- node of an edge. The function will
    return a value from G[u][v] that depends on `edge_attr`.

c                 &   > [        TU    U   5      $ r   )len)r	   vr   s     r
   r   _edge_value.<locals>.value[   s    1Q47|#r   c                     gN   r   )r	   r   s     r
   r   r   `   s    r   weightc                 V   > [        U4S jTU    U   R                  5        5       5      $ )Nc              3   F   >#    U  H  oR                  TS 5      v   M     g7f)r   Nget.0d	edge_attrs     r
   	<genexpr>-_edge_value.<locals>.value.<locals>.<genexpr>k   s     M<LquuY22<Ls   !sumvaluesr	   r   r   r$   s     r
   r   r   j   s#    MAaDGNN<LMMMr   c                 4   > TU    U   R                  TS5      $ r   r   r*   s     r
   r   r   o   s    Q47;;y!44r   c                 V   > [        U4S jTU    U   R                  5        5       5      $ )Nc              3   ,   >#    U  H	  oT   v   M     g 7fr   r   r!   s     r
   r%   r&   w   s     F5E|5Es   r'   r*   s     r
   r   r   v   s#    FQqT!W^^5EFFFr   c                    > TU    U   T   $ r   r   r*   s     r
   r   r   {   s    Q479--r   )is_multigraphr   )r   r$   r   s   `` r
   _edge_valuer0   7   s    >  ??$h L_^ LY i      NJ LA5@ L7   G2 L).( L Lr   r$   r   )
edge_attrs
node_attrsc           	         SSK n[        X5      n[        X5      n	Uc"  [        U  V
s1 s H
  o" U
5      iM     sn
5      nOUn[	        U5      nU R                  5       (       + n[        [        U[        U5      5      5      nUR                  X4XVS9n[        5       nU R                  5        Hp  u  nnU HJ  nX" U5         X" U5         nnUU;  d  M  UUU4==   U" UU5      -  ss'   U(       d  M>  UUU4   UUU4'   ML     U(       d  M_  UR                  U5        Mr     U(       a"  XR                  SS9R                  US45      -  nUc  X4$ U$ s  sn
f )aq  Returns the attribute matrix using attributes from `G` as a numpy array.

If only `G` is passed in, then the adjacency matrix is constructed.

Let A be a discrete set of values for the node attribute `node_attr`. Then
the elements of A represent the rows and columns of the constructed matrix.
Now, iterate through every edge e=(u,v) in `G` and consider the value
of the edge attribute `edge_attr`.  If ua and va are the values of the
node attribute `node_attr` for u and v, respectively, then the value of
the edge attribute is added to the matrix element at (ua, va).

Parameters
----------
G : graph
    The NetworkX graph used to construct the attribute matrix.

edge_attr : str, optional
    Each element of the matrix represents a running total of the
    specified edge attribute for edges whose node attributes correspond
    to the rows/cols of the matrix. The attribute must be present for
    all edges in the graph. If no attribute is specified, then we
    just count the number of edges whose node attributes correspond
    to the matrix element.

node_attr : str, optional
    Each row and column in the matrix represents a particular value
    of the node attribute.  The attribute must be present for all nodes
    in the graph. Note, the values of this attribute should be reliably
    hashable. So, float values are not recommended. If no attribute is
    specified, then the rows and columns will be the nodes of the graph.

normalized : bool, optional
    If True, then each row is normalized by the summation of its values.

rc_order : list, optional
    A list of the node attribute values. This list specifies the ordering
    of rows and columns of the array. If no ordering is provided, then
    the ordering will be random (and also, a return value).

Other Parameters
----------------
dtype : NumPy data-type, optional
    A valid NumPy dtype used to initialize the array. Keep in mind certain
    dtypes can yield unexpected results if the array is to be normalized.
    The parameter is passed to numpy.zeros(). If unspecified, the NumPy
    default is used.

order : {'C', 'F'}, optional
    Whether to store multidimensional data in C- or Fortran-contiguous
    (row- or column-wise) order in memory. This parameter is passed to
    numpy.zeros(). If unspecified, the NumPy default is used.

Returns
-------
M : 2D NumPy ndarray
    The attribute matrix.

ordering : list
    If `rc_order` was specified, then only the attribute matrix is returned.
    However, if `rc_order` was None, then the ordering used to construct
    the matrix is returned as well.

Examples
--------
Construct an adjacency matrix:

>>> G = nx.Graph()
>>> G.add_edge(0, 1, thickness=1, weight=3)
>>> G.add_edge(0, 2, thickness=2)
>>> G.add_edge(1, 2, thickness=3)
>>> nx.attr_matrix(G, rc_order=[0, 1, 2])
array([[0., 1., 1.],
       [1., 0., 1.],
       [1., 1., 0.]])

Alternatively, we can obtain the matrix describing edge thickness.

>>> nx.attr_matrix(G, edge_attr="thickness", rc_order=[0, 1, 2])
array([[0., 1., 2.],
       [1., 0., 3.],
       [2., 3., 0.]])

We can also color the nodes and ask for the probability distribution over
all edges (u,v) describing:

    Pr(v has color Y | u has color X)

>>> G.nodes[0]["color"] = "red"
>>> G.nodes[1]["color"] = "red"
>>> G.nodes[2]["color"] = "blue"
>>> rc = ["red", "blue"]
>>> nx.attr_matrix(G, node_attr="color", normalized=True, rc_order=rc)
array([[0.33333333, 0.66666667],
       [1.        , 0.        ]])

For example, the above tells us that for all edges (u,v):

    Pr( v is red  | u is red)  = 1/3
    Pr( v is blue | u is red)  = 2/3

    Pr( v is red  | u is blue) = 1
    Pr( v is blue | u is blue) = 0

Finally, we can obtain the total weights listed by the node colors.

>>> nx.attr_matrix(G, edge_attr="weight", node_attr="color", rc_order=rc)
array([[3., 2.],
       [2., 0.]])

Thus, the total weight over all edges (u,v) with u and v having colors:

    (red, red)   is 3   # the sole contribution is from edge (0,1)
    (red, blue)  is 2   # contributions from edges (0,2) and (1,2)
    (blue, red)  is 2   # same as (red, blue) since graph is undirected
    (blue, blue) is 0   # there are no edges with blue endpoints

r   N)dtypeorderr   axis)numpyr0   r   listr   is_directeddictziprangezerosset	adjacencyaddr(   reshape)r   r$   r   
normalizedrc_orderr4   r5   np
edge_value
node_valuenorderingN
undirectedindexMseenr	   nbrdictr   ijs                         r
   r   r      sN   ~ Q*JQ*J21A23HA]]_$JXuQx()E
!u2A5Dkkm
7AA'z!})=qA}!Q$:a++:1gAadG  :HHQK $ 	UUU]""Aq6**{9 3s   Ec           	         SSK nSSKn[        X5      n[        X5      n	Uc"  [	        U  V
s1 s H
  o" U
5      iM     sn
5      nOUn[        U5      nU R                  5       (       + n[        [        U[        U5      5      5      nUR                  R                  X4US9n[        5       nU R                  5        Hp  u  nnU HJ  nX" U5         X" U5         nnUU;  d  M  UUU4==   U" UU5      -  ss'   U(       d  M>  UUU4   UUU4'   ML     U(       d  M_  UR                  U5        Mr     U(       a&  USUR                  SS9SS2UR                   4   -  -  nUc  X4$ U$ s  sn
f )a  Returns a SciPy sparse array using attributes from G.

If only `G` is passed in, then the adjacency matrix is constructed.

Let A be a discrete set of values for the node attribute `node_attr`. Then
the elements of A represent the rows and columns of the constructed matrix.
Now, iterate through every edge e=(u,v) in `G` and consider the value
of the edge attribute `edge_attr`.  If ua and va are the values of the
node attribute `node_attr` for u and v, respectively, then the value of
the edge attribute is added to the matrix element at (ua, va).

Parameters
----------
G : graph
    The NetworkX graph used to construct the NumPy matrix.

edge_attr : str, optional
    Each element of the matrix represents a running total of the
    specified edge attribute for edges whose node attributes correspond
    to the rows/cols of the matrix. The attribute must be present for
    all edges in the graph. If no attribute is specified, then we
    just count the number of edges whose node attributes correspond
    to the matrix element.

node_attr : str, optional
    Each row and column in the matrix represents a particular value
    of the node attribute.  The attribute must be present for all nodes
    in the graph. Note, the values of this attribute should be reliably
    hashable. So, float values are not recommended. If no attribute is
    specified, then the rows and columns will be the nodes of the graph.

normalized : bool, optional
    If True, then each row is normalized by the summation of its values.

rc_order : list, optional
    A list of the node attribute values. This list specifies the ordering
    of rows and columns of the array. If no ordering is provided, then
    the ordering will be random (and also, a return value).

Other Parameters
----------------
dtype : NumPy data-type, optional
    A valid NumPy dtype used to initialize the array. Keep in mind certain
    dtypes can yield unexpected results if the array is to be normalized.
    The parameter is passed to numpy.zeros(). If unspecified, the NumPy
    default is used.

Returns
-------
M : SciPy sparse array
    The attribute matrix.

ordering : list
    If `rc_order` was specified, then only the matrix is returned.
    However, if `rc_order` was None, then the ordering used to construct
    the matrix is returned as well.

Examples
--------
Construct an adjacency matrix:

>>> G = nx.Graph()
>>> G.add_edge(0, 1, thickness=1, weight=3)
>>> G.add_edge(0, 2, thickness=2)
>>> G.add_edge(1, 2, thickness=3)
>>> M = nx.attr_sparse_matrix(G, rc_order=[0, 1, 2])
>>> M.toarray()
array([[0., 1., 1.],
       [1., 0., 1.],
       [1., 1., 0.]])

Alternatively, we can obtain the matrix describing edge thickness.

>>> M = nx.attr_sparse_matrix(G, edge_attr="thickness", rc_order=[0, 1, 2])
>>> M.toarray()
array([[0., 1., 2.],
       [1., 0., 3.],
       [2., 3., 0.]])

We can also color the nodes and ask for the probability distribution over
all edges (u,v) describing:

    Pr(v has color Y | u has color X)

>>> G.nodes[0]["color"] = "red"
>>> G.nodes[1]["color"] = "red"
>>> G.nodes[2]["color"] = "blue"
>>> rc = ["red", "blue"]
>>> M = nx.attr_sparse_matrix(G, node_attr="color", normalized=True, rc_order=rc)
>>> M.toarray()
array([[0.33333333, 0.66666667],
       [1.        , 0.        ]])

For example, the above tells us that for all edges (u,v):

    Pr( v is red  | u is red)  = 1/3
    Pr( v is blue | u is red)  = 2/3

    Pr( v is red  | u is blue) = 1
    Pr( v is blue | u is blue) = 0

Finally, we can obtain the total weights listed by the node colors.

>>> M = nx.attr_sparse_matrix(G, edge_attr="weight", node_attr="color", rc_order=rc)
>>> M.toarray()
array([[3., 2.],
       [2., 0.]])

Thus, the total weight over all edges (u,v) with u and v having colors:

    (red, red)   is 3   # the sole contribution is from edge (0,1)
    (red, blue)  is 2   # contributions from edges (0,2) and (1,2)
    (blue, red)  is 2   # same as (red, blue) since graph is undirected
    (blue, blue) is 0   # there are no edges with blue endpoints

r   N)r4   r   r6   )r8   scipyr0   r   r9   r   r:   r;   r<   r=   sparse	lil_arrayr?   r@   rA   r(   newaxis)r   r$   r   rC   rD   r4   rE   sprF   rG   rH   rI   rJ   rK   rL   rM   rN   r	   rO   r   rP   rQ   s                         r
   r   r   6  s]   p Q*JQ*J21A23HA]]_$JXuQx()E
		QF%0A5Dkkm
7AA'z!})=qA}!Q$:a++:1gAadG  :HHQK $ 	QAq"**}---{9 3s   E")NNFNNN)NNFNN)	__doc__networkxnx__all__r   r0   _dispatchabler   r   r   r   r
   <module>r]      s    .
/*ZXv k40[I 

` J`F k40[INRZ JZr   