~ubuntu-branches/ubuntu/utopic/python-networkx/utopic

« back to all changes in this revision

Viewing changes to networkx/linalg/graphmatrix.py

  • Committer: Package Import Robot
  • Author(s): Sandro Tosi
  • Date: 2012-08-11 12:41:30 UTC
  • mfrom: (1.4.1) (5.1.13 sid)
  • Revision ID: package-import@ubuntu.com-20120811124130-whr6uso7fncyg8bi
Tags: 1.7-1
* New upstream release
* debian/patches/changeset_*
  - removed, included upstream

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""
 
2
Adjacency matrix and incidence matrix of graphs.
 
3
"""
 
4
#    Copyright (C) 2004-2011 by 
 
5
#    Aric Hagberg <hagberg@lanl.gov>
 
6
#    Dan Schult <dschult@colgate.edu>
 
7
#    Pieter Swart <swart@lanl.gov>
 
8
#    All rights reserved.
 
9
#    BSD license.
 
10
import networkx as nx
 
11
__author__ = "\n".join(['Aric Hagberg (hagberg@lanl.gov)',
 
12
                        'Pieter Swart (swart@lanl.gov)',
 
13
                        'Dan Schult(dschult@colgate.edu)'])
 
14
 
 
15
__all__ = ['incidence_matrix',
 
16
           'adj_matrix', 'adjacency_matrix',
 
17
           ]
 
18
 
 
19
 
 
20
def incidence_matrix(G, nodelist=None, edgelist=None, 
 
21
                     oriented=False, weight=None):
 
22
    """Return incidence matrix of G.
 
23
 
 
24
    The incidence matrix assigns each row to a node and each column to an edge.
 
25
    For a standard incidence matrix a 1 appears wherever a row's node is 
 
26
    incident on the column's edge.  For an oriented incidence matrix each
 
27
    edge is assigned an orientation (arbitrarily for undirected and aligning to
 
28
    direction for directed).  A -1 appears for the tail of an edge and 1 
 
29
    for the head of the edge.  The elements are zero otherwise.
 
30
    
 
31
    Parameters
 
32
    ----------
 
33
    G : graph
 
34
       A NetworkX graph 
 
35
 
 
36
    nodelist : list, optional   (default= all nodes in G)
 
37
       The rows are ordered according to the nodes in nodelist.
 
38
       If nodelist is None, then the ordering is produced by G.nodes().
 
39
 
 
40
    edgelist : list, optional (default= all edges in G) 
 
41
       The columns are ordered according to the edges in edgelist.
 
42
       If edgelist is None, then the ordering is produced by G.edges().
 
43
 
 
44
    oriented: bool, optional (default=False)
 
45
       If True, matrix elements are +1 or -1 for the head or tail node 
 
46
       respectively of each edge.  If False, +1 occurs at both nodes.
 
47
 
 
48
    weight : string or None, optional (default=None)
 
49
       The edge data key used to provide each value in the matrix.
 
50
       If None, then each edge has weight 1.  Edge weights, if used,
 
51
       should be positive so that the orientation can provide the sign.
 
52
 
 
53
    Returns
 
54
    -------
 
55
    A : NumPy matrix
 
56
      The incidence matrix of G.
 
57
 
 
58
    Notes
 
59
    -----
 
60
    For MultiGraph/MultiDiGraph, the edges in edgelist should be 
 
61
    (u,v,key) 3-tuples.
 
62
 
 
63
    "Networks are the best discrete model for so many problems in 
 
64
    applied mathematics" [1]_.
 
65
 
 
66
    References
 
67
    ----------
 
68
    .. [1] Gil Strang, Network applications: A = incidence matrix,
 
69
       http://academicearth.org/lectures/network-applications-incidence-matrix
 
70
    """
 
71
    try:
 
72
        import numpy as np
 
73
    except ImportError:
 
74
        raise ImportError(
 
75
          "incidence_matrix() requires numpy: http://scipy.org/ ")
 
76
    if nodelist is None:
 
77
        nodelist = G.nodes()
 
78
    if edgelist is None:
 
79
        if G.is_multigraph():
 
80
            edgelist = G.edges(keys=True)
 
81
        else:
 
82
            edgelist = G.edges()
 
83
    A = np.zeros((len(nodelist),len(edgelist)))
 
84
    node_index = dict( (node,i) for i,node in enumerate(nodelist) )
 
85
    for ei,e in enumerate(edgelist):
 
86
        (u,v) = e[:2]
 
87
        if u == v: continue  # self loops give zero column
 
88
        try:
 
89
            ui = node_index[u]
 
90
            vi = node_index[v]
 
91
        except KeyError:
 
92
            raise NetworkXError('node %s or %s in edgelist '
 
93
                                'but not in nodelist"%(u,v)')
 
94
        if weight is None:
 
95
            wt = 1
 
96
        else:
 
97
            if G.is_multigraph():
 
98
                ekey = e[2]
 
99
                wt = G[u][v][ekey].get(weight,1)
 
100
            else:
 
101
                wt = G[u][v].get(weight,1)
 
102
        if oriented:
 
103
            A[ui,ei] = -wt
 
104
            A[vi,ei] = wt
 
105
        else:
 
106
            A[ui,ei] = wt
 
107
            A[vi,ei] = wt
 
108
    return np.asmatrix(A)
 
109
 
 
110
def adjacency_matrix(G, nodelist=None, weight='weight'):
 
111
    """Return adjacency matrix of G.
 
112
 
 
113
    Parameters
 
114
    ----------
 
115
    G : graph
 
116
       A NetworkX graph 
 
117
 
 
118
    nodelist : list, optional       
 
119
       The rows and columns are ordered according to the nodes in nodelist.
 
120
       If nodelist is None, then the ordering is produced by G.nodes().
 
121
 
 
122
    weight : string or None, optional (default='weight')
 
123
       The edge data key used to provide each value in the matrix.
 
124
       If None, then each edge has weight 1.
 
125
 
 
126
    Returns
 
127
    -------
 
128
    A : numpy matrix
 
129
      Adjacency matrix representation of G.
 
130
 
 
131
    Notes
 
132
    -----
 
133
    If you want a pure Python adjacency matrix representation try
 
134
    networkx.convert.to_dict_of_dicts which will return a
 
135
    dictionary-of-dictionaries format that can be addressed as a
 
136
    sparse matrix.
 
137
 
 
138
    For MultiGraph/MultiDiGraph, the edges weights are summed.
 
139
    See to_numpy_matrix for other options.
 
140
 
 
141
    See Also
 
142
    --------
 
143
    to_numpy_matrix
 
144
    to_dict_of_dicts
 
145
    """
 
146
    return nx.to_numpy_matrix(G,nodelist=nodelist,weight=weight)
 
147
 
 
148
adj_matrix=adjacency_matrix
 
149
 
 
150
# fixture for nose tests
 
151
def setup_module(module):
 
152
    from nose import SkipTest
 
153
    try:
 
154
        import numpy
 
155
    except:
 
156
        raise SkipTest("NumPy not available")