/
graph_algo.go
288 lines (253 loc) · 7.08 KB
/
graph_algo.go
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
package common
import (
"math"
)
// returns shortest distances from the given source node to all vertices in the graph
func (graph *Graph) ShortestDistancesFromSource(src *Node) map[int]float64 {
result := graph.ShortestPath(src, ShortestPathParams{})
return result.Distances
}
type ShortestPathParams struct {
// maximum distance to travel from src
MaxDistance float64
// terminate search once we reach any of these nodes
StopNodes []*Node
// override edge length
EdgeLengths map[int]float64
}
func (params ShortestPathParams) IsStopNode(node *Node) bool {
for _, other := range params.StopNodes {
if other == node {
return true
}
}
return false
}
type ShortestPathResult struct {
source *Node
graph *Graph
Distances map[int]float64
Remaining map[int]bool
Backpointers map[int]int
}
func (result ShortestPathResult) GetPathTo(node *Node) []*Node {
if result.Remaining[node.ID] {
return nil
} else if _, ok := result.Backpointers[node.ID]; !ok {
return nil
}
var reverseSeq []*Node
curNode := node
for curNode.ID != result.source.ID {
reverseSeq = append(reverseSeq, curNode)
curNode = result.graph.Nodes[result.Backpointers[curNode.ID]]
}
path := make([]*Node, len(reverseSeq))
for i, node := range reverseSeq {
path[len(path) - i - 1] = node
}
return path
}
func (result ShortestPathResult) GetFullPathTo(node *Node) []*Node {
return append([]*Node{result.source}, result.GetPathTo(node)...)
}
func (graph *Graph) ShortestPath(src *Node, params ShortestPathParams) ShortestPathResult {
// use Dijkstra's algorithm
distances := make(map[int]float64)
remaining := make(map[int]bool)
backpointers := make(map[int]int)
for _, node := range graph.Nodes {
distances[node.ID] = math.Inf(1)
remaining[node.ID] = true
}
distances[src.ID] = 0
backpointers[src.ID] = src.ID
for len(remaining) > 0 {
var closestNode *Node
var closestDistance float64
for nodeID := range remaining {
if !math.IsInf(distances[nodeID], 1) && (closestNode == nil || distances[nodeID] < closestDistance) {
closestNode = graph.Nodes[nodeID]
closestDistance = distances[nodeID]
}
}
if closestNode == nil {
break
}
delete(remaining, closestNode.ID)
if (params.MaxDistance != 0 && closestDistance > params.MaxDistance) || params.IsStopNode(closestNode) {
break
}
for _, edge := range closestNode.Out {
var edgeLength float64
if l, ok := params.EdgeLengths[edge.ID]; ok {
edgeLength = l
} else {
edgeLength = edge.Segment().Length()
}
d := closestDistance + edgeLength
if remaining[edge.Dst.ID] && d < distances[edge.Dst.ID] {
distances[edge.Dst.ID] = d
backpointers[edge.Dst.ID] = closestNode.ID
}
}
}
return ShortestPathResult{
source: src,
graph: graph,
Distances: distances,
Remaining: remaining,
Backpointers: backpointers,
}
}
type FollowParams struct {
// Source, only one should be specified.
SourceNodes []*Node
SourcePos EdgePos
// Distance to travel along graph from source.
Distance float64
// If true, don't search forwards.
NoForwards bool
// If true, search backwards (in addition to searching forwards).
Backwards bool
// If set, will be populated with nodes that we pass during following.
SeenNodes map[int]bool
// If set, we will stop immediately before these nodes rather than passing them.
StopNodes map[int]bool
}
// Find locations after traveling along the graph from pos for distance.
func (graph *Graph) Follow(params FollowParams) []EdgePos {
seenNodePairs := make(map[[2]int]bool)
var positions []EdgePos
var followNode func(node *Node, remaining float64, backwards bool)
followForwards := func(pos EdgePos, remaining float64) {
seenNodePairs[[2]int{pos.Edge.Src.ID, pos.Edge.Dst.ID}] = true
if pos.Position + remaining <= pos.Edge.Segment().Length() {
positions = append(positions, EdgePos{
pos.Edge,
pos.Position + remaining,
})
} else if params.StopNodes != nil && params.StopNodes[pos.Edge.Dst.ID] {
positions = append(positions, EdgePos{
pos.Edge,
pos.Edge.Segment().Length(),
})
} else {
followNode(pos.Edge.Dst, remaining - (pos.Edge.Segment().Length() - pos.Position), false)
}
}
followBackwards := func(pos EdgePos, remaining float64) {
seenNodePairs[[2]int{pos.Edge.Src.ID, pos.Edge.Dst.ID}] = true
if remaining <= pos.Position {
positions = append(positions, EdgePos{
pos.Edge,
pos.Position - remaining,
})
} else if params.StopNodes != nil && params.StopNodes[pos.Edge.Src.ID] {
positions = append(positions, EdgePos{
pos.Edge,
0,
})
} else {
followNode(pos.Edge.Src, remaining - pos.Position, true)
}
}
followNode = func(node *Node, remaining float64, backwards bool) {
if params.SeenNodes != nil {
params.SeenNodes[node.ID] = true
}
var edges []*Edge
if !backwards {
edges = node.Out
} else {
edges = node.In
}
for _, edge := range edges {
if seenNodePairs[[2]int{edge.Src.ID, edge.Dst.ID}] || seenNodePairs[[2]int{edge.Dst.ID, edge.Src.ID}] {
continue
}
if !backwards {
followForwards(EdgePos{
edge,
0,
}, remaining)
} else {
followBackwards(EdgePos{
edge,
edge.Segment().Length(),
}, remaining)
}
}
}
if len(params.SourceNodes) > 0 {
for _, node := range params.SourceNodes {
if !params.NoForwards {
followNode(node, params.Distance, false)
}
if params.Backwards {
followNode(node, params.Distance, true)
}
}
} else {
if !params.NoForwards {
followForwards(params.SourcePos, params.Distance)
}
if params.Backwards {
followBackwards(params.SourcePos, params.Distance)
}
}
return positions
}
// A*
type AstarParams struct {
// maximum distance to travel from src
MaxDistance float64
}
func (graph *Graph) Astar(src *Node, dst *Node, params AstarParams) ShortestPathResult {
distances := make(map[int]float64)
remaining := make(map[int]bool)
backpointers := make(map[int]int)
scores := make(map[int]float64)
for _, node := range graph.Nodes {
distances[node.ID] = math.Inf(1)
remaining[node.ID] = true
scores[node.ID] = math.Inf(1)
}
distances[src.ID] = 0
backpointers[src.ID] = src.ID
scores[src.ID] = src.Point.Distance(dst.Point)
for len(remaining) > 0 {
var closestNode *Node
var closestDistance float64
var closestScore float64
for nodeID := range remaining {
if !math.IsInf(scores[nodeID], 1) && (closestNode == nil || scores[nodeID] < closestScore) {
closestNode = graph.Nodes[nodeID]
closestDistance = distances[nodeID]
closestScore = scores[nodeID]
}
}
if closestNode == nil {
break
}
delete(remaining, closestNode.ID)
if (params.MaxDistance != 0 && closestDistance > params.MaxDistance) || closestNode == dst {
break
}
for _, edge := range closestNode.Out {
d := closestDistance + edge.Segment().Length()
if remaining[edge.Dst.ID] && d < distances[edge.Dst.ID] {
distances[edge.Dst.ID] = d
backpointers[edge.Dst.ID] = closestNode.ID
scores[edge.Dst.ID] = d + edge.Dst.Point.Distance(dst.Point)
}
}
}
return ShortestPathResult{
source: src,
graph: graph,
Distances: distances,
Remaining: remaining,
Backpointers: backpointers,
}
}