o
    hG                     @   sN  d Z ddlZddlmZ ddlZddlmZ g dZej	ddddde
ddfd	d
Zej	dddd+ddZej	dd					d,ddZej	ddd					d,ddZej	ddd-ddZdd Zdd Zdd Zdd  Zd!d" Zej	ddd	d.d$d%Zej	ddddde
ddfd&d'Zej	ddd	d.dd(d)d*ZdS )/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           	   	   C   s>   ddl }t| ||||||d}|du rt| }|j|||dS )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M r   k/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/networkx/convert_matrix.pyr   .   s   \	r   T)graphsreturns_graphc              
   C   st   z| | j  } W n% ty, } ztt| j t| j}| d}td||d}~ww | j}t	||| jd}|S )a7  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   r   r   r   r      s   7
r   )preserve_edge_attrssourcetargetc                    s$  ddl }|du r| jdd n| j|dd dd  D }dd  D }t jdd	  D  }	||	v r<td
|d||	v rItd|dtd fdd|	D }
|  r|dur||	v rltd|ddd | jddD }||||||i}n||||i}||
 |j	||dS )az  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                 S   s   g | ]\}}}|qS r   r   ).0s_r   r   r   
<listcomp>"      z&to_pandas_edgelist.<locals>.<listcomp>c                 S   s   g | ]\}}}|qS r   r   )r0   r2   tr   r   r   r3   #  r4   c                 s   s    | ]
\}}}|  V  qd S Nkeysr0   r2   dr   r   r   	<genexpr>%      z%to_pandas_edgelist.<locals>.<genexpr>zSource name z is an edge attr namezTarget name nanc                    s"   i | ]   fd dD qS )c                    s   g | ]\}}}|  qS r   getr9   )kr=   r   r   r3   ,  s    z1to_pandas_edgelist.<locals>.<dictcomp>.<listcomp>r   r0   edgelistr=   )r@   r   
<dictcomp>,  s   " z&to_pandas_edgelist.<locals>.<dictcomp>zEdge key name c                 S   s   g | ]\}}}|qS r   r   )r0   r2   r@   r   r   r   r3   1  r4   r7   )r   )
r   edgesr"   unionr$   r%   floatis_multigraphupdater   )r   r-   r.   r   r   edge_keyr   source_nodestarget_nodes	all_attrs	edge_attr	edge_keysedgelistdictr   rB   r   r      s*   >
r   c              
      sV  t d|}|du r;| r-|dur-t |  |  | D ]\}}}	||||	 q|S |t |  |  |S ||g| rL|durL| g }
g }|du r_fdd jD }
nt|t	t
B ri|}
n|g}
t|
dkrzt d|
 zt fdd|
D  }W n ttfy } zd| }t ||d}~ww | r|durz | }t||}W n ttfy } zd	| }t ||d}~ww t |  | |D ]*\}}}|dur|\}}|j|||d
}n|||}|| | | t|
| q|S t |  | |D ]\}}}||| || | t|
| q|S )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   NTc                    s   g | ]}| vr|qS r   r   )r0   c)reserved_columnsr   r   r3         z(from_pandas_edgelist.<locals>.<listcomp>z8Invalid edge_attr argument: No columns found with name: c                    s   g | ]} | qS r   r   )r0   col)r'   r   r   r3         zInvalid edge_attr argument: zInvalid edge_key argument: )key)r$   empty_graphrH   zipadd_edgeadd_edges_fromappendr   
isinstancer   tuplelenr%   KeyError	TypeErrorrI   )r'   r-   r.   rN   r    rJ   guvr@   attr_col_headingsattribute_datar(   r*   multigraph_edge_keysr1   r5   attrsmultigraph_edge_keyrV   r   )r'   rR   r   r   :  sd   v"



r   csrc              
      s  ddl }t| dkrtd|du rt| }t| }n<t|}|dkr)tdt| |}|t|krM|D ]}|| vrGtd| dq8td|t| k rX| |} tt	|t
