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
|
#!/usr/bin/env python
from __future__ import division
import numpy as np
import time
import mrol_mapping.occupiedlist as occupiedlist
import mrol_mapping.poseutil as poseutil
import collections
#import mrol_mapping.cython.fast as fast
import matplotlib.pyplot as plt
import scipy.spatial as spatial
#import numexpr as ne
#ne.set_num_threads(4)
import cProfile
profile = False
# TODO run this speed test on real/simulated from blender data?
class SpeedTest():
def setUp(self):
#np.random.seed(6)
self.resolution = 1
self.mpts = 100000 #Adding a zero here changes the cython results dramatically
self.npts = 100000
self.high = 50
self.M = np.random.randint(0, self.high, (self.mpts, 3)).astype(np.int16)
self.P = np.random.randint(0, self.high, (self.npts, 3)).astype(np.int16)
self.testpose = (-2., 42., 80., 0.2, 0.1, 2.6)
self.testposeinv = poseutil.inverse(self.testpose)
self.Pxformed = poseutil.transformPoints(self.P, self.testpose)[0]
self.ol = occupiedlist.OccupiedList(self.resolution, use_bloom=False)
self.ol.add_points(self.M)
self.ol_bloom = occupiedlist.OccupiedList(self.resolution, use_bloom=True)
self.ol_bloom.add_points(self.M)
self.Mkdt = spatial.cKDTree(self.M)
self.maparray = np.zeros((self.high, self.high, self.high), dtype=np.bool)
#self.maparray = ndsparse.ndsparse((self.high, self.high, self.high))
self.maparray[self.M[:, 0], self.M[:, 1], self.M[:, 2]] = True
# set up packed arrays map
ids = occupiedlist._pack(self.M)
self.mapvoxels_int16 = dict.fromkeys(ids, 1)
self.mapset = set(ids)
#self.mapvoxels_int16 = collections.defaultdict(int)
#for ID in ids:
# self.mapvoxels_int16[ID.tostring()] += 1
# bloom map
self.bloom = occupiedlist.BloomFilter(self.mpts)
self.bloom.add_voxel_ids(occupiedlist._pack(self.M))
# dictionary of dictionaries
#D = dict.fromkeys(self.mpts[:,0], dict())
self.Pint = self.P.astype(int)
D = dict()
# first initialise
for a, b, c in self.M:
D.setdefault(a, dict())
D[a].setdefault(b, dict())
D[a][b][c] = 0
for a, b, c in self.M:
D[a][b][c] += 1
self.nestedDict = D
# Functions to be benchmarked start with bench_
def Xbench_nested_dict(self):
D = self.nestedDict
#ainds = np.where([i in D for i in self.P[:, 0]])[0]
#binds = [self.P[i, 1] in D[self.P[i, 0]] for i in ainds]
#cinds = ainds[np.array(binds)]
#return sum(self.P[c, 2] in D[self.P[c, 0]][self.P[c, 1]] for c in cinds)
#overlap = 0
#for a, b, c in self.P:
#if a in D and b in D[a] and c in D[a][b]:
#overlap += 1
overlap = sum(a in D and b in D[a] and c in D[a][b] for a, b, c in self.P)
#overlap = fast.nested_intersection(D, self.Pint)
# cython version slower than python!
return overlap
def Xbench_kdtree_overlap(self):
dists, inds = self.Mkdt.query(self.P, k=1, p=1)
return sum(dists < 1)
def bench_lookup_bloom(self):
#PV = occupiedlist.pointstovoxels(self.P, 1)
#ids = occupiedlist._pack(PV)
ids = occupiedlist._pack(self.P)
overlaps = self.bloom.contains(ids)
#return len(overlap)
return np.sum(overlaps)
def bench_lookup_dense_array(self):
return np.sum(self.maparray[self.P[:, 0], self.P[:, 1], self.P[:, 2]])
def bench_lookup_set_intersection(self):
'''If many points fall in the same voxel this will return only overlap
of one for all those points.'''
Pset = occupiedlist._pack(self.P)
overlap = self.mapset.intersection(Pset)
return len(overlap)
def bench_lookup_hashtable(self):
ids = occupiedlist._pack(self.P)
overlap = sum(ID in self.mapvoxels_int16 for ID in ids)
return overlap
def bench_rotate_translate_quantise(self):
transformedpts, pose = poseutil.transformPoints(self.Pxformed, self.testposeinv)
transformedvoxels = occupiedlist.pointstovoxels(transformedpts, resolution=self.resolution)
ids = occupiedlist._pack(transformedvoxels)
def bench_transform_and_lookup_hashtable(self):
#overlap = self.ol.calccollisions(None, self.P)
overlap = self.ol.calccollisions(self.testposeinv, self.Pxformed)
return overlap
def bench_transform_and_lookup_bloom(self):
#overlap = self.ol.calccollisions(None, self.P)
overlap = self.ol_bloom.calccollisions(self.testposeinv, self.Pxformed)
return overlap
# end of functions to be benchmarked
def test_map_query(self):
# TODO re-write the comparison methods to operate on the same
# data sets as those that call an OccupiedList object.
# find functions that start with bench_ to be timed
funcs = dir(self)
funcs = [getattr(self, func) for func in funcs if func.startswith('bench_')]
expected_overlap = self.bench_lookup_dense_array()
overlaps = []
results = []
print 'description', 'overlap /'+str(len(self.P)), 'time 1e-6 s'
runs = 10
for func in funcs:
name = func.__name__[6:]
exec_times = []
for i in range(runs):
start = time.time()
if profile:
cProfile.runctx('func()', globals(), locals(), 'speed_test.profile')
overlap = 0
else:
overlap = func()
taken = time.time() - start
exec_times.append(taken/float(self.npts))
overlaps.append(overlap)
results.append((name, exec_times))
#assert exec_time > 1e5, 'Transformations and lookups not fast enough'
print name.ljust(40),
print str(overlap).rjust(10),
print exec_times
times = np.array(zip(*results)[1]) * 1e6
# display results graphically
plt.boxplot(times.T, vert=0)
#plt.barh(range(len(results)), times.min(axis=1), color='gray')
for y, result in enumerate(results):
plt.text(0, y + 1, ' ' + result[0], verticalalignment='center')
#plt.plot(times[y], np.repeat(y+0.5, runs), 'k+')
plt.xlabel('Time (1e-6 s)')
plt.grid()
# save results
F = open('benchmark_results.txt', 'w')
F.write(repr(results))
F.close()
plt.show()
# Make sure all overlaps are the same
# TODO see above comment before re-enabling this assert
#assert np.all(np.diff(overlaps) == 0)
if __name__ == '__main__':
st = SpeedTest()
st.setUp()
st.test_map_query()
|