ó žÃÒYc @sÎdZddlZddlZddlZddlmZddlm Z ddddd d d d d ddddg Z ddde ddd„Z ddde ddd„Zdd„Zdddddd„Zddddd„Zddddd„Zddde ddd„Zedd„Ze dƒdddd„ƒZdddd d!„Zd"„Zd#„Zd$„Zd%„Zd&„Zeddd'„Zddde ddd(„Zedd)„Zd*„Z dS(+sNFunctions to convert NetworkX graphs to and from numpy/scipy matrices. The preferred way of converting data to a NetworkX graph is through the graph constuctor. The constructor calls the 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 matrix >>> import numpy as np >>> a = np.reshape(np.random.random_integers(0, 1, size=100), (10, 10)) >>> D = nx.DiGraph(a) or equivalently >>> D = nx.to_networkx_graph(a, create_using=nx.DiGraph()) See Also -------- nx_agraph, nx_pydot iÿÿÿÿN(t_prep_create_using(tnot_implemented_fortfrom_numpy_matrixtto_numpy_matrixtfrom_pandas_dataframetto_pandas_dataframetfrom_pandas_adjacencytto_pandas_adjacencytfrom_pandas_edgelisttto_pandas_edgelisttto_numpy_recarraytfrom_scipy_sparse_matrixtto_scipy_sparse_matrixtfrom_numpy_arraytto_numpy_arraytweightgcCs2d}tj|tƒt|||||||ƒS(s0DEPRECATED: Replaced by ``to_pandas_adjacency``.s]to_pandas_dataframe is deprecated and will be removedin 2.1, use to_pandas_adjacency instead.(t _warningstwarntDeprecationWarningR(tGtnodelisttdtypetordertmultigraph_weightRtnonedgetmsg((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyR-sc Cssddl}t|d|d|d|d|d|d|ƒ}|dkrWt|ƒ}n|jd |d |d |ƒS( s8 Return 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 ----- 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 >>> import numpy as np >>> G = nx.Graph([(1, 1)]) >>> df = nx.to_pandas_adjacency(G, dtype=int) >>> df 1 1 1 >>> df.values[np.diag_indices_from(df)] *= 2 >>> df 1 1 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_pandas_adjacency(G, nodelist=[0, 1, 2], dtype=int) 0 1 2 0 0 2 0 1 1 0 0 2 0 0 4 iÿÿÿÿNRRRRRRtdatatindextcolumns(tpandasRtNonetlistt DataFrame( RRRRRRRtpdtM((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyR6sP    cCs–|j}t||ƒ}y||j}Wn>tjddtt|jƒjt|jƒƒƒƒ‚nXtj j |t t |jƒƒdt ƒ|S(srReturn 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 Use specified graph for result. The default is Graph() Notes ----- If the numpy matrix has a single data type for each matrix entry it will be converted to an appropriate Python data type. If the numpy matrix 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 >>> 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(nx.info(G)) Name: Graph from pandas adjacency matrix Type: Graph Number of nodes: 2 Number of edges: 3 Average degree: 3.0000 sColumns must match Indices.s%s not in columnstcopy(tvaluesRRtnxt NetworkXErrorRtsett differenceRtrelabelt relabel_nodestdictt enumeratetFalse(tdft create_usingtAR((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyRs/  /(tsourcettargetcsæddl}|dkr-|jdtƒ‰n|j|dtƒ‰gˆD]\}}} |^qI} gˆD]\}}} |^qk} tƒjd„ˆDƒŒ} ‡fd†| Dƒ} i| |6| |6}|j| ƒ|j|ƒS(sReturn 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 iteger) for the source nodes (for the directed case). target : str or int, optional A valid column name (string or iteger) for the target nodes (for the directed case). nodelist : list, optional Use only nodes specified in nodelist 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 cost source target weight 0 1 A B 7 1 9 C E 10 iÿÿÿÿNRcss$|]\}}}|jƒVqdS(N(tkeys(t.0tstttd((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys õscsGi|]=}gˆD]'\}}}|j|tdƒƒ^q|“qS(tnan(tgettfloat(R4tkR5R6R7(tedgelist(sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys ös (RRtedgestTrueR'tuniontupdateR (RR1R2RRRR!R5R6R7t source_nodest target_nodestall_keyst edge_attrt edgelistdict((R<sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyR Ês$  "" cCs,d}tj|tƒt|||||ƒS(s1DEPRECATED: Replaced by ``from_pandas_edgelist``.s`from_pandas_dataframe is deprecated and will be removedin 2.1, use from_pandas_edgelist instead.(RRRR(R.R1R2RDR/R((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyRüscsät|ƒ}|jj|ƒ}|jj|ƒ}|r´|tkr™g}x¬t|jƒD]:\} } | |k rX| |k rX|j| | fƒqXqXWn^t|ttfƒrÜg|D]} | |jj| ƒf^qµ}n||jj|ƒfg}xæ|j D]¬‰ˆ|ˆ|} } |j ƒrx|j | | ƒt || | ƒ} || | | j ‡fd†|Dƒƒq|j | | ƒ|| | j ‡fd†|DƒƒqWn,x)|j D]‰|j ˆ|ˆ|ƒq¾W|S(s Return 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 node 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 iteger) for the source nodes (for the directed case). target : str or int A valid column name (string or iteger) for the target nodes (for the directed case). edge_attr : str or int, iterable, True A valid column name (str or integer) or list of column names that will be used to retrieve items from the row and add them to the graph as edge attributes. If `True`, all of the remaining columns will be added. create_using : NetworkX graph Use specified graph for result. The default is Graph() See Also -------- to_pandas_edgelist Examples -------- Simple integer weights on edges: >>> import pandas as pd >>> import numpy as np >>> r = np.random.RandomState(seed=5) >>> ints = r.random_integers(1, 10, 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 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' c3s%|]\}}|ˆ|fVqdS(N((R4titj(trow(sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys hsc3s%|]\}}|ˆ|fVqdS(N((R4RFRG(RH(sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys ks(RRtget_locR>R,tappendt isinstanceRttupleR$t is_multigraphtadd_edgetmaxR@(R.R1R2RDR/tgtsrc_ittar_itedge_iRFtcolR5R6tkey((RHsm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyRs.H  . ,,c CsUddl}t|d|d|d|d|d|d|ƒ}|j|d|ƒ} | S( sG Return the graph adjacency matrix as a NumPy matrix. Parameters ---------- G : graph The NetworkX graph used to construct the NumPy matrix. 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 single NumPy data type used to initialize the array. This must be a simple type such as int or numpy.float64 and not a compound data type (see to_numpy_recarray) If None, then the NumPy default is used. order : {'C', 'F'}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. If None, then the NumPy default is used. 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 (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. nonedge : float (default = 0.0) 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 ------- M : NumPy matrix Graph adjacency matrix See Also -------- to_numpy_recarray, from_numpy_matrix Notes ----- The matrix 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 Numpy matrix can be modified as follows: >>> import numpy as np >>> G = nx.Graph([(1, 1)]) >>> A = nx.to_numpy_matrix(G) >>> A matrix([[ 1.]]) >>> A.A[np.diag_indices_from(A)] *= 2 >>> A matrix([[ 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_matrix(G, nodelist=[0, 1, 2]) matrix([[ 0., 2., 0.], [ 1., 0., 0.], [ 0., 0., 4.]]) iÿÿÿÿNRRRRRR(tnumpyRtasmatrix( RRRRRRRtnpR0R"((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyRus [   c sddl}itd6td6td6td6td6td6d d 6‰ytd ƒ}tˆd >> import numpy as np >>> A = np.matrix([[1, 1], [2, 1]]) >>> G = nx.from_numpy_matrix(A) If `create_using` is a multigraph and the matrix has only integer entries, the entries will be interpreted as weighted edges joining the vertices (without creating parallel edges): >>> A = np.matrix([[1, 1], [1, 2]]) >>> G = nx.from_numpy_matrix(A, create_using=nx.MultiGraph()) >>> G[1][1] AtlasView({0: {'weight': 2}}) If `create_using` is a multigraph and the matrix has only integer entries but `parallel_edges` is True, then the entries will be interpreted as the number of parallel edges joining those two vertices: >>> A = np.matrix([[1, 1], [1, 2]]) >>> temp = nx.MultiGraph() >>> G = nx.from_numpy_matrix(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.matrix([[(1.0, 2)]], dtype=dt) >>> G = nx.from_numpy_matrix(A) >>> list(G.edges()) [(0, 0)] >>> G[0][0]['cost'] 2 >>> G[0][0]['weight'] 1.0 iÿÿÿÿNtfRFtutbtctStvoidtViÝtUsAdjacency matrix is not square.snx,ny=%ssUnknown numpy data type: %scss*|] \}\}}|||fVqdS(N((R4tnameRtoffset((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys Lsc 3sG|]=\}}||‡fd†tˆˆ||fƒDƒfVqdS(cs5i|]+\\}}}}ˆ|j|ƒ|“qS((tkind(R4t_RRatval(tkind_to_python_type(sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys Ns N(tzip(R4RZtv(R0tfieldsRf(sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys Nsc3s>|]4\‰‰‡‡fd†tˆˆˆfƒDƒVqdS(c3s'|]}ˆˆtddƒfVqdS(RiN(R+(R4R7(RZRh(sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys ^sN(trange(R4(R0(RZRhsm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys ^sc 3s=|]3\}}||tdˆˆ||fƒƒfVqdS(RN(R+(R4RZRh(R0t python_type(sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys ascss3|])\}}}||kr|||fVqdS(N((R4RZRhR7((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys ls(RVR:tinttbooltcomplextstrtchrt ValueErrortunicodeRtshapeR%R&RRct TypeErrortadd_nodes_fromRjRgtasarraytnonzerotsortedRititemsRMt itertoolstchaint from_iterablet is_directedtadd_edges_from( R0tparallel_edgesR/RXtblurbRtntmtdtR=ttriplesR{((R0RiRfRksm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyRÙsPS               t multigraphcCsž|dkrdtfg}nddl}|dkrEt|ƒ}nt|ƒ}t|ƒt|ƒkrd}tj|ƒ‚nt|ƒ}|jƒ }t t |t |ƒƒƒ} |j ||fd|d|ƒ} | j j} x©|jdtƒD]•\} } }| |krõ| |krõ| | | | }}tg| D]}||^q;ƒ}|| ||f<|rŠ| ||f| ||f>> G = nx.Graph() >>> G.add_edge(1, 2, weight=7.0, cost=5) >>> A = nx.to_numpy_recarray(G, dtype=[('weight', float), ('cost', int)]) >>> print(A.weight) [[ 0. 7.] [ 7. 0.]] >>> print(A.cost) [[0 5] [5 0]] RiÿÿÿÿNs4Ambiguous ordering: `nodelist` contained duplicates.RRR(RR:RVRR'tlenR%R&R}R+RgRjtzerosRtnamesR=R>RLtviewtrecarray(RRRRRXtnodesetRtnlent undirectedRR"RˆRZRhtattrsRFRGRR$((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyR qs,.      ! "#$tcsrcs9ddlm}|d kr+t|ƒ}nt|ƒ}|dkrUtjdƒ‚nt|ƒtt|ƒƒkr‹d}tj|ƒ‚ntt |t |ƒƒƒ‰t ‡‡fd†|j |dt ƒDƒŒ}y|\} } } Wn%t k rggg} } } nX|jƒrK|j| | | ffd||fd |ƒ} n²| | } | | }| | }ttj|dt ƒƒ}|rÐt ‡‡fd †|DƒŒ\}}| |7} ||7}||7}n|j| ||ffd||fd |ƒ} y| j|ƒSWn$tk r4tjd |ƒ‚nXd S( s Return the graph adjacency matrix as a SciPy sparse matrix. Parameters ---------- G : graph The NetworkX graph used to construct the NumPy matrix. 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 type of the matrix to be returned (default 'csr'). For some algorithms different implementations of sparse matrices can perform better. See [1]_ for details. Returns ------- M : SciPy sparse matrix Graph adjacency matrix. Notes ----- The matrix entries 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 matrix is built from the subgraph of `G` that is induced by the nodes in `nodelist`. Uses coo_matrix format. To convert to other formats specify the format= keyword. 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 Scipy sparse matrix can be modified as follows: >>> import scipy as sp >>> G = nx.Graph([(1, 1)]) >>> A = nx.to_scipy_sparse_matrix(G) >>> print(A.todense()) [[1]] >>> A.setdiag(A.diagonal() * 2) >>> print(A.todense()) [[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 >>> S = nx.to_scipy_sparse_matrix(G, nodelist=[0, 1, 2]) >>> print(S.todense()) [[0 2 0] [1 0 0] [0 0 4]] References ---------- .. [1] Scipy Dev. References, "Sparse Matrices", https://docs.scipy.org/doc/scipy/reference/sparse.html iÿÿÿÿ(tsparseisGraph has no nodes or edgess4Ambiguous ordering: `nodelist` contained duplicates.c3sS|]I\}}}|ˆkr|ˆkrˆ|ˆ||jˆdƒfVqdS(iN(R9(R4RZRhR7(RR(sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys s RRsRc3sM|]C\}}}|ˆkr|ˆkrˆ||jˆdƒ fVqdS(iN(R9(R4RZRhR7(RR(sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys ,s s Unknown sparse matrix format: %sN(tscipyRRRR†R%R&R'R+RgRjR=R>RqR}t coo_matrixtselfloop_edgestasformattAttributeError(RRRRtformatRRŒRt coefficientsRHRTRR"R7trR\t selfloopst diag_indext diag_data((RRsm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyR ¹sDR           - ccs|jd}|j|j|j}}}xPt|ƒD]B}x9t||||dƒD]}|||||fVqYWq7WdS(suConverts a SciPy sparse matrix in **Compressed Sparse Row** format to an iterable of weighted edge triples. iiN(RsRtindicestindptrRj(R0tnrowsRRœRRFRG((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyt_csr_gen_triples9s  "ccs|jd}|j|j|j}}}xPt|ƒD]B}x9t||||dƒD]}|||||fVqYWq7WdS(sxConverts a SciPy sparse matrix in **Compressed Sparse Column** format to an iterable of weighted edge triples. iN(RsRRœRRj(R0tncolsRRœRRFRG((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyt_csc_gen_triplesEs  "cCs-|j|j|j}}}t|||ƒS(sjConverts a SciPy sparse matrix in **Coordinate** format to an iterable of weighted edge triples. (RHRTRRg(R0RHRTR((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyt_coo_gen_triplesQsccs5x.|jƒD] \\}}}|||fVq WdS(srConverts a SciPy sparse matrix in **Dictionary of Keys** format to an iterable of weighted edge triples. N(Ry(R0R˜R\Rh((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyt_dok_gen_triplesZscCs[|jdkrt|ƒS|jdkr2t|ƒS|jdkrKt|ƒSt|jƒƒS(s½Returns 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 matrix (in any format). Rtcsctdok(R–RŸR¡R£R¢ttocoo(R0((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyt_generate_weighted_edgescs   c Csît|ƒ}|j\}}||krCtjd|jfƒ‚n|jt|ƒƒt|ƒ}|jjdkr«|j ƒr«|r«t j j }|d„|Dƒƒ}n|j ƒr×|j ƒ r×d„|Dƒ}n|j|d|ƒ|S(s, Creates a new graph from an adjacency matrix given as a SciPy sparse matrix. Parameters ---------- A: scipy sparse matrix 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 adjacency matrix are interpreted as the weight of a single edge joining the vertices. create_using: NetworkX graph Use specified graph for result. The default is Graph() 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 ----- If `create_using` is an instance of :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. In this case, `edge_attribute` will be ignored. If `create_using` is 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_matrix(A) If `create_using` is a multigraph and the matrix has only integer entries, the entries will be interpreted as weighted edges joining the vertices (without creating parallel edges): >>> A = sp.sparse.csr_matrix([[1, 1], [1, 2]]) >>> G = nx.from_scipy_sparse_matrix(A, create_using=nx.MultiGraph()) >>> G[1][1] AtlasView({0: {'weight': 2}}) If `create_using` is a multigraph and the matrix has only integer entries but `parallel_edges` is True, then the entries will be interpreted as the number of parallel edges joining those two vertices: >>> A = sp.sparse.csr_matrix([[1, 1], [1, 2]]) >>> G = nx.from_scipy_sparse_matrix(A, parallel_edges=True, ... create_using=nx.MultiGraph()) >>> G[1][1] AtlasView({0: {'weight': 1}, 1: {'weight': 1}}) s(Adjacency matrix is not square. nx,ny=%sRFRZc3s7|]-\‰‰}‡‡fd†t|ƒDƒVqdS(c3s|]}ˆˆdfVqdS(iN((R4R7(RZRh(sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys ÊsN(Rj(R4tw((RZRhsm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys Êscss3|])\}}}||kr|||fVqdS(N((R4RZRhR7((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pys ÔsR(RFRZ(RRsR%R&RuRjR§RRcRMRzR{R|R}tadd_weighted_edges_from( R0RR/tedge_attributeRRR‚R„R{((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyR ts?   $  cCsƒddl}|dkr't|ƒ}nt|ƒ}t|ƒt|ƒkrcd} tj| ƒ‚nt|ƒ} |jƒ } tt |t | ƒƒƒ} |j ƒrÀ|j | | f|j d|ƒ} i|jt6|jt6|jt6}y||}Wntdƒ‚nXxH|jdtƒD]š\}}}||kr||kr| || |}}|j|dƒ}||| ||fgƒ| ||f<| r¹| ||f| ||f>> 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.]]) iÿÿÿÿNs4Ambiguous ordering: `nodelist` contained duplicates.Rs*multigraph_weight must be sum, min, or maxRiR(RVRRR'R†R%R&R}R+RgRjRMtfullR8tnansumtsumtnanmintmintnanmaxRORqR=R>R9t adjacencyRytKeyErrortisnanRv(RRRRRRRRXR‹RRŒRRR0toperatortopRZRhRŽRFRGte_weighttnbrdictR7((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyRÙsD[     " !$"&'!(  cCst|d|d|ƒS(s= Return a graph from NumPy array. The NumPy array is interpreted as an adjacency matrix for the graph. Parameters ---------- A : 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 adjacency 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 adjacency matrix are interpreted as the weight of a single edge joining the vertices. create_using : NetworkX graph Use specified graph for result. The default is Graph() Notes ----- If `create_using` is an instance of :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` is an undirected multigraph, then only the edges indicated by the upper triangle of the array `A` will be added to the graph. 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` is a multigraph and the array has only integer entries, the entries will be interpreted as weighted edges joining the vertices (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` is a multigraph and the array has only integer entries but `parallel_edges` is True, then the entries will be interpreted 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 RR/(R(R0RR/((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyR ‚sUcCs†ddlm}yddl}Wn|dƒ‚nXyddl}Wn|dƒ‚nXyddl}Wn|dƒ‚nXdS(Niÿÿÿÿ(tSkipTestsNumPy not availablesSciPy not availablesPandas not available(tnoseR¸RVR‘R(tmoduleR¸RVR‘R((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pyt setup_moduleÜs(!t__doc__twarningsRRztnetworkxR%tnetworkx.convertRtnetworkx.utilsRt__all__RR­RRRR RRRR-RR R RŸR¡R¢R£R§R RR R»(((sm/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/convert_matrix.pytsR      X ; 1    o c˜ G  d ¨Z