-
Notifications
You must be signed in to change notification settings - Fork 110
/
nearestNeighbor.go
183 lines (161 loc) · 4.21 KB
/
nearestNeighbor.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
//go:build !no_cgo
package motionplan
import (
"context"
"math"
"sort"
"go.viam.com/utils"
"go.viam.com/rdk/motionplan/ik"
)
const defaultNeighborsBeforeParallelization = 1000
type neighborManager struct {
nnKeys chan node
neighbors chan *neighbor
seedPos node
nCPU int
parallelNeighbors int
}
type neighbor struct {
dist float64
node node
}
//nolint:revive
func kNearestNeighbors(planOpts *plannerOptions, tree rrtMap, target node, neighborhoodSize int) []*neighbor {
kNeighbors := neighborhoodSize
if neighborhoodSize > len(tree) {
kNeighbors = len(tree)
}
allCosts := make([]*neighbor, 0)
for rrtnode := range tree {
dist := planOpts.DistanceFunc(&ik.Segment{
StartConfiguration: target.Q(),
EndConfiguration: rrtnode.Q(),
})
allCosts = append(allCosts, &neighbor{dist: dist, node: rrtnode})
}
// sort neighbors by their distance to target first so that first nearest neighbor isn't always the start node of tree
sort.Slice(allCosts, func(i, j int) bool {
if !math.IsNaN(allCosts[i].node.Cost()) {
if !math.IsNaN(allCosts[j].node.Cost()) {
return allCosts[i].dist < allCosts[j].dist
}
}
return allCosts[i].dist < allCosts[j].dist
})
allCosts = allCosts[:kNeighbors]
// sort k nearest distance neighbors by "total cost to target" metric so that target's nearest neighbor
// provides the smallest cost path from start node to target
sort.Slice(allCosts, func(i, j int) bool {
if !math.IsNaN(allCosts[i].node.Cost()) {
if !math.IsNaN(allCosts[j].node.Cost()) {
return (allCosts[i].dist + allCosts[i].node.Cost()) < (allCosts[j].dist + allCosts[j].node.Cost())
}
}
return allCosts[i].dist < allCosts[j].dist
})
return allCosts
}
// Can return `nil` when the context is canceled during processing.
func (nm *neighborManager) nearestNeighbor(
ctx context.Context,
planOpts *plannerOptions,
seed node,
tree rrtMap,
) node {
if nm.parallelNeighbors == 0 {
nm.parallelNeighbors = defaultNeighborsBeforeParallelization
}
if len(tree) > nm.parallelNeighbors && nm.nCPU > 1 {
// If the map is large, calculate distances in parallel
return nm.parallelNearestNeighbor(ctx, planOpts, seed, tree)
}
bestDist := math.Inf(1)
var best node
for k := range tree {
seg := &ik.Segment{
StartConfiguration: seed.Q(),
EndConfiguration: k.Q(),
}
if pose := seed.Pose(); pose != nil {
seg.StartPosition = pose
}
if pose := k.Pose(); pose != nil {
seg.EndPosition = pose
}
dist := planOpts.DistanceFunc(seg)
if dist < bestDist {
bestDist = dist
best = k
}
}
return best
}
func (nm *neighborManager) parallelNearestNeighbor(
ctx context.Context,
planOpts *plannerOptions,
seed node,
tree rrtMap,
) node {
nm.seedPos = seed
nm.neighbors = make(chan *neighbor, nm.nCPU)
nm.nnKeys = make(chan node, len(tree))
defer close(nm.neighbors)
for i := 0; i < nm.nCPU; i++ {
utils.PanicCapturingGo(func() {
nm.nnWorker(ctx, planOpts)
})
}
for k := range tree {
nm.nnKeys <- k
}
close(nm.nnKeys)
wasInterrupted := false
var best node
bestDist := math.Inf(1)
for workerIdx := 0; workerIdx < nm.nCPU; workerIdx++ {
candidate := <-nm.neighbors
if candidate == nil {
// Seeing a `nil` here implies the workers did not get to all of the candidate
// neighbors. And thus we don't have the right answer to return.
wasInterrupted = true
continue
}
if candidate.dist < bestDist {
bestDist = candidate.dist
best = candidate.node
}
}
if wasInterrupted {
return nil
}
return best
}
func (nm *neighborManager) nnWorker(ctx context.Context, planOpts *plannerOptions) {
var best node
bestDist := math.Inf(1)
for candidate := range nm.nnKeys {
select {
case <-ctx.Done():
// We were interrupted, signal that to the caller by returning a `nil`.
nm.neighbors <- nil
return
default:
}
seg := &ik.Segment{
StartConfiguration: nm.seedPos.Q(),
EndConfiguration: candidate.Q(),
}
if pose := nm.seedPos.Pose(); pose != nil {
seg.StartPosition = pose
}
if pose := candidate.Pose(); pose != nil {
seg.EndPosition = pose
}
dist := planOpts.DistanceFunc(seg)
if dist < bestDist {
bestDist = dist
best = candidate
}
}
nm.neighbors <- &neighbor{bestDist, best}
}