summaryrefslogtreecommitdiff
path: root/networkx/convert.py
blob: 526841152f8c19caa33b51a7654c995e72c344a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
"""
Convert NetworkX graphs to and from other formats.

from_whatever attemps to guess the input format

Create a 10 node random digraph

>>> from networkx import *
>>> import numpy
>>> a=numpy.reshape(numpy.random.random_integers(0,1,size=100),(10,10))
>>> D=from_whatever(D,create_using=DiGraph()) # or D=DiGraph(a) 


For graphviz formats see networkx.drawing.nx_pygraphviz
or networkx.drawing.nx_pydot.

$Id$
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
#    Copyright (C) 2006 by 
#    Aric Hagberg <hagberg@lanl.gov>
#    Dan Schult <dschult@colgate.edu>
#    Pieter Swart <swart@lanl.gov>
#    Distributed under the terms of the GNU Lesser General Public License
#    http://www.gnu.org/copyleft/lesser.html

import networkx

def from_whatever(thing,create_using=None):
    """Attempt to make a NetworkX graph from an known type.

    Current known types are:

       any NetworkX graph
       dict-of-dicts
       dist-of-lists
       numpy matrix
       numpy ndarray
       scipy sparse matrix
       pygraphviz agraph

    """
    if create_using is None:
        G=networkx.Graph()
    else:
        try:
            G=create_using
            G.clear()
        except:
            raise TypeError("Input graph is not a NetworkX graph type.")
        
    # pygraphviz  agraph
    if hasattr(thing,"is_strict"):
        try:
            return networkx.from_agraph(thing,create_using=create_using)
        except:
            raise
#            raise networkx.NetworkXError,\
#                  "Input is not a correct pygraphviz graph."

    # NX graph
    if hasattr(thing,"add_node"):
        try:
            return from_dict_of_dicts(thing.adj,create_using=create_using)
        except:
            raise networkx.NetworkXError,\
                  "Input is not a correct NetworkX graph."

    # dict of dicts/lists
    if isinstance(thing,dict):
        try:
            return from_dict_of_dicts(thing,create_using=create_using)
        except:
            try:
                return from_dict_of_lists(thing,create_using=create_using)
            except:
                raise TypeError("Input is not known type.")

    # numpy matrix or ndarray 

    try:
        import numpy
        if isinstance(thing,numpy.core.defmatrix.matrix) or \
               isinstance(thing,numpy.ndarray):
            try:
                return from_numpy_matrix(thing,create_using=create_using)
            except:
                raise networkx.NetworkXError,\
                      "Input is not a correct numpy matrix or array."
    except ImportError:
        pass # fail silently

    # scipy sparse matrix - any format
    try:
        import scipy
        if hasattr(thing,"format"):
            try:
                return from_scipy_sparse_matrix(thing,create_using=create_using)
            except:
                raise networkx.NetworkXError, \
                      "Input is not a correct scipy sparse matrix type."
    except ImportError:
        pass # fail silently


    raise networkx.NetworkXError, \
          "Input is not a known data type for conversion."

    return 


def to_dict_of_lists(G,nodelist=None):
    """Return graph G as a Python dict of lists.

    If nodelist is defined return a dict of lists with only those nodes.

    Completely ignores edge data for XGraph and XDiGraph.

    """
    if nodelist is None:
        nodelist=G.nodes()

    # is this a XGraph or XDiGraph?
    if hasattr(G,'allow_multiedges')==True:
        xgraph=True
    else:
        xgraph=False

    d = {}

    for n in nodelist:
        d[n]=G.neighbors(n)
    return d            

def from_dict_of_lists(d,create_using=None):
    """Return a NetworkX graph G from a Python dict of lists.

    """
    if create_using is None:
        G=networkx.Graph()
    else:
        try:
            G=create_using
            G.clear()
        except:
            raise TypeError("Input graph is not a networkx graph type")

    for node in d:
        for nbr in d[node]:
            G.add_edge(node,nbr)
    G.add_nodes_from(d.keys())        
    return G                         


def to_dict_of_dicts(G,nodelist=None,weighted=False):
    """Return graph G as a Python dictionary of dictionaries.

    If nodelist is defined return a dict of dicts with only those nodes.
    
    """
    if nodelist is None:
        nodelist=G.nodes()
    if not weighted or not hasattr(G,"get_edge"):
        w=lambda x,y:1
    else:
        w=lambda x,y:G.get_edge(x,y)

    d = {}
    for u in nodelist:
        d[u]={}
        for v in G.neighbors(u):
            d[u][v]=w(u,v)
    return d            


def from_dict_of_dicts(d,create_using=None):
    """Return a NetworkX graph G from a Python dictionary of dictionaries.

    """
    if create_using is None:
        G=networkx.Graph()
    else:
        try:
            G=create_using
            G.clear()
        except:
            raise TypeError("Input graph is not a networkx graph type")

    # is this a XGraph or XDiGraph?
    if hasattr(G,'allow_multiedges')==True:
        xgraph=True
    else:
        xgraph=False

    for u in d:
        for v in d[u]:
            if xgraph:
                G.add_edge((u,v,d[u][v]))
            else:
                G.add_edge(u,v)

    G.add_nodes_from(d.keys())        
    return G                         



def to_numpy_matrix(G,nodelist=None):
    """Return adjacency matrix of graph as a numpy matrix.

    If nodelist is defined return adjacency matrix with nodes in nodelist
    in the order specified.  If not the ordering is whatever order
    the method G.nodes() produces.

    For Graph/DiGraph types which have no edge data 
    The value of the entry A[u,v] is one if there is an edge u-v
    and zero otherwise.

    For XGraph/XDiGraph the edge data is assumed to be a weight and be
    able to be converted to a valid numpy type (e.g. an int or a
    float).  The value of the entry A[u,v] is the weight given by
    get_edge(u,v) one if there is an edge u-v and zero otherwise.

    Graphs with multi-edges are not handled.

    """
    try:
        import numpy
    except ImportError:
        raise ImportError, \
              "Import Error: not able to import numpy: http://numpy.scipy.org "

    if hasattr(G,"multiedges"):
        if G.multiedges==True:
            raise ImportError, \
                  "Not allowed with for graphs with multiedges."

    if nodelist is None:
        nodelist=G.nodes()
    nlen=len(nodelist)    
    index=dict(zip(nodelist,range(nlen)))# dict mapping vertex name to position
    A = numpy.asmatrix(numpy.zeros((nlen,nlen)))
    for e in G.edges_iter(nodelist):
        u=e[0]
        v=e[1]
        if len(e)==2:
            d=1
        else:
            d=e[2]
        A[index[u],index[v]]=d
        if not G.is_directed():
            A[index[v],index[u]]=d
    return A            

def from_numpy_matrix(A,create_using=None):
    """Return networkx graph G from numpy matrix adjacency list. 

    >>> G=from_numpy_matrix(A)

    """
    # This should never fail if you have created a numpy matrix with numpy...  
    try:
        import numpy
    except ImportError:
        raise ImportError, \
              "Import Error: not able to import numpy: http://numpy.scipy.org "

    if create_using is None:
        G=networkx.Graph()
    else:
        try:
            G=create_using
            G.clear()
        except:
            raise TypeError("Input graph is not a networkx graph type")

    # is this a XGraph or XDiGraph?
    if hasattr(G,'allow_multiedges')==True:
        xgraph=True
    else:
        xgraph=False

    nx,ny=A.shape

    try:
        nx==ny
    except:
        raise networkx.NetworkXError, \
              "Adjacency matrix is not square. nx,ny=%s",A.shape

    G.add_nodes_from(range(nx)) # make sure we get isolated nodes

    x,y=numpy.asarray(A).nonzero()         
    for (u,v) in zip(x,y):        
        if xgraph:
            G.add_edge(u,v,A[u,v])
        else:
            G.add_edge(u,v)                
    return G


def to_scipy_sparse_matrix(G,nodelist=None):
    """Return adjacency matrix of graph as a scipy sparse matrix.

    Uses lil_matrix format.  To convert to other formats see
    scipy.sparse documentation.

    If nodelist is defined return adjacency matrix with nodes in nodelist
    in the order specified.  If not the ordering is whatever order
    the method G.nodes() produces.

    For Graph/DiGraph types which have no edge data 
    The value of the entry A[u,v] is one if there is an edge u-v
    and zero otherwise.

    For XGraph/XDiGraph the edge data is assumed to be a weight and be
    able to be converted to a valid numpy type (e.g. an int or a
    float).  The value of the entry A[u,v] is the weight given by
    get_edge(u,v) one if there is an edge u-v and zero otherwise.

    Graphs with multi-edges are not handled.

    >>> A=scipy_sparse_matrix(G)
    >>> A.tocsr() # convert to compressed row storage

    """
    try:
        from scipy import sparse
    except ImportError:
        raise ImportError, \
              """Import Error: not able to import scipy sparse:
              see http://scipy.org""" 

    if hasattr(G,"multiedges"):
        if G.multiedges==True:
            raise ImportError, \
                  "Not allowed with for graphs with multiedges."

    if nodelist is None:
        nodelist=G.nodes()
    nlen=len(nodelist)    
    index=dict(zip(nodelist,range(nlen)))# dict mapping vertex name to position
    A = sparse.lil_matrix((nlen,nlen))
    for e in G.edges_iter(nodelist):
        u=e[0]
        v=e[1]
        if len(e)==2:
            d=1
        else:
            d=e[2]
        A[index[u],index[v]]=d
        if not G.is_directed():
            A[index[v],index[u]]=d
    return A            