| t	 fdd	| j|d
dD  }	z|	\}
}}W n ty   g g g }
}}Y nw |  r|jj||
|ff||f|d}n@|| }|
| }||
 }ttj| |d
d}|rt	 fdd	|D  \}}||7 }||7 }||7 }|jj|||ff||f|d}z||W S  ty } z	td| |d}~ww )a  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   (    | ]\}}} |  | |fV  qd S r6   r   r0   rb   rc   wtr   r   r   r;        & z(to_scipy_sparse_array.<locals>.<genexpr>   r   default)shaper   c                 3   s$    | ]\}}} | | fV  qd S r6   r   rm   ro   r   r   r;     s   " zUnknown sparse matrix format: )scipyr^   r$   r%   r   r"   nbunch_itersubgraphdictrX   rangerE   
ValueErroris_directedsparse	coo_arrayselfloop_edgesasformat)r   r   r   r   formatspnlennodesetncoefficientsrowrT   r   r+   r:   rrQ   	selfloops
diag_index	diag_datar(   r   ro   r   r	     s\    .




 r	   c                 C   sZ   | j d }| j| j| j}}}ddl}|||||}t|	 |	 | j	 S )ztConverts a SciPy sparse array in **Compressed Sparse Row** format to
    an iterable of weighted edge triples.

    r   N
rt   indptrindicesr   numpyrepeatarangediffrX   tolist)r+   nrowsr   dst_indicesr   npsrc_indicesr   r   r   _csr_gen_triples  
   
r   c                 C   sZ   | j d }| j| j| j}}}ddl}|||||}t|	 |	 | j	 S )zwConverts a SciPy sparse array in **Compressed Sparse Column** format to
    an iterable of weighted edge triples.

    rq   r   Nr   )r+   ncolsr   r   r   r   r   r   r   r   _csc_gen_triples  r   r   c                 C   s   t | j | j | j S )ziConverts a SciPy sparse array in **Coordinate** format to an iterable
    of weighted edge triples.

    )rX   r   r   rT   r   r+   r   r   r   _coo_gen_triples  s   r   c                 c   s4    |   D ]\\}}}t|t|| fV  qdS )zqConverts a SciPy sparse array in **Dictionary of Keys** format to an
    iterable of weighted edge triples.

    N)itemsintitem)r+   r   rQ   rc   r   r   r   _dok_gen_triples  s   r   c                 C   sB   | j dkr	t| S | j dkrt| S | j dkrt| S t|  S )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).

    ri   cscdok)r   r   r   r   r   tocoor   r   r   r   _generate_weighted_edges  s   


r   Fc           	      C   s   t d|}| j\}}||krt d| j |t| t| }| jjdv r<|	 r<|r<t
jj}|dd |D }|	 rK| sKdd |D }|j||d |S )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=)irb   c                 3   s.    | ]\ } fd dt |D V  qdS )c                 3   s    | ]} d fV  qdS rq   Nr   r0   r:   rb   rc   r   r   r;   e      z4from_scipy_sparse_array.<locals>.<genexpr>.<genexpr>Nry   )r0   wr   r   r   r;   e     , z*from_scipy_sparse_array.<locals>.<genexpr>c                 s   (    | ]\}}}||kr|||fV  qd S r6   r   r0   rb   rc   r:   r   r   r   r;   o  rp   )r   )r$   rW   rt   r%   add_nodes_fromry   r   r   kindrH   	itertoolschainfrom_iterabler{   add_weighted_edges_from)	r+   parallel_edgesr    edge_attributer   r   mtriplesr   r   r   r   r     s   D
	r   c                    sl  ddl }|du rt| }t|}t|}	|	t|  r'td|	t|   dt|	|k r2td|j||f|||d}
