Debian Codegraph @

altgraph/GraphAlgo.py

raw symbols SCIP
1 """
2 altgraph.GraphAlgo - Graph algorithms
3 =====================================
4 """
5 from altgraph import GraphError
6
7
8 def dijkstra(graph, start, end=None):
9 """
10 Dijkstra's algorithm for shortest paths
11
12 `David Eppstein, UC Irvine, 4 April 2002
13 <http://www.ics.uci.edu/~eppstein/161/python/>`_
14
15 `Python Cookbook Recipe
16 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466>`_
17
18 Find shortest paths from the start node to all nodes nearer than or
19 equal to the end node.
20
21 Dijkstra's algorithm is only guaranteed to work correctly when all edge
22 lengths are positive. This code does not verify this property for all
23 edges (only the edges examined until the end vertex is reached), but will
24 correctly compute shortest paths even for some graphs with negative edges,
25 and will raise an exception if it discovers that a negative edge has
26 caused it to make a mistake.
27
28 Adapted to altgraph by Istvan Albert, Pennsylvania State University -
29 June, 9 2004
30 """
31 D = {} # dictionary of final distances
32 P = {} # dictionary of predecessors
33 Q = _priorityDictionary() # estimated distances of non-final vertices
34 Q[start] = 0
35
36 for v in Q:
37 D[v] = Q[v]
38 if v == end:
39 break
40
41 for w in graph.out_nbrs(v):
42 edge_id = graph.edge_by_node(v, w)
43 vwLength = D[v] + graph.edge_data(edge_id)
44 if w in D:
45 if vwLength < D[w]:
46 raise GraphError(
47 "Dijkstra: found better path to already-final vertex"
48 )
49 elif w not in Q or vwLength < Q[w]:
50 Q[w] = vwLength
51 P[w] = v
52
53 return (D, P)
54
55
56 def shortest_path(graph, start, end):
57 """
58 Find a single shortest path from the *start* node to the *end* node.
59 The input has the same conventions as dijkstra(). The output is a list of
60 the nodes in order along the shortest path.
61
62 **Note that the distances must be stored in the edge data as numeric data**
63 """
64
65 D, P = dijkstra(graph, start, end)
66 Path = []
67 while 1:
68 Path.append(end)
69 if end == start:
70 break
71 end = P[end]
72 Path.reverse()
73 return Path
74
75
76 #
77 # Utility classes and functions
78 #
79 class _priorityDictionary(dict):
80 """
81 Priority dictionary using binary heaps (internal use only)
82
83 David Eppstein, UC Irvine, 8 Mar 2002
84
85 Implements a data structure that acts almost like a dictionary, with
86 two modifications:
87
88 1. D.smallest() returns the value x minimizing D[x]. For this to
89 work correctly, all values D[x] stored in the dictionary must be
90 comparable.
91
92 2. iterating "for x in D" finds and removes the items from D in sorted
93 order. Each item is not removed until the next item is requested,
94 so D[x] will still return a useful value until the next iteration
95 of the for-loop. Each operation takes logarithmic amortized time.
96 """
97
98 def __init__(self):
99 """
100 Initialize priorityDictionary by creating binary heap of pairs
101 (value,key). Note that changing or removing a dict entry will not
102 remove the old pair from the heap until it is found by smallest()
103 or until the heap is rebuilt.
104 """
105 self.__heap = []
106 dict.__init__(self)
107
108 def smallest(self):
109 """
110 Find smallest item after removing deleted items from front of heap.
111 """
112 if len(self) == 0:
113 raise IndexError("smallest of empty priorityDictionary")
114 heap = self.__heap
115 while heap[0][1] not in self or self[heap[0][1]] != heap[0][0]:
116 lastItem = heap.pop()
117 insertionPoint = 0
118 while 1:
119 smallChild = 2 * insertionPoint + 1
120 if (
121 smallChild + 1 < len(heap)
122 and heap[smallChild] > heap[smallChild + 1]
123 ):
124 smallChild += 1
125 if smallChild >= len(heap) or lastItem <= heap[smallChild]:
126 heap[insertionPoint] = lastItem
127 break
128 heap[insertionPoint] = heap[smallChild]
129 insertionPoint = smallChild
130 return heap[0][1]
131
132 def __iter__(self):
133 """
134 Create destructive sorted iterator of priorityDictionary.
135 """
136
137 def iterfn():
138 while len(self) > 0:
139 x = self.smallest()
140 yield x
141 del self[x]
142
143 return iterfn()
144
145 def __setitem__(self, key, val):
146 """
147 Change value stored in dictionary and add corresponding pair to heap.
148 Rebuilds the heap if the number of deleted items gets large, to avoid
149 memory leakage.
150 """
151 dict.__setitem__(self, key, val)
152 heap = self.__heap
153 if len(heap) > 2 * len(self):
154 self.__heap = [(v, k) for k, v in self.items()]
155 self.__heap.sort()
156 else:
157 newPair = (val, key)
158 insertionPoint = len(heap)
159 heap.append(None)
160 while insertionPoint > 0 and newPair < heap[(insertionPoint - 1) // 2]:
161 heap[insertionPoint] = heap[(insertionPoint - 1) // 2]
162 insertionPoint = (insertionPoint - 1) // 2
163 heap[insertionPoint] = newPair
164
165 def setdefault(self, key, val):
166 """
167 Reimplement setdefault to pass through our customized __setitem__.
168 """
169 if key not in self:
170 self[key] = val
171 return self[key]