ó
 ,µ[c           @   s|  d  Z  d d l Z d d l Z d d l m Z d d d d d d	 d
 d d d d g Z d d d e d d d „ Z	 d d „ Z
 d d d d d d „ Z d d d d d „ Z d d d e d d d „ Z e d d „ Z e d ƒ d d d d „ ƒ Z d d d d d „ Z d „  Z d „  Z d „  Z d  „  Z d! „  Z e d d d" „ Z d d d e d d d# „ Z e d d$ „ Z d% „  Z d S(&   s4  Functions to convert NetworkX graphs to and from numpy/scipy matrices.

The preferred way of converting data to a NetworkX graph is through the
graph constructor.  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.random.randint(0, 2, size=(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   not_implemented_fort   from_numpy_matrixt   to_numpy_matrixt   from_pandas_adjacencyt   to_pandas_adjacencyt   from_pandas_edgelistt   to_pandas_edgelistt   to_numpy_recarrayt   from_scipy_sparse_matrixt   to_scipy_sparse_matrixt   from_numpy_arrayt   to_numpy_arrayt   weightg        c   	      C   ss   d d l  } t |  d | d | d | d | d | d | ƒ} | d k rW t |  ƒ } n  | j d	 | d
 | d | ƒ S(   sd
  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
    >>> pd.options.display.max_columns = 20
    >>> 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ÿÿÿÿNt   nodelistt   dtypet   ordert   multigraph_weightR   t   nonedget   datat   indext   columns(   t   pandasR   t   Nonet   listt	   DataFrame(	   t   GR   R   R   R   R   R   t   pdt   M(    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyR   *   s    Q	c         C   s¥   y |  |  j  }  WnJ d } t t |  j  ƒ j t |  j ƒ ƒ ƒ } t j d | | ƒ ‚ n X|  j } t | d | ƒ} t j	 j
 | t t |  j ƒ ƒ d t ƒ| S(   s×  Return 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
    -----
    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
    >>> 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(nx.info(G))
    Name: Graph from pandas adjacency matrix
    Type: Graph
    Number of nodes: 2
    Number of edges: 3
    Average degree:   3.0000

    s   %s not in columnss   Columns must match Indices.t   create_usingt   copy(   R   R   t   sett
   differenceR   t   nxt   NetworkXErrort   valuesR   t   relabelt   relabel_nodest   dictt	   enumeratet   False(   t   dfR   t   msgt   missingt   AR   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyR   „   s    0'	(t   sourcet   targetc            sæ   d d l  } | d k r- |  j d t ƒ ‰  n |  j | d t ƒ‰  g  ˆ  D] \ } } }	 | ^ qI }
 g  ˆ  D] \ } } }	 | ^ qk } t ƒ  j d „  ˆ  Dƒ Œ  } ‡  f d †  | Dƒ } i |
 | 6| | 6} | j | ƒ | j | ƒ S(   sµ  Return 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[['source', 'target', 'cost', 'weight']]
      source target  cost  weight
    0      A      B     1       7
    1      C      E     9      10

    iÿÿÿÿNR   c         s   s$   |  ] \ } } } | j  ƒ  Vq d  S(   N(   t   keys(   t   .0t   st   tt   d(    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pys	   <genexpr>í   s    c            sG   i  |  ]= } g  ˆ  D]' \ } } } | j  | t d  ƒ ƒ ^ q | “ q S(   t   nan(   t   gett   float(   R/   t   kR0   R1   R2   (   t   edgelist(    s6   lib/python2.7/site-packages/networkx/convert_matrix.pys
   <dictcomp>î   s   	(   R   R   t   edgest   TrueR   t   uniont   updateR   (   R   R,   R-   R   R   R   R   R0   R1   R2   t   source_nodest   target_nodest   all_keyst	   edge_attrt   edgelistdict(    (   R7   s6   lib/python2.7/site-packages/networkx/convert_matrix.pyR   Â   s    $""
c         C   s¿  t  j d | ƒ } | d k r@ | j t |  | |  | ƒ ƒ | S| t k rƒ g  |  j D]$ } | | k	 rV | | k	 rV | ^ qV } n' t | t t	 f ƒ r¡ | } n	 | g } y' t g  | D] } |  | ^ q· Œ  }	 Wn2 t
 t f k
 r}
 d | } t  j | ƒ ‚ n Xx² t |  | |  | |	 ƒ D]– \ } } } | j | | ƒ | j ƒ  rt | | | ƒ } | | | | j d „  t | | ƒ Dƒ ƒ q!| | | j d „  t | | ƒ Dƒ ƒ 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 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 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 constructor, optional (default=nx.Graph)
       Graph type to create. If graph instance, then cleared before populated.

    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'

    i    s   Invalid edge_attr argument: %sc         s   s!   |  ] \ } } | | f Vq d  S(   N(    (   R/   t   attrt   val(    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pys	   <genexpr>V  s    c         s   s!   |  ] \ } } | | f Vq d  S(   N(    (   R/   RA   RB   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pys	   <genexpr>X  s    N(   R    t   empty_graphR   t   add_edges_fromt   zipR9   R   t
   isinstanceR   t   tuplet   KeyErrort	   TypeErrorR!   t   add_edget   is_multigrapht   maxR;   (   R(   R,   R-   R?   R   t   gt   ct   colst   colt   eattrst   eR)   R0   R1   t   attrst   key(    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyR   õ   s*    H7		'
*/,c   
      C   sU   d d l  } t |  d | d | d | d | d | d | ƒ} | j | d | ƒ}	 |	 S(	   s¬  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
    >>> try:
    ...    np.set_printoptions(legacy="1.13")
    ... except TypeError:
    ...    pass
    >>> 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ÿÿÿÿNR   R   R   R   R   R   (   t   numpyR   t   asmatrix(
   R   R   R   R   R   R   R   t   npR+   R   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyR   ]  s    _	c            s!  d d l  } i t d 6t d 6t d 6t d 6t d 6t d 6d	 d
 6‰ y t d ƒ } t ˆ d <Wn t k
 rz t ˆ d <n Xt	 j
 d | ƒ } ˆ  j \ } } | | k rÇ t	 j d d ˆ  j f ƒ ‚ n  ˆ  j } y ˆ | j ‰ Wn t d | ƒ ‚ n X| j t | ƒ ƒ t d „  t | j ˆ  ƒ j ƒ  Œ  ƒ }	 ˆ d	 k r‚t d „  ˆ  j j j ƒ  Dƒ ƒ ‰ ‡  ‡ ‡ f d †  |	 Dƒ }
 nb ˆ t k rË| j ƒ  rË| rËt j j } | ‡  f d †  |	 Dƒ ƒ }
 n ‡  ‡ f d †  |	 Dƒ }
 | j ƒ  r| j ƒ  rd „  |
 Dƒ }
 n  | j |
 ƒ | S(   s  Return a graph from numpy matrix.

    The numpy matrix is interpreted as an adjacency matrix for the graph.

    Parameters
    ----------
    A : numpy matrix
        An adjacency matrix representation of a graph

    parallel_edges : Boolean
        If 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 False, then the entries in the adjacency 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.

    Notes
    -----
    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.

    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.

    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_numpy_matrix, to_numpy_recarray

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

    >>> import numpy as np
    >>> A = np.matrix([[1, 1], [2, 1]])
    >>> G = nx.from_numpy_matrix(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 = 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` 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 = 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ÿÿÿÿNt   ft   it   ut   bRN   t   St   voidt   ViÝ  t   Ui    s   Adjacency matrix is not square.s   nx,ny=%ss   Unknown numpy data type: %sc         S   s   t  |  d ƒ t  |  d ƒ f S(   Ni    i   (   t   int(   RR   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyt   <lambda>4  s    c         s   s*   |  ]  \ } \ } } | | | f Vq d  S(   N(    (   R/   t   nameR   t   offset(    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pys	   <genexpr>9  s    c      	   3   sG   |  ]= \ } } | | ‡ f d  †  t  ˆ ˆ  | | f ƒ Dƒ f Vq d S(   c            s5   i  |  ]+ \ \ } } } } ˆ  | j  | ƒ | “ q S(    (   t   kind(   R/   t   _R   Rb   RB   (   t   kind_to_python_type(    s6   lib/python2.7/site-packages/networkx/convert_matrix.pys
   <dictcomp>;  s   	N(   RE   (   R/   RZ   t   v(   R+   t   fieldsRf   (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pys	   <genexpr>;  s   c         3   s>   |  ]4 \ ‰  ‰ ‡  ‡ f d  †  t  ˆ ˆ  ˆ f ƒ Dƒ Vq d S(   c         3   s'   |  ] } ˆ  ˆ t  d  d ƒ f Vq d S(   R   i   N(   R%   (   R/   R2   (   RZ   Rg   (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pys	   <genexpr>K  s    N(   t   range(   R/   (   R+   (   RZ   Rg   s6   lib/python2.7/site-packages/networkx/convert_matrix.pys	   <genexpr>K  s   c      	   3   s=   |  ]3 \ } } | | t  d  ˆ ˆ  | | f ƒ ƒ f Vq d S(   R   N(   R%   (   R/   RZ   Rg   (   R+   t   python_type(    s6   lib/python2.7/site-packages/networkx/convert_matrix.pys	   <genexpr>N  s   c         s   s3   |  ]) \ } } } | | k r | | | f Vq d  S(   N(    (   R/   RZ   Rg   R2   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pys	   <genexpr>Y  s    (   RU   R5   R`   t   boolt   complext   strt   chrt
   ValueErrort   unicodeR    RC   t   shapeR!   R   Rd   RI   t   add_nodes_fromRi   t   mapRE   t   asarrayt   nonzerot   sortedRh   t   itemsRK   t	   itertoolst   chaint   from_iterablet   is_directedRD   (   R+   t   parallel_edgesR   RW   t   blurbR   t   nt   mt   dtR8   t   triplesRy   (    (   R+   Rh   Rf   Rj   s6   lib/python2.7/site-packages/networkx/convert_matrix.pyR   Å  sR    S

				
	t
   multigraphc         C   sž  | d k r d t f g } n  d d l } | d k rE t |  ƒ } n  t | ƒ } t | ƒ t | ƒ k r d } t j | ƒ ‚ n  t | ƒ } |  j ƒ  } t	 t
 | t | ƒ ƒ ƒ }	 | j | | f d | d | ƒ}
 |
 j j } x© |  j d t ƒ D]• \ } } } | | k rõ | | k rõ |	 | |	 | } } t g  | D] } | | ^ q;ƒ } | |
 | | f <| rŠ|
 | | f |
 | | f <qŠqõ qõ W|
 j | j ƒ S(   s(  Return the graph adjacency matrix as a NumPy recarray.

    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 named dtype used to initialize the NumPy recarray.
        The data type names are assumed to be keys in the graph edge attribute
        dictionary.

    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.

    Returns
    -------
    M : NumPy recarray
       The graph with specified edge data as a Numpy recarray

    Notes
    -----
    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`.

    Examples
    --------
    >>> 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]]

    R   iÿÿÿÿNs4   Ambiguous ordering: `nodelist` contained duplicates.R   R   R   (   R   R5   RU   R   R   t   lenR    R!   R{   R%   RE   Ri   t   zerosR   t   namesR8   R9   RG   t   viewt   recarray(   R   R   R   R   RW   t   nodesetR)   t   nlent
   undirectedR   R   R…   RZ   Rg   RS   RY   t   jR~   R"   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyR   ^  s,    .!"#$t   csrc            s?  d d l  m } | d k r+ t |  ƒ } n  t | ƒ } | d k rU t j d ƒ ‚ n  t | ƒ t t | ƒ ƒ k r‹ d } t j | ƒ ‚ n  t t	 | t
 | ƒ ƒ ƒ ‰  t	 ‡  ‡ f d †  |  j | d t ƒDƒ Œ  } y | \ }	 }
 } Wn% t k
 rg  g  g  }	 }
 } n X|  j ƒ  rK| j | |	 |
 f f d | | f d	 | ƒ} n² | | } |	 |
 } |
 |	 } t t j |  d t ƒƒ } | rÐt	 ‡  ‡ f d
 †  | Dƒ Œ  \ } } | | 7} | | 7} | | 7} n  | j | | | f f d | | f d	 | ƒ} y | j | ƒ SWn* t t f k
 r:t j d | ƒ ‚ n Xd 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ÿÿÿÿ(   t   sparsei    s   Graph has no nodes or edgess4   Ambiguous ordering: `nodelist` contained duplicates.c         3   sS   |  ]I \ } } } | ˆ  k r | ˆ  k r ˆ  | ˆ  | | j  ˆ d  ƒ f Vq d S(   i   N(   R4   (   R/   RZ   Rg   R2   (   R   R   (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pys	   <genexpr>  s   R   Rq   R   c         3   sM   |  ]C \ } } } | ˆ  k r | ˆ  k r ˆ  | | j  ˆ d  ƒ f Vq d S(   i   N(   R4   (   R/   RZ   Rg   R2   (   R   R   (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pys	   <genexpr>  s   s    Unknown sparse matrix format: %sN(   t   scipyR   R   R   Rƒ   R    R!   R   R%   RE   Ri   R8   R9   Ro   R{   t
   coo_matrixt   selfloop_edgest   asformatt   AttributeError(   R   R   R   R   t   formatR   R‰   R)   t   coefficientst   rowRP   R   R   R2   t   rRN   t	   selfloopst
   diag_indext	   diag_data(    (   R   R   s6   lib/python2.7/site-packages/networkx/convert_matrix.pyR	   ¦  sD    R




-c         c   s   |  j  d } |  j |  j |  j } } } xP t | ƒ D]B } x9 t | | | | d ƒ D] } | | | | | f VqY Wq7 Wd S(   su   Converts a SciPy sparse matrix in **Compressed Sparse Row** format to
    an iterable of weighted edge triples.

    i    i   N(   Rq   R   t   indicest   indptrRi   (   R+   t   nrowsR   Rš   R›   RY   R‹   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyt   _csr_gen_triples(  s
    "c         c   s   |  j  d } |  j |  j |  j } } } xP t | ƒ D]B } x9 t | | | | d ƒ D] } | | | | | f VqY Wq7 Wd S(   sx   Converts a SciPy sparse matrix in **Compressed Sparse Column** format to
    an iterable of weighted edge triples.

    i   N(   Rq   R   Rš   R›   Ri   (   R+   t   ncolsR   Rš   R›   RY   R‹   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyt   _csc_gen_triples4  s
    "c         C   s-   |  j  |  j |  j } } } t | | | ƒ S(   sj   Converts a SciPy sparse matrix in **Coordinate** format to an iterable
    of weighted edge triples.

    (   R•   RP   R   RE   (   R+   R•   RP   R   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyt   _coo_gen_triples@  s    c         c   s5   x. |  j  ƒ  D]  \ \ } } } | | | f Vq Wd S(   sr   Converts a SciPy sparse matrix in **Dictionary of Keys** format to an
    iterable of weighted edge triples.

    N(   Rw   (   R+   R–   RN   Rg   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyt   _dok_gen_triplesI  s    c         C   s[   |  j  d k r t |  ƒ S|  j  d k r2 t |  ƒ S|  j  d k rK t |  ƒ 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).

    RŒ   t   csct   dok(   R“   R   RŸ   R¡   R    t   tocoo(   R+   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyt   _generate_weighted_edgesR  s    


c   	      C   sô   t  j d | ƒ } |  j \ } } | | k rI t  j d |  j f ƒ ‚ n  | j t | ƒ ƒ t |  ƒ } |  j j d k r± | j	 ƒ  r± | r± t
 j j } | d „  | Dƒ ƒ } n  | j	 ƒ  rÝ | j ƒ  rÝ d „  | Dƒ } n  | j | d | ƒ| S(	   sv	  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 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
    -----

    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_matrix(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_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` 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_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}})

    i    s(   Adjacency matrix is not square. nx,ny=%sRY   RZ   c         3   s7   |  ]- \ ‰  ‰ } ‡  ‡ f d  †  t  | ƒ Dƒ Vq d S(   c         3   s   |  ] } ˆ  ˆ d  f Vq d S(   i   N(    (   R/   R2   (   RZ   Rg   (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pys	   <genexpr>¹  s    N(   Ri   (   R/   t   w(    (   RZ   Rg   s6   lib/python2.7/site-packages/networkx/convert_matrix.pys	   <genexpr>¹  s    c         s   s3   |  ]) \ } } } | | k r | | | f Vq d  S(   N(    (   R/   RZ   Rg   R2   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pys	   <genexpr>Ã  s    R   (   RY   RZ   (   R    RC   Rq   R!   Rr   Ri   R¥   R   Rd   RK   Rx   Ry   Rz   R{   t   add_weighted_edges_from(	   R+   R|   R   t   edge_attributeR   R~   R   R   Ry   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyR   c  s    ?$	c         C   sƒ  d d l  } | d k r' t |  ƒ } n  t | ƒ } t | ƒ t | ƒ k rc d }	 t j |	 ƒ ‚ n  t | ƒ }
 |  j ƒ  } t t	 | t
 |
 ƒ ƒ ƒ } |  j ƒ  rÀ| j |
 |
 f | j d | ƒ} i | j t 6| j t 6| j t 6} y | | } Wn t d ƒ ‚ n XxH|  j d t ƒ D]š \ } } } | | k r| | k r| | | | } } | j | d ƒ } | | | | | f g ƒ | | | f <| r¹| | | f | | | f <q¹qqWn— | j |
 |
 f | j d | ƒ} xs |  j ƒ  D]e \ } } xV | j ƒ  D]H \ } } y( | j | d ƒ | | | | | f <Wqt k
 rNqXqWqîW| | | j | ƒ <| j | d | ƒ} | S(	   sŸ  Return 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 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 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

    See Also
    --------
    from_numpy_array

    Notes
    -----
    Entries in the adjacency matrix 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 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
    >>> try:
    ...    np.set_printoptions(legacy="1.13")
    ... except TypeError:
    ...    pass
    >>> 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ÿÿÿÿNs4   Ambiguous ordering: `nodelist` contained duplicates.R   s*   multigraph_weight must be sum, min, or maxR   i   R   (   RU   R   R   R   Rƒ   R    R!   R{   R%   RE   Ri   RK   t   fullR3   t   nansumt   sumt   nanmint   mint   nanmaxRL   Ro   R8   R9   R4   t	   adjacencyRw   RH   t   isnanRt   (   R   R   R   R   R   R   R   RW   Rˆ   R)   R‰   RŠ   R   R+   t   operatort   opRZ   Rg   RS   RY   R‹   t   e_weightt   nbrdictR2   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyR   È  sD    _"!$"&'!(c         C   s   t  |  d | d | ƒS(   sw  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 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.

    Notes
    -----
    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 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

    R|   R   (   R   (   R+   R|   R   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyR
   v  s    Tc         C   s†   d d l  m } y d d  l } Wn | d ƒ ‚ n Xy d d  l } Wn | d ƒ ‚ n Xy d d  l } Wn | d ƒ ‚ n Xd  S(   Niÿÿÿÿ(   t   SkipTests   NumPy not availables   SciPy not availables   Pandas not available(   t   noseRµ   RU   RŽ   R   (   t   moduleRµ   RU   RŽ   R   (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyt   setup_moduleÏ  s    (   t   __doc__Rx   t   networkxR    t   networkx.utilsR    t   __all__R   R«   R   R   R   R   R   R'   R   R   R	   R   RŸ   R    R¡   R¥   R   R   R
   R¸   (    (    (    s6   lib/python2.7/site-packages/networkx/convert_matrix.pyt   <module>   sD   	Y>	2	g	g™	G							d	­Y