|dksG|  dkrI|
S d}|
jj	r[|du rW|j	}nt
dtt|t|}t|t| k rs| | } |  r|r~tdtt}| j|d	d
D ]\}}}||| || f | q|t| j\}}fdd| D }nog g g }}}|r| jddD ]\}}}|||  |||  || q|D ]  fdd|D }||
  ||f< |  s||
  ||f< q|
S | j|d	d
D ]\}}}|||  |||  || q	||
||f< |  s4||
||f< |
S )ad  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 rj   rk   )
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 MultiGraphs      ?rr   c                    s   g | ]} |qS r   r   )r0   ws)r   r   r   r3   B  rU   z"to_numpy_array.<locals>.<listcomp>Tr/   c                    s   g | ]}|  d qS )r   r>   )r0   rn   )attrr   r   r3   P  rS   )r   r   r^   r"   r$   r%   fullnumber_of_edgesr   namesrz   rx   rX   ry   rw   copyrH   r   rE   r[   arrayr8   Tr&   r{   )r   r   r   r   r   r   r   r   r   r   r+   r   idxr:   rb   rc   rn   r   jwtsr   	attr_datar   )r   r   r   r   t  sl    !

r   )r   c             
      s  t ttttttddtd|} jdkrtd j  j	\}}||kr1td j	  j
}z|j W n tyO }	 ztd| |	d}	~	ww |du  }
r[t|}n
t||kretd	|| d
d t   D }dkrtdd  j
j D  fdd|D }nBtu r| r|rtjj}dv r| fdd|D }n$| fdd|D }ndv rdd |D }n fdd|D }| r| sdd |D }|
stt|fdd|D }|| |S )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   rb   brQ   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                 s   s(    | ]}t |d  t |d fV  qdS )r   rq   N)r   )r0   er   r   r   r;     rp   z#from_numpy_array.<locals>.<genexpr>c                 s   s"    | ]\}\}}|||fV  qd S r6   r   )r0   namer   offsetr   r   r   r;     s    
c              	   3   sF    | ]\}}||d v ri nfddt  ||f D fV  qdS )FNc                    s&   i | ]\\}}}}| |j  |qS r   )r   )r0   r2   r   r   val)kind_to_python_typer   r   rD     s    z.from_numpy_array.<locals>.<genexpr>.<dictcomp>N)rX   r0   rb   rc   )r+   rN   fieldsr   r   r   r;     s    

r   c                 3   s4    | ]\  fd dt  f D V  qdS )c                 3   s    | ]} i fV  qd S r6   r   r   r   r   r   r;     r   -from_numpy_array.<locals>.<genexpr>.<genexpr>Nr   rA   r   r   r   r;     s   2 c                 3   s6    | ]\  fd dt  f D V  qdS )c                 3   s    | ]
} d ifV  qdS r   r   r   )rN   rb   rc   r   r   r;     r<   r   Nr   rA   )r+   rN   r   r   r;     s    &
c                 s   s    | ]
\}}||i fV  qd S r6   r   r   r   r   r   r;     r<   c                 3   s.    | ]\}}|| ||f ifV  qd S r6   r   r   )r+   rN   python_typer   r   r;     r   c                 s   r   r6   r   r   r   r   r   r;     rp   c                 3   rl   r6   r   r   )idx_to_noder   r   r;   #  rp   )rG   r   boolcomplexstrr$   rW   ndimr%   rt   r   r   r!   r`   ry   r^   rz   r   rX   nonzerosortedr   r   rH   r   r   r   r{   rx   	enumeraterZ   )r+   r   r    rN   r   r   r   r   dtr(   _default_nodesrE   r   r   r   )r+   rN   r   r   r   r   r   r
   c  sh   i






	
r
   r6   )r-   r.   NNN)NNr   ri   )FNr   )__doc__r   collectionsr   networkxr$   networkx.utilsr   __all___dispatchablesumr   r   r   r   r	   r   r   r   r   r   r   r   r
   r   r   r   r   <module>   sp    
k
C[ 
2 b

h o