K i(dZddlZddlmZddlZgdZejddddeddfdZ ejdd dd Z ejd  dd Z ejdd  ddZ ejdddZ dZdZdZdZdZejdd  ddZejddddeddfdZejdd  ddddZy)aFunctions 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)from_pandas_adjacencyto_pandas_adjacencyfrom_pandas_edgelistto_pandas_edgelistfrom_scipy_sparse_arrayto_scipy_sparse_arrayfrom_numpy_arrayto_numpy_arrayweight) edge_attrsgc pddl}t|||||||}| t|}|j|||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 rN)nodelistdtypeordermultigraph_weightr nonedge)dataindexcolumns)pandasr list DataFrame) Grrrrr rpdMs ]/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/networkx/convert_matrix.pyrr-sMx + A7 <>> 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 columnszColumns must match Indices.N) create_usingr) r Exceptionrset differencernx NetworkXErrorvaluesr )dfr"errmissingmsgArs rrrsjL \ A KA H Ls288}//BJJ@A )>> 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 rNTrc3DK|]\}}}|jywNkeys).0_ds r z%to_pandas_edgelist.."s?71aaffh?s z Source name z is an edge attr namez Target name nanzEdge key name r3)r) redgesr$unionr&r'floatget is_multigraphupdater)rsourcetargetrredge_keyredgelistsr6 source_nodest target_nodes all_attrsr9kr7 edge_attr edge_keys edgelistdicts rrrs|777%778$7/%-.'!QA.L.%-.'!QA.L. ?h?@I fZ7LMNN fZ7LMNN ,CENOO(;wq!QQUU1c];;OIOX1 y ""^H>> 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'}}) rNTz8Invalid edge_attr argument: No columns found with name: zInvalid edge_attr argument: zInvalid edge_key argument: )key)r& empty_graphr>zipadd_edgeadd_edges_fromappendr isinstancertuplelenr'KeyError TypeErrorr?)r)r@rArJr"rBguvrIreserved_columnsattr_col_headingsattribute_dataccolr*r,multigraph_edge_keysrDrFattrsmultigraph_edge_keyrNs rrr7sl q,'A ?? !5r&z2f:r(|D $1a 1a# $   SFRZ8 9'X1)ND(* P1a?O6OQPP Ite| ,%&K "FGXFY Z  -2CD3r#wDE     5')(|$!$^5I!J r&z2f:~F ?KAq%#-2**jjA+>j?jjA& aDGCL  $5u = > ? H r&z2f:~F :KAq% JJq!  aDGNN30%8 9 : HOQE i -,YK8s#,-i( 53H:>&&s+4 5sN? H H H H)HIHI +II I=I88I=cZddl}t|dk(rtjd|t |}t|}nt|}|dk(rtjdt |j |}|t|k7r9|D]}||vstjd|dtjd|t|kr|j|}tt|t|tfd|j|d D} | \} } } |jr%|jj| | | ff||f| } ny| | z}| | z}| | z}t tj ||d }|r#tfd |D\}}||z }||z }||z }|jj|||ff||f| } | j#|S#t$r ggg} } } YwxYw#t$r}tjd ||d}~wwxYw)aReturns 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 >>> 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 adjacency 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 rNzGraph has no nodes or edgesznodelist has no nodeszNode  in nodelist is not in Gnodelist contains duplicates.c3<K|]\}}}|||fywr2r5rZr[wtrs rr8z(to_scipy_sparse_array..s& Sxq!R58U1Xr " Srdefault)shaperc36K|]\}}}|| fywr2rhris rr8z(to_scipy_sparse_array..s!)ThaB58bS/)TszUnknown sparse matrix format: )scipyrVr&r'rr$ nbunch_itersubgraphdictrPranger: ValueError is_directedsparse coo_arrayselfloop_edgesasformat)rrrr formatspnlennodesetn coefficientsrowr`rr-r7rr_ selfloops diag_index diag_datar*rs @rr r sJZ 1v{<==71v8} 19""#:; ;ammH-. 3w<  PA:**U1#5M+NOO P""#BC C #a&= 8$A XuT{+ ,E S177PQ73R SL$%S$  }} II  Sz 24,e  T 4K #I #I**161EF $')T))T$U !J NA OA OA II  QF D$K {!!#[%7%7%9166==? KKrcR|jd}|j|j|j}}}ddl}|j |j ||j|}t|j|j|jjS)zwConverts a SciPy sparse array in **Compressed Sparse Column** format to an iterable of weighted edge triples. rlrNr)r-ncolsrrrrrs r_csc_gen_triplesrrrct|jj|jj|jjS)ziConverts a SciPy sparse array in **Coordinate** format to an iterable of weighted edge triples. )rPrrr`rr-s r_coo_gen_triplesrs1 quu||~quu||~qvv}} ??rc#K|jD]/\\}}}t|t||jf1yw)zqConverts a SciPy sparse array in **Dictionary of Keys** format to an iterable of weighted edge triples. N)itemsintitem)r-rr_r[s r_dok_gen_triplesrs@ WWY' A!fc!faffh&&'sAAc|jdk(r t|S|jdk(r t|S|jdk(r t|St |j 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). csrcscdok)r|rrrrtocoors r_generate_weighted_edgesrsZ xx5""xx5""xx5"" AGGI &&rctjd|}|j\}}||k7r"tjd|j|j t |t |}|jjdvr;|jr+|r)tjj}|d|D}|jr|js d|D}|j|||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=)irZc3RK|]\}fdt|Dyw)c3(K|] }df ywrlNrhr5r7rZr[s rr8z4from_scipy_sparse_array...bs5q!Q5Nru)r5wrZr[s @@rr8z*from_scipy_sparse_array..bs$O)1a5E!H55Os#'c3:K|]\}}}||ks |||fywr2rhr5rZr[r7s rr8z*from_scipy_sparse_array..l">AqqAvAq!9> )r )r&rOror'add_nodes_fromrurrkindr> itertoolschain from_iterablerwadd_weighted_edges_from) r-parallel_edgesr"edge_attributerrmtriplesrs rrrsH q,'A 77DAqAv!DQWWINOOU1X'q)G  ww||z!aoo&7N--OwOO >G>gn= HrcHddl}| t|}t|}t|} | t|z r%t j d| t|z dt| |krt j d|j ||f|||} |dk(s|jdk(r| Sd} | jjr| |j} n tdtt|t|} t|t|kr|j|j}|j!r| rt j dt#t} |j%|d D]"\}}}| | || |fj'|$|j)t| j+j,\}}| j/Dcgc] }|| }}nggg}}}| r|j%d D]?\}}}|j'| ||j'| ||j'|A| D]F}|Dcgc]}|j1|d }}|| |||f<|j3r=|| |||f<H| S|j%|d D]?\}}}|j'| ||j'| ||j'|A|| ||f<|j3s|| ||f<| Scc}wcc}w) adReturns 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.]]) rNzNodes rerf) fill_valuerrzSpecifying `weight` not supported for structured dtypes .To create adjacency matrices from structured dtypes, use `weight=None`.z3Structured arrays are not supported for MultiGraphsg?rmTr0)rrrVr$r&r'fullnumber_of_edgesrnamesrvrtrPrurscopyr>rr:rSarrayr4Tr(r=rw)rrrrrr rrr~rr-r idxr7rZr[rjrjwswtsrattr attr_datas rr r qs@7 x=D(mGQ#a&(8'99QRSS 7|d>?? t UKA qyA%%'1,Jww}} >JZ  s8U4[) *C 8}s1v JJx % % '  ""E   VS9 +HAq" s1vs1v  & &r * +xxQVVX'))1/0xxz: $::Bc1 gg4g0 ! 1dQ Q  4  ! # .9<=2RVVD#.= = )$1 }}$-AdGAqDM  . HVS9 HAq" HHSV  HHSV  JJrN  AadG ==?!Q$ H=;>s *L!L)rc tttttttddt j d|}jdk7r"t jdjj\}}||k7r"t jdjj} |j|dux} r t|}nt||k7r t!d |j#|d t%j'D} dk(rCt)d jj*j-Dfd | D} nxturU|j/rE|rCt0j2j4} d vr| fd| D} n.| fd| D} nd vr d| D} n fd| D} |j/r|j7s d| D} | st9t;|fd| D} |j=| |S#t$r} td|| d} ~ wwxYw)aReturns 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)frrZbr_SUVrzInput array must be 2D, not rzUnknown numpy data type: Nz0nodelist must have the same length as A.shape[0]c3TK|] }t|dt|df"yw)rrlN)r)r5es rr8z#from_numpy_array..s% ?c!A$iQqT # ?s&(c32K|]\}\}}|||fywr2rh)r5nameroffsets rr8z#from_numpy_array..s$ &;dOUFVUD ! sc 3K|]P\}}||dvrin?t ||fDcic]\\}}}}| |j|!c}}}}fRycc}}}}ww)FNN)rPr) r5rZr[r6rrvalr-rJfieldskind_to_python_types rr8z#from_numpy_array..s  1 -25VQq!tW1E-(E4#9-ejj9#>>   s&A!$A A!rc3\K|]!\fdtfD#yw)c3(K|] }if ywr2rhrs rr8z-from_numpy_array... s@AaBZ@rNr)r5rZr[r-s @@rr8z#from_numpy_array.. s*UVa@qAw@@Us',c3^K|]"\fdtfD$yw)c3,K|] }dif ywrrh)r5r7rJrZr[s rr8z-from_numpy_array... s@A!QA'@sNr)r5rZr[r-rJs @@rr8z#from_numpy_array.. s/EKa@qAw@@s(-c3,K|] \}}||ifywr2rh)r5rZr[s rr8z#from_numpy_array..s4da1bz4sc 3HK|]\}}||||fifywr2rh)r5rZr[r-rJ python_types rr8z#from_numpy_array..s.STQ1y+a1g*>?@Ss"c3:K|]\}}}||ks |||fywr2rhrs rr8z#from_numpy_array..rrc3<K|]\}}}|||fywr2rh)r5rZr[r7 idx_to_nodes rr8z#from_numpy_array.. s&N71aKNKNA6Nrk)r<rboolcomplexstrr&rOndimr'rorrr#rXrurVrvrrPnonzerosortedrrr>rrrrwrt enumeraterR)r-rr"rJrrrrdtr*_default_nodesr:rrrrrrs` ` @@@@rr r `s4R         q,'Avv{!=affXFGG 77DAqAv!DQWWINOO BC)"''2 #d*+~+8 x=A OP PX @S!))+-> ?Ef ?@ww~~?S?S?U      $   1n--  %UuUUGOTG  %4e4GSUSG >G> 9X./ NgNW HO C3B489sBCs8H== IIIr2)r@rANNN)NNr r)FNr )__doc__r collectionsrnetworkxr&__all__ _dispatchablesumrrrrr rrrrrrr r rhrrrs6# X&    hB'hBVT2> 3> Bd+      X3,X3vT2    n 3n bX&^S'^SB L L@''"T2?Ge 3e PX&    k 'k \T2:BA PTA 3A r