forked from pmatiello/python-graph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.py
More file actions
474 lines (349 loc) · 12.7 KB
/
Copy pathgraph.py
File metadata and controls
474 lines (349 loc) · 12.7 KB
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# Copyright (c) 2007-2009 Pedro Matiello <pmatiello@gmail.com>
# Johannes Reinhardt <jreinhardt@ist-dein-freund.de>
# Nathan Davis <davisn90210@gmail.com>
# Zsolt Haraszti <zsolt@drawwell.net>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
"""
Graph class
"""
# Imports
#from pygraph.algorithms import *
#from pygraph.algorithms import filters
from pygraph.algorithms import traversal
from pygraph.classes.exceptions import AdditionError
class graph (object):
"""
Graph class.
Graphs are built of nodes and edges.
@sort: __init__, __getitem__, __iter__, __len__, __str__, add_edge, add_edge_attribute,
add_graph, add_node, add_node_attribute, add_nodes, add_spanning_tree, complete, del_edge,
del_node, edges, edge_attributes, edge_label, edge_weight, node_attributes,
has_edge, has_node, inverse, neighbors, node_order, nodes, set_edge_label,
set_edge_weight, traversal
"""
def __init__(self):
"""
Initialize a graph.
"""
self.node_neighbors = {} # Pairing: Node -> Neighbors
self.edge_properties = {} # Pairing: Edge -> (Label, Weight)
self.node_attr = {} # Pairing: Node -> Attributes
self.edge_attr = {} # Pairing: Edge -> Attributes
def __str__(self):
"""
Return a string representing the graph when requested by str() (or print).
@rtype: string
@return: String representing the graph.
"""
return "<graph object " + str(self.nodes()) + " " + str(self.edges()) + ">"
def __len__(self):
"""
Return the order of the graph when requested by len().
@rtype: number
@return: Size of the graph.
"""
return len(self.node_neighbors)
def __iter__(self):
"""
Return a iterator passing through all nodes in the graph.
@rtype: iterator
@return: Iterator passing through all nodes in the graph.
"""
for each in self.node_neighbors.keys():
yield each
def __getitem__(self, node):
"""
Return a iterator passing through all neighbors of the given node.
@rtype: iterator
@return: Iterator passing through all neighbors of the given node.
"""
for each in self.node_neighbors[node]:
yield each
def nodes(self):
"""
Return node list.
@rtype: list
@return: Node list.
"""
return list(self.node_neighbors.keys())
def neighbors(self, node):
"""
Return all nodes that are directly accessible from given node.
@type node: node
@param node: Node identifier
@rtype: list
@return: List of nodes directly accessible from given node.
"""
return self.node_neighbors[node]
def edges(self):
"""
Return all edges in the graph.
@rtype: list
@return: List of all edges in the graph.
"""
return list(self.edge_properties.keys())
def has_node(self, node):
"""
Return whether the requested node exists.
@type node: node
@param node: Node identifier
@rtype: boolean
@return: Truth-value for node existence.
"""
return node in self.node_neighbors
def add_node(self, node, attrs=[]):
"""
Add given node to the graph.
@attention: While nodes can be of any type, it's strongly recommended to use only
numbers and single-line strings as node identifiers if you intend to use write().
@type node: node
@param node: Node identifier.
@type attrs: list
@param attrs: List of node attributes specified as (attribute, value) tuples.
"""
if (not node in self.node_neighbors):
self.node_neighbors[node] = []
self.node_attr[node] = attrs
else:
raise AdditionError("Node %s already in graph" % node)
def add_nodes(self, nodelist):
"""
Add given nodes to the graph.
@attention: While nodes can be of any type, it's strongly recommended to use only
numbers and single-line strings as node identifiers if you intend to use write().
@type nodelist: list
@param nodelist: List of nodes to be added to the graph.
"""
for each in nodelist:
self.add_node(each)
def add_edge(self, u, v, wt=1, label='', attrs=[]):
"""
Add an edge (u,v) to the graph connecting nodes u and v.
@type u: node
@param u: One node.
@type v: node
@param v: Other node.
@type wt: number
@param wt: Edge weight.
@type label: string
@param label: Edge label.
@type attrs: list
@param attrs: List of node attributes specified as (attribute, value) tuples.
"""
if (v not in self.node_neighbors[u] and u not in self.node_neighbors[v]):
self.node_neighbors[u].append(v)
self.node_neighbors[v].append(u)
self.edge_properties[(u, v)] = [label, wt]
self.edge_properties[(v, u)] = [label, wt]
self.edge_attr[(u, v)] = attrs
self.edge_attr[(v, u)] = attrs
else:
raise AdditionError("Edge (%s, %s) already in graph" % (u, v))
def del_node(self, node):
"""
Remove a node from the graph.
@type node: node
@param node: Node identifier.
"""
for each in list(self.neighbors(node)):
if (each != node):
self.del_edge(each, node)
del(self.node_neighbors[node])
del(self.node_attr[node])
def del_edge(self, u, v):
"""
Remove an edge (u, v) from the graph.
@type u: node
@param u: One node.
@type v: node
@param v: Other node.
"""
self.node_neighbors[u].remove(v)
del(self.edge_properties[(u,v)])
del(self.edge_attr[(u,v)])
if (u != v):
self.node_neighbors[v].remove(u)
del(self.edge_properties[(v,u)])
del(self.edge_attr[(v,u)])
def edge_weight(self, u, v):
"""
Get the weight of an edge.
@type u: node
@param u: One node.
@type v: node
@param v: Other node.
@rtype: number
@return: Edge weight.
"""
return self.edge_properties[(u, v)][1]
def set_edge_weight(self, u, v, wt):
"""
Set the weight of an edge.
@type u: node
@param u: One node.
@type v: node
@param v: Other node.
@type wt: number
@param wt: Edge weight.
"""
self.edge_properties[(u, v)][1] = wt
self.edge_properties[(v, u)][1] = wt
def edge_label(self, u, v):
"""
Get the label of an edge.
@type u: node
@param u: One node.
@type v: node
@param v: Other node.
@rtype: string
@return: Edge label
"""
return self.edge_properties[(u, v)][0]
def set_edge_label(self, u, v, label):
"""
Set the label of an edge.
@type u: node
@param u: One node.
@type v: node
@param v: Other node.
@type label: string
@param label: Edge label.
"""
self.edge_properties[(u, v)][0] = label
self.edge_properties[(v, u)][0] = label
def add_node_attribute(self, node, attr):
"""
Add attribute to the given node.
@type node: node
@param node: Node identifier
@type attr: tuple
@param attr: Node attribute specified as a tuple in the form (attribute, value).
"""
self.node_attr[node] = self.node_attr[node] + [attr]
def node_attributes(self, node):
"""
Return the attributes of the given node.
@type node: node
@param node: Node identifier
@rtype: list
@return: List of attributes specified tuples in the form (attribute, value).
"""
return self.node_attr[node]
def add_edge_attribute(self, u, v, attr):
"""
Add attribute to the given edge.
@type u: node
@param u: One node.
@type v: node
@param v: Other node.
@type attr: tuple
@param attr: Node attribute specified as a tuple in the form (attribute, value).
"""
self.edge_attr[(u,v)] = self.edge_attr[(u,v)] + [attr]
self.edge_attr[(v,u)] = self.edge_attr[(v,u)] + [attr]
def edge_attributes(self, u, v):
"""
Return the attributes of the given edge.
@type u: node
@param u: One node.
@type v: node
@param v: Other node.
@rtype: list
@return: List of attributes specified tuples in the form (attribute, value).
"""
return self.edge_attr[(u,v)]
def has_edge(self, u, v):
"""
Return whether an edge between nodes u and v exists.
@type u: node
@param u: One node.
@type v: node
@param v: Other node.
@rtype: boolean
@return: Truth-value for edge existence.
"""
return (u,v) in self.edge_properties and (v,u) in self.edge_properties
def node_order(self, node):
"""
Return the order of the given node.
@rtype: number
@return: Order of the given node.
"""
return len(self.neighbors(node))
def complete(self):
"""
Make the graph a complete graph.
@attention: This will modify the current graph.
"""
for each in self.nodes():
for other in self.nodes():
if (each != other and not self.has_edge(each, other)):
self.add_edge(each, other)
def inverse(self):
"""
Return the inverse of the graph.
@rtype: graph
@return: Complement graph for the graph.
"""
inv = graph()
inv.add_nodes(self.nodes())
inv.complete()
for each in self.edges():
if (inv.has_edge(each[0], each[1])):
inv.del_edge(each[0], each[1])
return inv
def add_graph(self, graph):
"""
Add other graph to the graph.
@attention: Attributes and labels are not preserved.
@type graph: graph
@param graph: Graph
"""
for each_node in graph.nodes():
if each_node not in self.nodes():
self.add_node(each_node)
for each_edge in graph.neighbors(each_node):
if (not self.has_edge(each_node, each_edge)):
self.add_edge(each_node, each_edge)
def add_spanning_tree(self, st):
"""
Add a spanning tree to the graph.
@type st: dictionary
@param st: Spanning tree.
"""
self.add_nodes(list(st.keys()))
for each in st:
if (st[each] is not None):
self.add_edge(st[each], each)
def traversal(self, node, order='pre'):
"""
Graph traversal iterator.
@type node: node
@param node: Node.
@type order: string
@param order: traversal ordering. Possible values are:
2. 'pre' - Preordering (default)
1. 'post' - Postordering
@rtype: iterator
@return: Traversal iterator.
"""
for each in traversal.traversal(self, node, order):
yield each