forked from pmatiello/python-graph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminmax.py
More file actions
249 lines (193 loc) · 7.33 KB
/
Copy pathminmax.py
File metadata and controls
249 lines (193 loc) · 7.33 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
# Copyright (c) 2007-2009 Pedro Matiello <pmatiello@gmail.com>
# Rhys Ulerich <rhys.ulerich@gmail.com>
# Roy Smith <roy@panix.com>
# Salim Fadhley <sal@stodge.org>
#
# 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.
"""
Minimization and maximization algorithms.
@sort: heuristic_search, minimal_spanning_tree, shortest_path, _first_unvisited, _lightest_edge,
_reconstruct_path
"""
from heapq import heappush, heappop
from pygraph.classes.exceptions import NodeUnreachable
# Minimal spanning tree
def minimal_spanning_tree(graph, root=None):
"""
Minimal spanning tree.
@attention: Minimal spanning tree is meaningful only for weighted graphs.
@type graph: graph
@param graph: Graph.
@type root: node
@param root: Optional root node (will explore only root's connected component)
@rtype: dictionary
@return: Generated spanning tree.
"""
visited = [] # List for marking visited and non-visited nodes
spanning_tree = {} # MInimal Spanning tree
# Initialization
if (root is not None):
visited.append(root)
nroot = root
spanning_tree[root] = None
else:
nroot = 1
# Algorithm loop
while (nroot is not None):
ledge = _lightest_edge(graph, visited)
if (ledge == (-1, -1)):
if (root is not None):
break
nroot = _first_unvisited(graph, visited)
if (nroot is not None):
spanning_tree[nroot] = None
visited.append(nroot)
else:
spanning_tree[ledge[1]] = ledge[0]
visited.append(ledge[1])
return spanning_tree
def _first_unvisited(graph, visited):
"""
Return first unvisited node.
@type graph: graph
@param graph: Graph.
@type visited: list
@param visited: List of nodes.
@rtype: node
@return: First unvisited node.
"""
for each in graph:
if (each not in visited):
return each
return None
def _lightest_edge(graph, visited):
"""
Return the lightest edge in graph going from a visited node to an unvisited one.
@type graph: graph
@param graph: Graph.
@type visited: list
@param visited: List of nodes.
@rtype: tuple
@return: Lightest edge in graph going from a visited node to an unvisited one.
"""
lightest_edge = (-1, -1)
weight = -1
for each in visited:
for other in graph[each]:
if (other not in visited):
w = graph.edge_weight(each, other)
if (w < weight or weight < 0):
lightest_edge = (each, other)
weight = w
return lightest_edge
# Shortest Path
# Code donated by Rhys Ulerich
def shortest_path(graph, source):
"""
Return the shortest path distance between source and all other nodes using Dijkstra's
algorithm.
@attention: All weights must be nonnegative.
@type graph: graph, digraph
@param graph: Graph.
@type source: node
@param source: Node from which to start the search.
@rtype: tuple
@return: A tuple containing two dictionaries, each keyed by target nodes.
1. Shortest path spanning tree
2. Shortest distance from given source to each target node
Inaccessible target nodes do not appear in either dictionary.
"""
# Initialization
dist = { source: 0 }
previous = { source: None}
q = graph.nodes()
# Algorithm loop
while q:
# examine_min process performed using O(nodes) pass here.
# May be improved using another examine_min data structure.
u = q[0]
for node in q[1:]:
if ((u not in dist)
or (node in dist and dist[node] < dist[u])):
u = node
q.remove(u)
# Process reachable, remaining nodes from u
if (u in dist):
for v in graph[u]:
if v in q:
alt = dist[u] + graph.edge_weight(u, v)
if (v not in dist) or (alt < dist[v]):
dist[v] = alt
previous[v] = u
return previous, dist
def heuristic_search(graph, start, goal, heuristic):
"""
A* search algorithm.
A set of heuristics is available under C{graph.algorithms.heuristics}. User-created heuristics
are allowed too.
@type graph: graph, digraph
@param graph: Graph
@type start: node
@param start: Start node
@type goal: node
@param goal: Goal node
@type heuristic: function
@param heuristic: Heuristic function
@rtype: list
@return: Optimized path from start to goal node
"""
# The queue stores priority, node, cost to reach, and parent.
queue = [ (0, start, 0, None) ]
# This dictionary maps queued nodes to distance of discovered paths
# and the computed heuristics to goal. We avoid to compute the heuristics
# more than once and to insert too many times the node in the queue.
g = {}
# This maps explored nodes to parent closest to the start
explored = {}
while queue:
_, current, dist, parent = heappop(queue)
if current == goal:
path = [current] + [ n for n in _reconstruct_path( parent, explored ) ]
path.reverse()
return path
if current in explored:
continue
explored[current] = parent
for neighbor in graph[current]:
if neighbor in explored:
continue
ncost = dist + graph.edge_weight(current, neighbor)
if neighbor in g:
qcost, h = g[neighbor]
if qcost <= ncost:
continue
# if ncost < qcost, a longer path to neighbor remains
# g. Removing it would need to filter the whole
# queue, it's better just to leave it there and ignore
# it when we visit the node a second time.
else:
h = heuristic(neighbor, goal)
g[neighbor] = ncost, h
heappush(queue, (ncost + h, neighbor, ncost, current))
raise NodeUnreachable( start, goal )
def _reconstruct_path(node, parents):
while node is not None:
yield node
node = parents[node]