
    hG                        S r SSKrSSKJr  SSKrSSKJr  / SQr\R                  " SS9SSS\
SS4S	 j5       r\R                  " SS
S9SS j5       r\R                  " S
S9     SS j5       r\R                  " SS
S9     SS j5       r\R                  " SS9SS j5       rS rS rS rS rS r\R                  " SS
S9 SS j5       r\R                  " SS9SSS\
SS4S j5       r\R                  " SS
S9 SSS.S jj5       rg)a  Functions to convert NetworkX graphs to and from common data containers
like numpy arrays, scipy sparse arrays, and pandas DataFrames.

The preferred way of converting data to a NetworkX graph is through the
graph constructor.  The constructor calls the `~networkx.convert.to_networkx_graph`
function which attempts to guess the input type and convert it automatically.

Examples
--------
Create a 10 node random graph from a numpy array

>>> import numpy as np
>>> rng = np.random.default_rng()
>>> a = rng.integers(low=0, high=2, size=(10, 10))
>>> DG = nx.from_numpy_array(a, create_using=nx.DiGraph)

or equivalently:

>>> DG = nx.DiGraph(a)

which calls `from_numpy_array` internally based on the type of ``a``.

See Also
--------
nx_agraph, nx_pydot
    N)defaultdict)not_implemented_for)from_pandas_adjacencyto_pandas_adjacencyfrom_pandas_edgelistto_pandas_edgelistfrom_scipy_sparse_arrayto_scipy_sparse_arrayfrom_numpy_arrayto_numpy_arrayweight)