def from_scipy_sparse_matrix(A,create_using=None):
    """Return networkx graph G from scipy scipy sparse matrix
    adjacency list. 

    >>> G=from_scipy_sparse_matrix(A)

    """
    if create_using is None:
        G=networkx.Graph()
    else:
        try:
            G=create_using
            G.clear()
        except:
            raise TypeError("Input graph is not a networkx graph type")

    # is this a XGraph or XDiGraph?
    if hasattr(G,'allow_multiedges')==True:
        xgraph=True
    else:
        xgraph=False

    # convert everythin to coo - not the most efficient        
    AA=A.tocoo()
    nx,ny=AA.shape
    try:
        nx==ny
    except:
        raise networkx.NetworkXError, \
              "Adjacency matrix is not square. nx,ny=%s",A.shape


    G.add_nodes_from(range(nx)) # make sure we get isolated nodes
    for i in range(AA.nnz):
        e=AA.rowcol(i)
        if xgraph:
            e=(e[0],e[1],AA.getdata(i))
        G.add_edge(e)
    return G


def _test_suite():
    import doctest
    suite = doctest.DocFileSuite('tests/convert.txt',
                                 package='networkx')
    return suite

def _test_suite_numpy():
    import doctest
    suite = doctest.DocFileSuite('tests/convert_numpy.txt',
                                     package='networkx')
    return suite

def _test_suite_scipy():
    import doctest
    suite = doctest.DocFileSuite('tests/convert_scipy.txt',
                                     package='networkx')
    return suite




if __name__ == "__main__":
    import os 
    import sys
    import unittest
    if sys.version_info[:2] < (2, 4):
        print "Python version 2.4 or later required for tests (%d.%d detected)." %  sys.version_info[:2]
        sys.exit(-1)
    # directory of networkx package (relative to this)
    nxbase=sys.path[0]+os.sep+os.pardir
    sys.path.insert(0,nxbase) # prepend to search path
    unittest.TextTestRunner().run(_test_suite())
    try:
        import numpy
        unittest.TextTestRunner().run(_test_suite_numpy())
    except ImportError: 
        pass
    try:
        import scipy
        unittest.TextTestRunner().run(_test_suite_scipy())
    except ImportError: 
        pass