-
Notifications
You must be signed in to change notification settings - Fork 0
/
library.py
671 lines (563 loc) · 20.6 KB
/
library.py
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
'''library.py
A dumping ground for functions and networks we've defined.
List:
pc
Numpy array with shape (*, 4). Sample pointcloud
quantize(x, a = - 3, b = 1, v = 0.4)
Given a floating value x, quantize its value within
range [a, b] with spacing v.
sample_points(
pointcloud,
D = [-3, 1], H = [-40, 40], W = [0, 70.4], T = 35,
vD = 0.4, vH = 0.2, vW = 0.2,
flip_xyz = True, room_for_augmentation = True
)
Given a pointcloud (i.e. array of (n, 4) points)
and quantization parameters D, H, W, T, vD, vH, vW,
1. quantize according to the parameters D, H, W, vD, vH, vW,
2. sample per-cell according to T, and
3. Augment by adding the offset features (point - offset from mean)
return the (D, H, W, T, 7) array of selected points.
augment_pc_with_offsets(voxelgrid):
Given a voxel from sample_points(...),
we want to augment each point in each cell
with (z - z_mean, y - y_mean, x - x_mean),
i.e. the offset from the centroid of the cell.
Operates IN PLACE.
equi_hash(n, a = 0.618033988749895, K = 131072)
Hash integer n to range [0, K) using Equidistribution Theorem Hash, using irrational a.
ravel_multi_index(
index = (0, 0, 0),
shape = (10, 400, 352)
):
Flatten an index for a given range
And the layers: VFE_FCN, ElementwiseMaxpool, PointwiseConcat, VFE, VFE_out, ConvMiddleLayer, RPNConvBlock
Quick import:
from library import pc, quantize, sample_points, augment_pc_with_offsets
from library import equi_hash, ravel_multi_index
from library import VFE_FCN, ElementwiseMaxpool, PointwiseConcat, VFE, VFE_out
from library import ConvMiddleLayer, RPNConvBlock
'''
import math
import os
import random
import sys
import struct
import warnings
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
# Define a pointcloud for us to use
with open('example_pc.bytes', 'rb') as ff:
pc_bytes = ff.read()
pc = np.array(list(struct.iter_unpack('f', pc_bytes))).reshape(-1, 4)
#Part 1: Voxel Feature Encoder functions
def quantize(x, a = - 3, b = 1, v = 0.4):
'''Given a floating value x, quantize its value within
range [a, b] with spacing v.
:param x: The value to quantize.
:type x: float
:param a: The left-bound of the range.
:type a: float
:param b: The right-bound of the range.
:type b: float
:param v: The size of each quantize
:type v: float
:return: The quantized index of x
:rtype: int
Examples:
>>> quantize(x = -3.0, a = - 3, b = 1, v = 0.4)
0
>>> quantize(x = 1.0, a = - 3, b = 1, v = 0.4)
9
>>> quantize(x = 0.3, a = - 3, b = 1, v = 0.4)
8
'''
return int((x - a) // v)
def sample_points(
pointcloud,
D = [-3, 1],
H = [-40, 40],
W = [0, 70.4],
T = 35,
vD = 0.4,
vH = 0.2,
vW = 0.2,
flip_xyz = True,
room_for_augmentation = True
):
'''Given a pointcloud (i.e. array of (n, 4) points)
and quantization parameters D, H, W, T, vD, vH, vW,
1. quantize according to the parameters D, H, W, vD, vH, vW,
2. sample per-cell according to T, and
3. Augment by adding the offset features (point - offset from mean)
return the (D, H, W, T, 7) array of selected points.
:param pointcloud: Array of floats, size (n, 4) or (n, 3).
Assuming (x, y, z).
:type pointcloud: numpy.ndarray
:param D: Range over Z axis, list of two floats
:type D: list
:param H: Range over Y axis, list of two floats
:type H: list
:param W: Range over X axis, list of two floats
:type W: list
:param T: Maximum number of points to sample
:type T: int
:param vD: Quantization size over Z axis
:type vD: float
:param vH: Quantization size over Y axis
:type vH: float
:param vW: Quantization size over X axis
:type vW: float
:param flip_xyz: If True, assume the input array is (x, y, z)
rather than (z, y, x).
:type flip_xyz: bool
:param room_for_augmentation: If True, instantiage G with
size 7 instead of 4, leaving room for augmentation
described in 2.1.1.
:type flip_xyz: bool
:return: Array of size (D, H, W, T, 4) (or 3)
containing selection of points.
:rtype: numpy.ndarray
'''
#pointcloud,
#D = [-3, 1],H = [-40, 40],W = [0, 70.4],
#T = 35,
#vD = 0.4,vH = 0.2,vW = 0.2,
#flip_xyz = True
# Get the sizes of the grid
Dsize = int((D[1] - D[0]) / vD)
Hsize = int((H[1] - H[0]) / vH)
Wsize = int((W[1] - W[0]) / vW)
assert len(pointcloud.shape) == 2, "Pointcloud should be of shape (n, 4)"
assert pointcloud.shape[1] == 4, \
f"Expected points in 4 dimensions, not {pointcloud.shape[1]}"
# 1 and 2: Define our arrays
point_size = 7 if room_for_augmentation else 4
G = np.zeros((Dsize, Hsize, Wsize, T, point_size))
N = np.zeros((Dsize, Hsize, Wsize), dtype=np.int)
# 3. Randomly shuffle incoming points P
number_of_points = pointcloud.shape[0]
random_indices = np.random.permutation(number_of_points)
# 4. For each point in the pointcloud to add to the grid,
for pc_index in random_indices:
# 1. Get the indices `(i, j, k)`
x, y, z, r = pointcloud[pc_index]
# skip if any are out of bounds
if not D[0] < z < D[1]:
continue
if not H[0] < y < H[1]:
continue
if not W[0] < x < W[1]:
continue
# note (i, j, k) corresponds to (Z, Y, X)
i = quantize(z, a=D[0], b=D[1], v=vD)
j = quantize(y, a=H[0], b=H[1], v=vH)
k = quantize(x, a=W[0], b=W[1], v=vW)
# 2. Get t and increase N
t = N[i, j, k]
N[i, j, k] += 1
# 3 and 4 Skip if t >= T, add the point to G
if t < T:
G[i, j, k, t, :4] = z, y, x, r
return G, N
def augment_pc_with_offsets(voxelgrid):
'''Given a voxel from sample_points(...),
we want to augment each point in each cell
with (z - z_mean, y - y_mean, x - x_mean),
i.e. the offset from the centroid of the cell.
Operates IN PLACE.
voxelgrid[:,:,:,:,4:7] should be empty.
:param voxelgrid: Voxelgrid returned from sample_points,
shape (D, H, W, T, 7)
:type voxelgrid: numpy.ndarray
'''
voxelgrid[:,:,:,:,4:7] = \
voxelgrid[:,:,:,:,:3] \
- voxelgrid[:,:,:,:,:3].mean(axis=3)[:,:,:,None,:]
# Operates in-place! Return is only for convenience.
return voxelgrid
def equi_hash(n, a = 0.618033988749895, K = 131072):
"""Hash integer n to range [0, K) using Equidistribution Theorem Hash, using irrational a.
Is optimal for a = Phi = 1.618034.
Because of mod 1, we use 0.618034.
:param n: Input to hash
:type n: int
:param a: Irrational number, defaults to 0.618033988749895
:type a: float, optional
:param K: [description], defaults to 131072
:type K: int, optional
:return: Result of the hash: An int in range [0, K)
:rtype: int
"""
return math.floor(((n * a) % 1)*K)
def ravel_multi_index(
index = (0, 0, 0),
shape = (10, 400, 352)
):
"""Flatten an index for a given range
:param index: Multi-axis index, defaults to (0, 0, 0)
:type index: tuple, optional
:param shape: Range of the index, defaults to (10, 400, 352)
:type shape: tuple, optional
:return: Flat index for the given shape
:rtype: int
"""
assert len(index) == len(shape)
flat_index = 0
for axis in range(len(index)):
flat_index = flat_index * shape[axis]
flat_index = flat_index + index[axis]
return flat_index
#Part 1.2. VFE neural layers
class VFE_FCN(keras.layers.Layer):
'''The fully-connected layer used for the VFE.
:param CC: Dimension of input
:type CC: int
:param name: Suffix of names to be given to layers
:type name: str
'''
def __init__(self, units = 32, name = "VFE_FCN"):
super(VFE_FCN, self).__init__(name=name)
self.linear = keras.layers.Dense(units, name = f"{name}_linear")
self.bn = keras.layers.BatchNormalization(name = f"{name}_bn")
self.relu = keras.layers.ReLU(name = f"{name}_fcn")
def call(self, xx):
'''
:param xx: Input tensor
:type xx: Tensor
'''
# TODO: tflow can't autograph this. report on github
return self.relu(self.bn(self.linear(xx)))
class ElementwiseMaxpool(keras.layers.Layer):
'''
:param axis: Axis to maxpool over
:type axis: int
:param keepdims: If true, reduced axes are not deleted.
E.g. (3, 3, 35) over axis 2 becomes (3, 3, 1).
:type keepdims: bool
:param name: Suffix of names to be given to layers
:type name: str
'''
def __init__(self, axis = 3, keepdims = True, name = "VFE_ElementwiseMaxpool"):
super(ElementwiseMaxpool, self).__init__(name=name)
self.axis = axis
self.keepdims = keepdims
def call(self, xx):
'''
:param xx: Input tensor to be maxpooled
:type xx: Tensor
:return: Output tensor after maxpooling operation
:rtype: Tensor
'''
return tf.reduce_max(xx, axis = self.axis, keepdims = self.keepdims)
class PointwiseConcat(keras.layers.Layer):
'''Given two inputs, broadcast the second over a given axis to match
the first, and then concatenate them.
:param axis: Axis to repeat over
:type axis: int
:param expand_dims: If True, expand at the axis on the second input.
Use False if the axis is already there (shape 1).
:type expand_dims: bool
:param name: Suffix of names to be given to layers
:type name: str
'''
def __init__(self, axis = 4, expand_dims = False, name = "pointwise_concat_"):
super(PointwiseConcat, self).__init__(name=name)
self.axis = axis
self.expand_dims = expand_dims
def call(self, xx):
'''
:param xx: Input tensor
:type xx: Tensor
'''
# 1. make sure shape makes sense
X1 = xx[0] # pointwise
X2 = xx[1] # aggregate
if self.expand_dims:
assert len(X1.shape) == len(X2.shape) + 1
else:
assert len(X1.shape) == len(X2.shape)
# 2. Get num to repeat
num_to_repeat = X1.shape[self.axis]
# 3. expand_dims, repeat,
if self.expand_dims:
X2_wip = tf.expand_dims(X2, axis = self.axis)
X2_wip = tf.repeat(X2, num_to_repeat, axis = self.axis)
#todo: assert fails even though both are equal.
#debug later...
#assert X2_wip.shape == X1.shape, f"{X2_wip.shape} != {X1.shape}"
return tf.concat([X1, X2_wip], axis = -1)
class VFE(keras.layers.Layer):
'''
:param cin: Dimensionality of input points
:type cin: int
:param cout: Dimension of output
:type cout: int
:param cout: Max number of points in voxel, needed for repeat
:type cout: int
:param name: Suffix of names to be given to layers
:type name: str
'''
def __init__(
self,
cin = 7,
cout = 32,
T = 35,
name = "VFE"
):
super(VFE, self).__init__(name=name)
self.fcn = VFE_FCN(units = cout//2, name = f"{name}_fcn")
self.elementwise_maxpool = ElementwiseMaxpool(
axis = 4,
keepdims = True,
name = f"{name}_elementwise_maxpool"
)
self.pointwise_concat = PointwiseConcat(
axis = 4,
name = f"{name}_pointwise_concat"
)
def call(
self,
xx
):
'''
:param xx: Input tensor
:type xx: Tensor
:return: Output of layer
:rtype: Tensor
'''
pointwise_features = self.fcn(xx)
aggregate_features = self.elementwise_maxpool(pointwise_features)
return self.pointwise_concat([pointwise_features, aggregate_features])
class VFE_out(keras.layers.Layer):
'''Connects VFE-n layer to the convolutional middle layers.
:param CC: Dimension of input
:type CC: int
:param axis: Axis to maxpool over
:type axis: int
:param name: Suffix of names to be given to layers
:type name: str
'''
def __init__(self, CC = 128, axis = 3, name = "VFE_out"):
super(VFE_out, self).__init__(name=name)
self.fcn = VFE_FCN(units=CC, name = f"{name}_fcn")
self.elementwise_maxpool = ElementwiseMaxpool(
axis = 4,
keepdims = False,
name = f"{name}_elementwise_maxpool"
)
def call(self, xx):
'''
:param xx: Input tensor
:type xx: Tensor
:return: Output of layer
:rtype: Tensor
'''
return self.elementwise_maxpool(self.fcn(xx))
#Part 2. Convolutional middle layers
class ConvMiddleLayer(keras.layers.Layer):
'''
See section 2.1.2 "Convolutional Middle Layers" of the VoxelNet paper.
For parameters kk, ss, and pp, these are vectors of size MM,
but can be instantiated as a scalar.
(E.g. for MM = 3 and kk = 2, this code changes it to kk = (2, 2, 2)
:param MM: Dimension of the convolution, default 3
:type MM: int
:param c_in: Number of input channels
:type c_in: int
:param c_out: Number of output channels
:type c_out: int
:param kk: Kernel size, vector of size MM
:type kk: tuple or int
:param ss: Stride size, vector of size MM
:type ss: tuple or int
:param pp: Padding size, vector of size MM
:type pp: tuple or int
:param name: Suffix of names to be given to layers
:type name: str
'''
def __init__(
self,
MM = 3,
c_in = 64,
c_out = 64,
kk = 3,
ss = (2, 1, 1),
pp = (1, 1, 1),
name = "ConvMiddleBlock"
):
super(ConvMiddleLayer, self).__init__(name=name)
# Check all values first
# (todo: type hint, how to do iterables and union in 3.7?)
# (todo: consider using pattern matching, if you're willing to break for old python version)
if not isinstance(MM, int):
raise TypeError("MM must be int")
if not isinstance(c_in, int):
raise TypeError("c_in must be int")
if not isinstance(c_out, int):
raise TypeError("c_out must be int")
self.MM = MM
self.c_in = c_in
self.c_out = c_out
if type(kk) is int:
self.kk = [kk for _ in range(MM)]
elif not hasattr(kk, '__iter__'):
raise TypeError("kk must be int or iterable of ints")
else:
if not len(kk) == MM:
raise ValueError("kk must be of length MM")
for val in kk:
if not isinstance(val, int):
raise TypeError("kk must be int or iterable of ints")
self.kk = kk
if type(ss) is int:
self.ss = [ss for _ in range(MM)]
elif not hasattr(ss, '__iter__'):
raise TypeError("ss must be int or iterable of ints")
else:
if not len(ss) == MM:
raise ValueError("ss must be of length MM")
for val in ss:
if not isinstance(val, int):
raise TypeError("ss must be int or iterable of ints")
self.ss = ss
if type(pp) is int:
self.pp = [pp for _ in range(MM)]
elif not hasattr(pp, '__iter__'):
raise TypeError("pp must be int or iterable of ints")
else:
if not len(pp) == MM:
raise ValueError("pp must be of length MM")
for val in pp:
if not isinstance(val, int):
raise TypeError("pp must be int or iterable of ints")
self.pp = pp
# TODO: define data format in padding and conv layers?
if MM == 3:
self.pad_layer = keras.layers.ZeroPadding3D(
padding = self.pp,
name = f"{self.name}_padding"
)
self.conv_layer = keras.layers.Conv3D(
filters = self.c_out,
kernel_size = self.kk,
strides = self.ss,
padding = "valid", # TODO: Padding self.pp applies during call
name = f"{self.name}_conv"
)
elif MM == 2:
self.pad_layer = keras.layers.ZeroPadding2D(
padding = self.pp,
name = f"{self.name}_padding"
)
self.conv_layer = keras.layers.Conv2D(
filters = self.c_out,
kernel_size = self.kk,
strides = self.ss,
padding = "valid", # TODO: Padding self.pp applies during call
name = f"{self.name}_conv"
)
elif MM == 1:
self.pad_layer = keras.layers.ZeroPadding1D(
padding = self.pp,
name = f"{self.name}_padding"
)
self.conv_layer = keras.layers.Conv1D(
filters = self.c_out,
kernel_size = self.kk,
strides = self.ss,
padding = "valid", # TODO: Padding self.pp applies during call
name = f"{self.name}_conv"
)
elif MM == 4:
raise NotImplementedError("4D convolutions not supported! Implement this in ConvMiddleLayer.")
else:
raise ValueError("Dimension MM must be 1, 2, or 3..")
self.batchnorm_layer = keras.layers.BatchNormalization(
name = f"{self.name}_batchnorm"
)
self.relu_layer = keras.layers.ReLU(
name = f"{self.name}_relu"
)
def call(
self,
tf_input
):
if not tf_input.shape[-1] == self.c_in:
print(f"Warning, {self.name} expected input with {self.c_in} channels, got {tf_input.shape[-1]} instead.")
conved = self.conv_layer(tf_input)
h1 = self.pad_layer(conved)
h2 = self.batchnorm_layer(h1)
h3 = self.relu_layer(h2)
return h3
#3. RPN block
class RPNConvBlock(keras.layers.Layer):
'''
See section 2.1.3 "Convolutional Middle Layers" of the VoxelNet paper.
This defines a 2D convolution block used in the RPN.
:param filters: Number of filters in each convolution block
:type filters: int
:param qq: Number of stacks of convolutions
:type qq: int
:param kernel_size:
:type kernel_size:
:param get_strides: A function mapping integers [0, ..., q) to integers.
(By default, follows values for car detection. Use `lambda ii: 1` to return constant 1.)
:type strides: function
:param padding:
:type padding:
:param name: Suffix of names to be given to layers
:type name: str
'''
def __init__(
self,
qq = 6,
filters = 128,
kernel_size = 3,
get_strides = lambda ii: 2 if ii == 0 else 1,
padding = 1,
name = "RPN_Conv_Block",
):
super(RPNConvBlock, self).__init__(name=name)
if qq <= 0:
raise ValueError(f"Expected positive number of layers, but RPN conv block \"{name}\" got qq = {qq}")
self.qq = qq
self.filters = filters
self.kernel_size = kernel_size
self.padding = padding
self.get_strides = get_strides
self.block_layers = []
for ii in range(self.qq):
strides = self.get_strides(ii)
new_layers = [
keras.layers.ZeroPadding2D(
padding = self.padding,
name = f"{self.name}_zeropadding_{ii}"
),
keras.layers.Conv2D(
filters = self.filters,
kernel_size = self.kernel_size,
strides = strides,
padding = 'valid',
name = f"{self.name}_conv_{ii}"
),
keras.layers.BatchNormalization(
name = f"{self.name}_bn_{ii}"
),
keras.layers.ReLU(
name = f"{self.name}_relu_{ii}"
)
]
self.block_layers.extend(new_layers)
def call(
self,
xx
):
for layer in self.block_layers:
xx = layer(xx)
return xx
# TODO: Loss, training, etc.
# See nb102 for connecting conv, RPN layers, stacking.