edge_attrsg        c           
      d    SSK n[        U UUUUUUS9nUc  [        U 5      nUR                  XUS9$ )a	  Returns the graph adjacency matrix as a Pandas DataFrame.

Parameters
----------
G : graph
    The NetworkX graph used to construct the Pandas DataFrame.

nodelist : list, optional
   The rows and columns are ordered according to the nodes in `nodelist`.
   If `nodelist` is None, then the ordering is produced by G.nodes().

multigraph_weight : {sum, min, max}, optional
    An operator that determines how weights in multigraphs are handled.
    The default is to sum the weights of the multiple edges.

weight : string or None, optional
    The edge attribute that holds the numerical value used for
    the edge weight.  If an edge does not have that attribute, then the
    value 1 is used instead.

nonedge : float, optional
    The matrix values corresponding to nonedges are typically set to zero.
    However, this could be undesirable if there are matrix values
    corresponding to actual edges that also have the value zero. If so,
    one might prefer nonedges to have some other value, such as nan.

Returns
-------
df : Pandas DataFrame
   Graph adjacency matrix

Notes
-----
For directed graphs, entry i,j corresponds to an edge from i to j.

The DataFrame entries are assigned to the weight edge attribute. When
an edge does not have a weight attribute, the value of the entry is set to
the number 1.  For multiple (parallel) edges, the values of the entries
are determined by the 'multigraph_weight' parameter.  The default is to
sum the weight attributes for each of the parallel edges.

When `nodelist` does not contain every node in `G`, the matrix is built
from the subgraph of `G` that is induced by the nodes in `nodelist`.

The convention used for self-loop edges in graphs is to assign the
diagonal matrix entry value to the weight attribute of the edge
(or the number 1 if the edge has no weight attribute).  If the
alternate convention of doubling the edge weight is desired the
resulting Pandas DataFrame can be modified as follows::

    >>> import pandas as pd
    >>> G = nx.Graph([(1, 1), (2, 2)])
    >>> df = nx.to_pandas_adjacency(G)
    >>> df
         1    2
    1  1.0  0.0
    2  0.0  1.0
    >>> diag_idx = list(range(len(df)))
    >>> df.iloc[diag_idx, diag_idx] *= 2
    >>> df
         1    2
    1  2.0  0.0
    2  0.0  2.0

Examples
--------
>>> G = nx.MultiDiGraph()
>>> G.add_edge(0, 1, weight=2)
0
>>> G.add_edge(1, 0)
0
>>> G.add_edge(2, 2, weight=3)
0
>>> G.add_edge(2, 2)
1
>>> nx.to_pandas_adjacency(G, nodelist=[0, 1, 2], dtype=int)
   0  1  2
0  0  2  0
1  1  0  0
2  0  0  4

r   N)nodelistdtypeordermultigraph_weightr   nonedge)dataindexcolumns)pandasr   list	DataFrame)	Gr   r   r   r   r   r   pdMs	            I/var/www/html/env/lib/python3.13/site-packages/networkx/convert_matrix.pyr   r   .   sK    x 	+	A 7<<Q<AA    T)graphsreturns_graphc                 B    X R                      n U R                  n[        XQU R
                  S9nU$ ! [         ab  n[        [        U R                   5      R	                  [        U R
                  5      5      5      nU S3n[        R                  " SU5      UeSnAff = f)a  Returns a graph from Pandas DataFrame.

The Pandas DataFrame is interpreted as an adjacency matrix for the graph.

Parameters
----------
df : Pandas DataFrame
  An adjacency matrix representation of a graph

create_using : NetworkX graph constructor, optional (default=nx.Graph)
   Graph type to create. If graph instance, then cleared before populated.

Notes
-----
For directed graphs, explicitly mention create_using=nx.DiGraph,
and entry i,j of df corresponds to an edge from i to j.

If `df` has a single data type for each entry it will be converted to an
appropriate Python data type.

If you have node attributes stored in a separate dataframe `df_nodes`,
you can load those attributes to the graph `G` using the following code:

```
df_nodes = pd.DataFrame({"node_id": [1, 2, 3], "attribute1": ["A", "B", "C"]})
G.add_nodes_from((n, dict(d)) for n, d in df_nodes.iterrows())
```

If `df` has a user-specified compound data type the names
of the data fields will be used as attribute keys in the resulting
NetworkX graph.

See Also
--------
to_pandas_adjacency

Examples
--------
Simple integer weights on edges:

>>> import pandas as pd
>>> pd.options.display.max_columns = 20
>>> df = pd.DataFrame([[1, 1], [2, 1]])
>>> df
   0  1
0  1  1
1  2  1
>>> G = nx.from_pandas_adjacency(df)
>>> G.name = "Graph from pandas adjacency matrix"
>>> print(G)
Graph named 'Graph from pandas adjacency matrix' with 2 nodes and 3 edges
z not in columnszColumns must match Indices.N)create_usingr   )
r   	Exceptionr   set
differencer   nxNetworkXErrorvaluesr   )dfr#   errmissingmsgAr   s          r   r   r      s    nL\ 			A

KAH  Ls288}//BJJ@A	)<cBKLs   2 
BABB)preserve_edge_attrsc                 B   SSK nUc  U R                  SS9nOU R                  USS9nU VV	s/ s H  u  n  oPM
     n
nn	U V	Vs/ s H  u  poPM	     nn	n[        5       R                  " S U 5       6 nX;   a  [        R
                  " SU< S35      eX-;   a  [        R
                  " SU< S35      e[        S	5      nU VV	Vs0 s H+  oU V	Vs/ s H  u    n	nUR                  X5      PM     snn	_M-     nn	nnU R                  5       (       aN  UbK  X];   a  [        R
                  " S
U< S35      eU R                  SS9 V	Vs/ s H  u    pUPM
     nn	nXX,UU0nOXX,0nUR                  U5        UR                  UUS9$ s  sn	nf s  snn	f s  snn	f s  snn	nf s  snn	f )a  Returns the graph edge list as a Pandas DataFrame.

Parameters
----------
G : graph
    The NetworkX graph used to construct the Pandas DataFrame.

source : str or int, optional
    A valid column name (string or integer) for the source nodes (for the
    directed case).

target : str or int, optional
    A valid column name (string or integer) for the target nodes (for the
    directed case).

nodelist : list, optional
   Use only nodes specified in nodelist

dtype : dtype, default None
    Use to create the DataFrame. Data type to force.
    Only a single dtype is allowed. If None, infer.

edge_key : str or int or None, optional (default=None)
    A valid column name (string or integer) for the edge keys (for the
    multigraph case). If None, edge keys are not stored in the DataFrame.

Returns
-------
df : Pandas DataFrame
   Graph edge list

Examples
--------
>>> G = nx.Graph(
...     [
...         ("A", "B", {"cost": 1, "weight": 7}),
...         ("C", "E", {"cost": 9, "weight": 10}),
...     ]
... )
>>> df = nx.to_pandas_edgelist(G, nodelist=["A", "C"])
>>> df[["source", "target", "cost", "weight"]]
  source target  cost  weight
0      A      B     1       7
1      C      E     9      10

>>> G = nx.MultiGraph([("A", "B", {"cost": 1}), ("A", "B", {"cost": 9})])
>>> df = nx.to_pandas_edgelist(G, nodelist=["A", "C"], edge_key="ekey")
>>> df[["source", "target", "cost", "ekey"]]
  source target  cost  ekey
0      A      B     1     0
1      A      B     9     1

r   NTr   c              3   H   #    U  H  u    pUR                  5       v   M     g 7fNkeys).0_ds      r   	<genexpr>%to_pandas_edgelist.<locals>.<genexpr>%  s     ?h71aaffhhhs    "zSource name z is an edge attr namezTarget name nanzEdge key name r4   )r   )r   edgesr%   unionr'   r(   floatgetis_multigraphupdater   )r   sourcetargetr   r   edge_keyr   edgelistsr7   source_nodesttarget_nodes	all_attrsr;   kr8   	edge_attr	edge_keysedgelistdicts                       r   r   r      s   | 777%778$7/%-.X'!QAXL.%-.X'!AXL.?h?@IfZ7LMNNfZ7LMNN
,CENOY(;(wq!QQUU1](;;YIOX1 ""^H<?T#UVV&'gg4g&89&871aQ&8	9fHiXfC	"<<E<22+ /. <O
 :s)   FFFF.FFFc                 <   [         R                  " SU5      nUcj  UR                  5       (       a4  Ub1  [        X   X   X   5       H  u  pxn	UR	                  XxU	5        M     U$ UR                  [        X   X   5      5        U$ X/n
UR                  5       (       a  Ub  U
R                  U5        / n/ nUSL a$  U R                   Vs/ s H  oU
;  d  M
  UPM     nnO"[        U[        [        -  5      (       a  UnOU/n[        U5      S:X  a  [         R                  " SU 35      e [        U Vs/ s H  oU   PM	     sn6 nUR                  5       (       a  Ub   X   n[        UU5      n[        X   X   U5       HW  u  nnnUb  Uu  nnUR	                  UUUS9nOUR	                  UU5      nUU   U   U   R                  [        UU5      5        MY     U$ [        X   X   U5       H:  u  nnnUR	                  UU5        UU   U   R                  [        UU5      5        M<     U$ s  snf s  snf ! [        [        4 a!  nSU 3n[         R                  " U5      UeSnAff = f! [        [        4 a!  nSU 3n[         R                  " U5      UeSnAff = f)a  Returns a graph from Pandas DataFrame containing an edge list.

The Pandas DataFrame should contain at least two columns of node names and
zero or more columns of edge attributes. Each row will be processed as one
edge instance.

Note: This function iterates over DataFrame.values, which is not
guaranteed to retain the data type across columns in the row. This is only
a problem if your row is entirely numeric and a mix of ints and floats. In
that case, all values will be returned as floats. See the
DataFrame.iterrows documentation for an example.

Parameters
----------
df : Pandas DataFrame
    An edge list representation of a graph

source : str or int
    A valid column name (string or integer) for the source nodes (for the
    directed case).

target : str or int
    A valid column name (string or integer) for the target nodes (for the
    directed case).

edge_attr : str or int, iterable, True, or None
    A valid column name (str or int) or iterable of column names that are
    used to retrieve items and add them to the graph as edge attributes.
    If `True`, all columns will be added except `source`, `target` and `edge_key`.
    If `None`, no edge attributes are added to the graph.

create_using : NetworkX graph constructor, optional (default=nx.Graph)
    Graph type to create. If graph instance, then cleared before populated.

edge_key : str or None, optional (default=None)
    A valid column name for the edge keys (for a MultiGraph). The values in
    this column are used for the edge keys when adding edges if create_using
    is a multigraph.

If you have node attributes stored in a separate dataframe `df_nodes`,
you can load those attributes to the graph `G` using the following code:

```
df_nodes = pd.DataFrame({"node_id": [1, 2, 3], "attribute1": ["A", "B", "C"]})
G.add_nodes_from((n, dict(d)) for n, d in df_nodes.iterrows())
```

See Also
--------
to_pandas_edgelist

Examples
--------
Simple integer weights on edges:

>>> import pandas as pd
>>> pd.options.display.max_columns = 20
>>> import numpy as np
>>> rng = np.random.RandomState(seed=5)
>>> ints = rng.randint(1, 11, size=(3, 2))
>>> a = ["A", "B", "C"]
>>> b = ["D", "A", "E"]
>>> df = pd.DataFrame(ints, columns=["weight", "cost"])
>>> df[0] = a
>>> df["b"] = b
>>> df[["weight", "cost", 0, "b"]]
   weight  cost  0  b
0       4     7  A  D
1       7     1  B  A
2      10     9  C  E
>>> G = nx.from_pandas_edgelist(df, 0, "b", ["weight", "cost"])
>>> G["E"]["C"]["weight"]
10
>>> G["E"]["C"]["cost"]
9
>>> edges = pd.DataFrame(
...     {
...         "source": [0, 1, 2],
...         "target": [2, 2, 3],
...         "weight": [3, 4, 5],
...         "color": ["red", "blue", "blue"],
...     }
... )
>>> G = nx.from_pandas_edgelist(edges, edge_attr=True)
>>> G[0][2]["color"]
'red'

Build multigraph with custom keys:

>>> edges = pd.DataFrame(
...     {
...         "source": [0, 1, 2, 0],
...         "target": [2, 2, 3, 2],
...         "my_edge_key": ["A", "B", "C", "D"],
...         "weight": [3, 4, 5, 6],
...         "color": ["red", "blue", "blue", "blue"],
...     }
... )
>>> G = nx.from_pandas_edgelist(
...     edges,
...     edge_key="my_edge_key",
...     edge_attr=["weight", "color"],
...     create_using=nx.MultiGraph(),
... )
>>> G[0][2]
AtlasView({'A': {'weight': 3, 'color': 'red'}, 'D': {'weight': 6, 'color': 'blue'}})


r   NTz8Invalid edge_attr argument: No columns found with name: zInvalid edge_attr argument: zInvalid edge_key argument: )key)r'   empty_graphr@   zipadd_edgeadd_edges_fromappendr   
isinstancer   tuplelenr(   KeyError	TypeErrorrA   )r*   rB   rC   rL   r#   rD   guvrK   reserved_columnsattr_col_headingsattribute_dataccolr+   r-   multigraph_edge_keysrF   rH   attrsmultigraph_edge_keyrP   s                          r   r   r   :  s   l 	q,'A??!5rz2:r|Da

1# E  SRZ89'X1) ND(*

P
1?O6OQ
P	Ite|	,	,%&K
"FGXFYZ
 	
-2CD2C3#w2CDE
 	5')|$!$^5I!J
 rz2:~FKAq%#-2**jjA+>j?jjA&aDGCL$5u => G H	 rz2:~FKAq%JJq!aDGNN30%89 G HO Q Ei  -,YK8s#,- i( 53H:>&&s+45sN   	H,H,)	H6 2H1 H6 I* 1H6 6I'I""I'*J:JJc                 f  ^ SSK n[        U 5      S:X  a  [        R                  " S5      eUc  [	        U 5      n[        U 5      nO[        U5      nUS:X  a  [        R                  " S5      e[        U R                  U5      5      nU[        U5      :w  a>  U H"  nX;  d  M
  [        R                  " SU S35      e   [        R                  " S5      eU[        U 5      :  a  U R                  U5      n [        [        U[        U5      5      5      m[        U4S jU R                  US	S
9 5       6 n	 U	u  pnU R                  5       (       a   UR                  R                  XU44Xf4US9nOtX-   nX-   nX-   n[	        [        R                   " XS	S
95      nU(       a$  [        U4S jU 5       6 u  nnUU-  nUU-  nUU-  nUR                  R                  XU44Xf4US9n UR#                  U5      $ ! [         a    / / / pn
 Nf = f! [         a  n[        R                  " SU 35      UeSnAff = f)az  Returns the graph adjacency matrix as a SciPy sparse array.

Parameters
----------
G : graph
    The NetworkX graph used to construct the sparse array.

nodelist : list, optional
   The rows and columns are ordered according to the nodes in `nodelist`.
   If `nodelist` is None, then the ordering is produced by ``G.nodes()``.

dtype : NumPy data-type, optional
    A valid NumPy dtype used to initialize the array. If None, then the
    NumPy default is used.

weight : string or None, optional (default='weight')
    The edge attribute that holds the numerical value used for
    the edge weight.  If None then all edge weights are 1.

format : str in {'bsr', 'csr', 'csc', 'coo', 'lil', 'dia', 'dok'}
    The format of the sparse array to be returned (default 'csr').  For
    some algorithms different implementations of sparse arrays
    can perform better.  See [1]_ for details.

Returns
-------
A : SciPy sparse array
   Graph adjacency matrix.

Notes
-----
For directed graphs, matrix entry ``i, j`` corresponds to an edge from
``i`` to ``j``.

The values of the adjacency matrix are populated using the edge attribute held in
parameter `weight`. When an edge does not have that attribute, the
value of the entry is 1.

For multiple edges the matrix values are the sums of the edge weights.

When `nodelist` does not contain every node in `G`, the adjacency matrix
is built from the subgraph of `G` that is induced by the nodes in
`nodelist`.

The convention used for self-loop edges in graphs is to assign the
diagonal matrix entry value to the weight attribute of the edge
(or the number 1 if the edge has no weight attribute).  If the
alternate convention of doubling the edge weight is desired the
resulting array can be modified as follows::

    >>> G = nx.Graph([(1, 1)])
    >>> A = nx.to_scipy_sparse_array(G)
    >>> A.toarray()
    array([[1]])
    >>> A.setdiag(A.diagonal() * 2)
    >>> A.toarray()
    array([[2]])

Examples
--------

Basic usage:

>>> G = nx.path_graph(4)
>>> A = nx.to_scipy_sparse_array(G)
>>> A  # doctest: +SKIP
<Compressed Sparse Row sparse array of dtype 'int64'
    with 6 stored elements and shape (4, 4)>

>>> A.toarray()
array([[0, 1, 0, 0],
       [1, 0, 1, 0],
       [0, 1, 0, 1],
       [0, 0, 1, 0]])

.. note:: The `toarray` method is used in these examples to better visualize
   the adjacancy matrix. For a dense representation of the adjaceny matrix,
   use `to_numpy_array` instead.

Directed graphs:

>>> G = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
>>> nx.to_scipy_sparse_array(G).toarray()
array([[0, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 0, 1],
       [0, 0, 0, 0]])

>>> H = G.reverse()
>>> H.edges
OutEdgeView([(1, 0), (2, 1), (3, 2)])
>>> nx.to_scipy_sparse_array(H).toarray()
array([[0, 0, 0, 0],
       [1, 0, 0, 0],
       [0, 1, 0, 0],
       [0, 0, 1, 0]])

By default, the order of the rows/columns of the adjacency matrix is determined
by the ordering of the nodes in `G`:

>>> G = nx.Graph()
>>> G.add_nodes_from([3, 5, 0, 1])
>>> G.add_edges_from([(1, 3), (1, 5)])
>>> nx.to_scipy_sparse_array(G).toarray()
array([[0, 0, 0, 1],
       [0, 0, 0, 1],
       [0, 0, 0, 0],
       [1, 1, 0, 0]])

The ordering of the rows can be changed with `nodelist`:

>>> ordered = [0, 1, 3, 5]
>>> nx.to_scipy_sparse_array(G, nodelist=ordered).toarray()
array([[0, 0, 0, 0],
       [0, 0, 1, 1],
       [0, 1, 0, 0],
       [0, 1, 0, 0]])

If `nodelist` contains a subset of the nodes in `G`, the adjacency matrix
for the node-induced subgraph is produced:

>>> nx.to_scipy_sparse_array(G, nodelist=[1, 3, 5]).toarray()
array([[0, 1, 1],
       [1, 0, 0],
       [1, 0, 0]])

The values of the adjacency matrix are drawn from the edge attribute
specified by the `weight` parameter:

>>> G = nx.path_graph(4)
>>> nx.set_edge_attributes(
...     G, values={(0, 1): 1, (1, 2): 10, (2, 3): 2}, name="weight"
... )
>>> nx.set_edge_attributes(
...     G, values={(0, 1): 50, (1, 2): 35, (2, 3): 10}, name="capacity"
... )
>>> nx.to_scipy_sparse_array(G).toarray()  # Default weight="weight"
array([[ 0,  1,  0,  0],
       [ 1,  0, 10,  0],
       [ 0, 10,  0,  2],
       [ 0,  0,  2,  0]])
>>> nx.to_scipy_sparse_array(G, weight="capacity").toarray()
array([[ 0, 50,  0,  0],
       [50,  0, 35,  0],
       [ 0, 35,  0, 10],
       [ 0,  0, 10,  0]])

Any edges that don't have a `weight` attribute default to 1:

>>> G[1][2].pop("capacity")
35
>>> nx.to_scipy_sparse_array(G, weight="capacity").toarray()
array([[ 0, 50,  0,  0],
       [50,  0,  1,  0],
       [ 0,  1,  0, 10],
       [ 0,  0, 10,  0]])

When `G` is a multigraph, the values in the adjacency matrix are given by
the sum of the `weight` edge attribute over each edge key:

>>> G = nx.MultiDiGraph([(0, 1), (0, 1), (0, 1), (2, 0)])
>>> nx.to_scipy_sparse_array(G).toarray()
array([[0, 3, 0],
       [0, 0, 0],
       [1, 0, 0]])

References
----------
.. [1] Scipy Dev. References, "Sparse Arrays",
   https://docs.scipy.org/doc/scipy/reference/sparse.html
r   NzGraph has no nodes or edgesznodelist has no nodeszNode  in nodelist is not in Gnodelist contains duplicates.c              3   @   >#    U  H  u  pnTU   TU   U4v   M     g 7fr3    r6   r\   r]   wtr   s       r   r9   (to_scipy_sparse_array.<locals>.<genexpr>  s&     	S3RxqR58U1Xr
"3R      r   default)shaper   c              3   :   >#    U  H  u  pnTU   U* 4v   M     g 7fr3   rj   rk   s       r   r9   rm     s     )T)haB58bS/)s   zUnknown sparse matrix format: )scipyrX   r'   r(   r   r%   nbunch_itersubgraphdictrR   ranger<   
ValueErroris_directedsparse	coo_arrayselfloop_edgesasformat)r   r   r   r   formatspnlennodesetncoefficientsrowrb   r   r.   r8   rra   	selfloops
diag_index	diag_datar+   r   s                        @r   r
   r
     s1   Z 
1v{<==71v8}19""#:;;ammH-.3w<:**U1#5M+NOO  ""#BCC#a&=

8$AXuT{+,E	S177PQ73R	SL$%$
 	}}IISz 24,eT KII **11EF	$')T))T$U!J	NAOAOAIIFD<uMSzz&!!+  $R$$$,  S!?xHIsRSs*   2G2 !H 2HH
H0H++H0c                 P   U R                   S   nU R                  U R                  U R                  pCnSSKnUR                  UR                  U5      UR                  U5      5      n[        UR                  5       UR                  5       U R                  R                  5       5      $ )zlConverts a SciPy sparse array in **Compressed Sparse Row** format to
an iterable of weighted edge triples.

r   N
rr   indptrindicesr   numpyrepeatarangediffrR   tolist)r.   nrowsr   dst_indicesr   npsrc_indicess          r   _csr_gen_triplesr     w    
 GGAJE !!))QVVF))BIIe,bggfo>K{!!#[%7%7%9166==?KKr   c                 P   U R                   S   nU R                  U R                  U R                  pCnSSKnUR                  UR                  U5      UR                  U5      5      n[        UR                  5       UR                  5       U R                  R                  5       5      $ )zoConverts a SciPy sparse array in **Compressed Sparse Column** format to
an iterable of weighted edge triples.

ro   r   Nr   )r.   ncolsr   r   r   r   r   s          r   _csc_gen_triplesr     r   r   c                     [        U R                  R                  5       U R                  R                  5       U R                  R                  5       5      $ )zaConverts a SciPy sparse array in **Coordinate** format to an iterable
of weighted edge triples.

)rR   r   r   rb   r   r.   s    r   _coo_gen_triplesr     s1    
 quu||~quu||~qvv}}??r   c              #      #    U R                  5        H/  u  u  pn[        U5      [        U5      UR                  5       4v   M1     g7f)ziConverts a SciPy sparse array in **Dictionary of Keys** format to an
iterable of weighted edge triples.

N)itemsintitem)r.   r   ra   r]   s       r   _dok_gen_triplesr     s8     
 WWY	!fc!faffh&& s   AAc                     U R                   S:X  a  [        U 5      $ U R                   S:X  a  [        U 5      $ U R                   S:X  a  [        U 5      $ [	        U R                  5       5      $ )zReturns an iterable over (u, v, w) triples, where u and v are adjacent
vertices and w is the weight of the edge joining u and v.

`A` is a SciPy sparse array (in any format).

csrcscdok)r   r   r   r   r   tocoor   s    r   _generate_weighted_edgesr     sZ     	xx5""xx5""xx5""AGGI&&r   c                 ,   [         R                  " SU5      nU R                  u  pVXV:w  a#  [         R                  " SU R                   35      eUR	                  [        U5      5        [        U 5      nU R                  R                  S;   aE  UR                  5       (       a0  U(       a)  [        R                  R                  nU" S U 5       5      nUR                  5       (       a  UR                  5       (       d	  S U 5       nUR                  XsS9  U$ )a	  Creates a new graph from an adjacency matrix given as a SciPy sparse
array.

Parameters
----------
A: scipy.sparse array
  An adjacency matrix representation of a graph

parallel_edges : Boolean
  If this is True, `create_using` is a multigraph, and `A` is an
  integer matrix, then entry *(i, j)* in the matrix is interpreted as the
  number of parallel edges joining vertices *i* and *j* in the graph.
  If it is False, then the entries in the matrix are interpreted as
  the weight of a single edge joining the vertices.

create_using : NetworkX graph constructor, optional (default=nx.Graph)
   Graph type to create. If graph instance, then cleared before populated.

edge_attribute: string
   Name of edge attribute to store matrix numeric value. The data will
   have the same type as the matrix entry (int, float, (real,imag)).

Notes
-----
For directed graphs, explicitly mention create_using=nx.DiGraph,
and entry i,j of A corresponds to an edge from i to j.

If `create_using` is :class:`networkx.MultiGraph` or
:class:`networkx.MultiDiGraph`, `parallel_edges` is True, and the
entries of `A` are of type :class:`int`, then this function returns a
multigraph (constructed from `create_using`) with parallel edges.
In this case, `edge_attribute` will be ignored.

If `create_using` indicates an undirected multigraph, then only the edges
indicated by the upper triangle of the matrix `A` will be added to the
graph.

Examples
--------
>>> import scipy as sp
>>> A = sp.sparse.eye(2, 2, 1)
>>> G = nx.from_scipy_sparse_array(A)

If `create_using` indicates a multigraph and the matrix has only integer
entries and `parallel_edges` is False, then the entries will be treated
as weights for edges joining the nodes (without creating parallel edges):

>>> A = sp.sparse.csr_array([[1, 1], [1, 2]])
>>> G = nx.from_scipy_sparse_array(A, create_using=nx.MultiGraph)
>>> G[1][1]
AtlasView({0: {'weight': 2}})

If `create_using` indicates a multigraph and the matrix has only integer
entries and `parallel_edges` is True, then the entries will be treated
as the number of parallel edges joining those two vertices:

>>> A = sp.sparse.csr_array([[1, 1], [1, 2]])
>>> G = nx.from_scipy_sparse_array(
...     A, parallel_edges=True, create_using=nx.MultiGraph
... )
>>> G[1][1]
AtlasView({0: {'weight': 1}, 1: {'weight': 1}})

r   #Adjacency matrix not square: nx,ny=)ir\   c              3   Z   ^^#    U  H  u  mmnUU4S  j[        U5       5       v   M!     g7f)c              3   .   >#    U  H
  nTTS 4v   M     g7fro   Nrj   r6   r8   r\   r]   s     r   r9   4from_scipy_sparse_array.<locals>.<genexpr>.<genexpr>e  s     5Hq!QH   Nrx   )r6   wr\   r]   s     @@r   r9   *from_scipy_sparse_array.<locals>.<genexpr>e  s$     Ow)1a5E!H55ws   '+c              3   >   #    U  H  u  po1U::  d  M  XU4v   M     g 7fr3   rj   r6   r\   r]   r8   s       r   r9   r   o       >GqAv9A!9G   )r   )r'   rQ   rr   r(   add_nodes_fromrx   r   r   kindr@   	itertoolschainfrom_iterablerz   add_weighted_edges_from)	r.   parallel_edgesr#   edge_attributer   r   mtriplesr   s	            r   r	   r	     s    H 	q,'A77DAv!DQWWINOOU1X 'q)G 	ww||z!aoo&7&7N-- OwOO 	>G>g=Hr   c                    SSK nUc  [        U 5      n[        U5      n[        U5      n	U	[        U 5      -
  (       a&  [        R
                  " SU	[        U 5      -
   S35      e[        U	5      U:  a  [        R
                  " S5      eUR                  X4XbUS9n
US:X  d  U R                  5       S:X  a  U
$ SnU
R                  R                  (       a  Uc  UR                  nO[        S5      e[        [        U[        U5      5      5      n[        U5      [        U 5      :  a  U R                  U5      R                  5       n U R!                  5       (       a  U(       a  [        R
                  " S5      e[#        [        5      nU R%                  US	S
9 H   u  pnXU   X   4   R'                  U5        M"     UR)                  [        UR+                  5       5      5      R,                  u  nnUR/                  5        Vs/ s H  nU" U5      PM     nnGO/ / / nnnU(       a  U R%                  SS9 H=  u  pnUR'                  X   5        UR'                  X   5        UR'                  U5        M?     U HP  nU Vs/ s H  nUR1                  US	5      PM     nnUU
U   UU4'   U R3                  5       (       a  MF  UU
U   UU4'   MR     U
$ U R%                  US	S
9 H=  u  pnUR'                  X   5        UR'                  X   5        UR'                  U5        M?     UU
UU4'   U R3                  5       (       d  UU
UU4'   U
$ s  snf s  snf )ah  Returns the graph adjacency matrix as a NumPy array.

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

nodelist : list, optional
    The rows and columns are ordered according to the nodes in `nodelist`.
    If `nodelist` is ``None``, then the ordering is produced by ``G.nodes()``.

dtype : NumPy data type, optional
    A NumPy data type used to initialize the array. If None, then the NumPy
    default is used. The dtype can be structured if `weight=None`, in which
    case the dtype field names are used to look up edge attributes. The
    result is a structured array where each named field in the dtype
    corresponds to the adjacency for that edge attribute. See examples for
    details.

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

multigraph_weight : callable, optional
    An function that determines how weights in multigraphs are handled.
    The function should accept a sequence of weights and return a single
    value. The default is to sum the weights of the multiple edges.

weight : string or None optional (default = 'weight')
    The edge attribute that holds the numerical value used for
    the edge weight. If an edge does not have that attribute, then the
    value 1 is used instead. `weight` must be ``None`` if a structured
    dtype is used.

nonedge : array_like (default = 0.0)
    The value used to represent non-edges in the adjacency matrix.
    The array values corresponding to nonedges are typically set to zero.
    However, this could be undesirable if there are array values
    corresponding to actual edges that also have the value zero. If so,
    one might prefer nonedges to have some other value, such as ``nan``.

Returns
-------
A : NumPy ndarray
    Graph adjacency matrix

Raises
------
NetworkXError
    If `dtype` is a structured dtype and `G` is a multigraph
ValueError
    If `dtype` is a structured dtype and `weight` is not `None`

See Also
--------
from_numpy_array

Notes
-----
For directed graphs, entry ``i, j`` corresponds to an edge from ``i`` to ``j``.

Entries in the adjacency matrix are given by the `weight` edge attribute.
When an edge does not have a weight attribute, the value of the entry is
set to the number 1.  For multiple (parallel) edges, the values of the
entries are determined by the `multigraph_weight` parameter. The default is
to sum the weight attributes for each of the parallel edges.

When `nodelist` does not contain every node in `G`, the adjacency matrix is
built from the subgraph of `G` that is induced by the nodes in `nodelist`.

The convention used for self-loop edges in graphs is to assign the
diagonal array entry value to the weight attribute of the edge
(or the number 1 if the edge has no weight attribute). If the
alternate convention of doubling the edge weight is desired the
resulting NumPy array can be modified as follows:

>>> import numpy as np
>>> G = nx.Graph([(1, 1)])
>>> A = nx.to_numpy_array(G)
>>> A
array([[1.]])
>>> A[np.diag_indices_from(A)] *= 2
>>> A
array([[2.]])

Examples
--------
>>> G = nx.MultiDiGraph()
>>> G.add_edge(0, 1, weight=2)
0
>>> G.add_edge(1, 0)
0
>>> G.add_edge(2, 2, weight=3)
0
>>> G.add_edge(2, 2)
1
>>> nx.to_numpy_array(G, nodelist=[0, 1, 2])
array([[0., 2., 0.],
       [1., 0., 0.],
       [0., 0., 4.]])

When `nodelist` argument is used, nodes of `G` which do not appear in the `nodelist`
and their edges are not included in the adjacency matrix. Here is an example:

>>> G = nx.Graph()
>>> G.add_edge(3, 1)
>>> G.add_edge(2, 0)
>>> G.add_edge(2, 1)
>>> G.add_edge(3, 0)
>>> nx.to_numpy_array(G, nodelist=[1, 2, 3])
array([[0., 1., 1.],
       [1., 0., 0.],
       [1., 0., 0.]])

This function can also be used to create adjacency matrices for multiple
edge attributes with structured dtypes:

>>> G = nx.Graph()
>>> G.add_edge(0, 1, weight=10)
>>> G.add_edge(1, 2, cost=5)
>>> G.add_edge(2, 3, weight=3, cost=-4.0)
>>> dtype = np.dtype([("weight", int), ("cost", float)])
>>> A = nx.to_numpy_array(G, dtype=dtype, weight=None)
>>> A["weight"]
array([[ 0, 10,  0,  0],
       [10,  0,  1,  0],
       [ 0,  1,  0,  3],
       [ 0,  0,  3,  0]])
>>> A["cost"]
array([[ 0.,  1.,  0.,  0.],
       [ 1.,  0.,  5.,  0.],
       [ 0.,  5.,  0., -4.],
       [ 0.,  0., -4.,  0.]])

As stated above, the argument "nonedge" is useful especially when there are
actually edges with weight 0 in the graph. Setting a nonedge value different than 0,
makes it much clearer to differentiate such 0-weighted edges and actual nonedge values.

>>> G = nx.Graph()
>>> G.add_edge(3, 1, weight=2)
>>> G.add_edge(2, 0, weight=0)
>>> G.add_edge(2, 1, weight=0)
>>> G.add_edge(3, 0, weight=1)
>>> nx.to_numpy_array(G, nonedge=-1.0)
array([[-1.,  2., -1.,  1.],
       [ 2., -1.,  0., -1.],
       [-1.,  0., -1.,  0.],
       [ 1., -1.,  0., -1.]])
r   NzNodes rg   rh   )
fill_valuer   r   zSpecifying `weight` not supported for structured dtypes
.To create adjacency matrices from structured dtypes, use `weight=None`.z3Structured arrays are not supported for MultiGraphsg      ?rp   Tr1   )r   r   rX   r%   r'   r(   fullnumber_of_edgesr   namesry   rw   rR   rx   rv   copyr@   r   r<   rU   arrayr5   Tr)   r?   rz   )r   r   r   r   r   r   r   r   r   r   r.   r   idxr8   r\   r]   rl   r   jwswtsr   attr	attr_datas                           r   r   r   t  s   @ 7x=D (mGQ#a&(8'99QRSS
7|d>??
UKA qyA%%'1, Jww}}>JZ  s8U4[)
*C
8}s1vJJx %%' 	""E  VS9HA"1vsv&&r* :xxQVVX'))1/0xxz:z $z:Bc1 gg4g0
d  

4  1 #9<=2RVVD#.	= )$1}}$-AdGAqDM	 #
 HVS9HA"HHSVHHSVJJrN : AadG==??!Q$H= ; >s   >L?:M)r   c          	        ^ ^^^^^ [         [        [        [        [        [        [        SS.m[
        R                  " SU5      nT R                  S:w  a#  [
        R                  " ST R                   35      eT R                  u  pgXg:w  a#  [
        R                  " ST R                   35      eT R                  n TUR                     mUSL =n
(       a  [        U5      nO[        U5      U:w  a  [!        S	5      eUR#                  U5        S
 [%        T R'                  5       6  5       nTS:X  aD  [)        S T R                  R*                  R-                  5        5       5      mU UUU4S jU 5       nOT[        L ac  UR/                  5       (       aN  U(       aG  [0        R2                  R4                  nTS;   a  U" U 4S jU 5       5      nO2U" U U4S jU 5       5      nOTS;   a
  S U 5       nOU UU4S jU 5       nUR/                  5       (       a  UR7                  5       (       d	  S U 5       nU
(       d   [9        [;        U5      5      mU4S jU 5       nUR=                  U5        U$ ! [         a  n	[        SU 35      U	eSn	A	ff = f)a  Returns a graph from a 2D NumPy array.

The 2D NumPy array is interpreted as an adjacency matrix for the graph.

Parameters
----------
A : a 2D numpy.ndarray
    An adjacency matrix representation of a graph

parallel_edges : Boolean
    If this is True, `create_using` is a multigraph, and `A` is an
    integer array, then entry *(i, j)* in the array is interpreted as the
    number of parallel edges joining vertices *i* and *j* in the graph.
    If it is False, then the entries in the array are interpreted as
    the weight of a single edge joining the vertices.

create_using : NetworkX graph constructor, optional (default=nx.Graph)
   Graph type to create. If graph instance, then cleared before populated.

edge_attr : String, optional (default="weight")
    The attribute to which the array values are assigned on each edge. If
    it is None, edge attributes will not be assigned.

nodelist : sequence of nodes, optional
    A sequence of objects to use as the nodes in the graph. If provided, the
    list of nodes must be the same length as the dimensions of `A`. The
    default is `None`, in which case the nodes are drawn from ``range(n)``.

Notes
-----
For directed graphs, explicitly mention create_using=nx.DiGraph,
and entry i,j of A corresponds to an edge from i to j.

If `create_using` is :class:`networkx.MultiGraph` or
:class:`networkx.MultiDiGraph`, `parallel_edges` is True, and the
entries of `A` are of type :class:`int`, then this function returns a
multigraph (of the same type as `create_using`) with parallel edges.

If `create_using` indicates an undirected multigraph, then only the edges
indicated by the upper triangle of the array `A` will be added to the
graph.

If `edge_attr` is Falsy (False or None), edge attributes will not be
assigned, and the array data will be treated like a binary mask of
edge presence or absence. Otherwise, the attributes will be assigned
as follows:

If the NumPy array has a single data type for each array entry it
will be converted to an appropriate Python data type.

If the NumPy array has a user-specified compound data type the names
of the data fields will be used as attribute keys in the resulting
NetworkX graph.

See Also
--------
to_numpy_array

Examples
--------
Simple integer weights on edges:

>>> import numpy as np
>>> A = np.array([[1, 1], [2, 1]])
>>> G = nx.from_numpy_array(A)
>>> G.edges(data=True)
EdgeDataView([(0, 0, {'weight': 1}), (0, 1, {'weight': 2}), (1, 1, {'weight': 1})])

If `create_using` indicates a multigraph and the array has only integer
entries and `parallel_edges` is False, then the entries will be treated
as weights for edges joining the nodes (without creating parallel edges):

>>> A = np.array([[1, 1], [1, 2]])
>>> G = nx.from_numpy_array(A, create_using=nx.MultiGraph)
>>> G[1][1]
AtlasView({0: {'weight': 2}})

If `create_using` indicates a multigraph and the array has only integer
entries and `parallel_edges` is True, then the entries will be treated
as the number of parallel edges joining those two vertices:

>>> A = np.array([[1, 1], [1, 2]])
>>> temp = nx.MultiGraph()
>>> G = nx.from_numpy_array(A, parallel_edges=True, create_using=temp)
>>> G[1][1]
AtlasView({0: {'weight': 1}, 1: {'weight': 1}})

User defined compound data type on edges:

>>> dt = [("weight", float), ("cost", int)]
>>> A = np.array([[(1.0, 2)]], dtype=dt)
>>> G = nx.from_numpy_array(A)
>>> G.edges()
EdgeView([(0, 0)])
>>> G[0][0]["cost"]
2
>>> G[0][0]["weight"]
1.0

void)fr   r\   bra   SUVr      zInput array must be 2D, not r   zUnknown numpy data type: Nz0nodelist must have the same length as A.shape[0]c              3   Z   #    U  H!  n[        US    5      [        US   5      4v   M#     g7f)r   ro   N)r   )r6   es     r   r9   #from_numpy_array.<locals>.<genexpr>  s'     ?->c!A$iQqT#->s   )+c              3   4   #    U  H  u  nu  p#X2U4v   M     g 7fr3   rj   )r6   namer   offsets       r   r9   r     s       
?U&;dOUVD!?Us   c              3      >#    U  HR  u  pUUTS ;   a  0 O?[        T	TX4   5       VVVVs0 s H  u  u  p4pVUT
UR                     " U5      _M      snnnn4v   MT     gs  snnnnf 7f)FNN)rR   r   )r6   r\   r]   r7   r   r   valr.   rL   fieldskind_to_python_types          r   r9   r     s~      
  -  25VQqtW1E1E-(4 -ejj9#>>1E	 s   'A%%AA%r   c              3   d   >^^#    U  H#  u  mmUU4S  j[        TTT4   5       5       v   M%     g7f)c              3   .   >#    U  H
  nTT0 4v   M     g 7fr3   rj   r   s     r   r9   -from_numpy_array.<locals>.<genexpr>.<genexpr>  s     @AaBZr   Nr   )r6   r\   r]   r.   s    @@r   r9   r     s*     UuVa@qAw@@us   +0c              3   f   >^^#    U  H$  u  mmUUU4S  j[        TTT4   5       5       v   M&     g7f)c              3   2   >#    U  H  nTTTS 04v   M     g7fr   rj   )r6   r8   rL   r\   r]   s     r   r9   r     s     @A!QA's   Nr   )r6   r\   r]   r.   rL   s    @@r   r9   r     s-      OTVa@qAw@@us   ,1c              3   .   #    U  H  u  pX0 4v   M     g 7fr3   rj   )r6   r\   r]   s      r   r9   r     s     4edabzes   c           	   3   H   >#    U  H  u  pXTT" TX4   5      04v   M     g 7fr3   rj   )r6   r\   r]   r.   rL   python_types      r   r9   r     s(     SUTQy+ag*>?@Us   "c              3   >   #    U  H  u  po1U::  d  M  XU4v   M     g 7fr3   rj   r   s       r   r9   r     r   r   c              3   @   >#    U  H  u  pnTU   TU   U4v   M     g 7fr3   rj   )r6   r\   r]   r8   idx_to_nodes       r   r9   r   #  s$     Ng71KNKNA6grn   )r>   r   boolcomplexstrr'   rQ   ndimr(   rr   r   r   r$   rZ   rx   rX   ry   r   rR   nonzerosortedr   r   r@   r   r   r   rz   rw   	enumeraterT   )r.   r   r#   rL   r   r   r   r   dtr+   _default_nodesr<   r   r   r   r   r   r   s   `  `          @@@@r   r   r   c  s8   R 	 	q,'Avv{!=affXFGG77DAv!DQWWINOO	
BC)"''2 #d*+~+8x=AOPP X @S!))+->?Ef 
?@ww~~?S?S?U
 

 
$ 
	 1 1n-- %UuUUG OT G %4e4GSUSG 	>G>9X./NgNWHO  C3B489sBCs   ;I* *
J4JJr3   )rB   rC   NNN)NNr   r   )FNr   )__doc__r   collectionsr   networkxr'   networkx.utilsr   __all___dispatchablesumr   r   r   r   r
   r   r   r   r   r   r	   r   r   rj   r   r   <module>r      s  6  #  .	 X& 

hB 'hBV T2@ 3@F d+ 
X3 ,X3v T2 n 3nb X&^S '^SB
L
L@''" T2?Ge 3eP X& 

k 'k\ T2:BAPTA 3Ar   