-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathclasses.py
More file actions
1946 lines (1707 loc) · 71.7 KB
/
classes.py
File metadata and controls
1946 lines (1707 loc) · 71.7 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
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# https://stackoverflow.com/questions/33533148/how-do-i-type-hint-a-method-with-the-type-of-the-enclosing-class
from __future__ import annotations
import pathlib, math, time, functools, datetime, zoneinfo
import numpy as np
import plyfile
import torch
import einops
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.transform.Rotation.html
import scipy.spatial.transform
# https://tqdm.github.io/docs/tqdm/#tqdm-objects
import tqdm
# https://docs.gsplat.studio/main/index.html
import gsplat
from libraries.utilities import ExLog, ExTimer, UTILITY
from libraries.cliconfigs import VGBuildConfig
class Camera:
def DeriveRandomPoseLookingAtOrigin(
center: torch.Tensor,
radius: float,
asset_name: str = "donut",
) -> Camera:
"""
center: (3,)
radius: pass in four times of the furthest distance in a cluster / cluster group
"""
camera_position_z = -radius + 2.0 * radius * torch.rand(1)
camera_position_xy_radius = torch.sqrt(radius**2 - camera_position_z**2)
camera_position_xy_theta = torch.rand(1) * 2.0 * torch.pi
camera_position_x = camera_position_xy_radius * torch.cos(
camera_position_xy_theta
)
camera_position_y = camera_position_xy_radius * torch.sin(
camera_position_xy_theta
)
camera_position_relative = torch.tensor(
[camera_position_x, camera_position_y, camera_position_z]
)
camera_position_absolute = center + camera_position_relative
camera_lookat = (
-camera_position_relative / camera_position_relative.pow(2).sum().sqrt()
)
camera_upward = torch.tensor([camera_lookat[1], -camera_lookat[0], 0])
camera_upward = camera_upward / camera_upward.pow(2).sum().sqrt()
camera_cross = torch.cross(camera_lookat, camera_upward, dim=0)
# use row vector
T = torch.tensor(
[
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[
-camera_position_absolute[0],
-camera_position_absolute[1],
-camera_position_absolute[2],
1,
],
]
)
R = torch.tensor(
[
[camera_cross[0], -camera_upward[0], camera_lookat[0], 0],
[camera_cross[1], -camera_upward[1], camera_lookat[1], 0],
[camera_cross[2], -camera_upward[2], camera_lookat[2], 0],
[0, 0, 0, 1],
]
)
if asset_name == "donut":
original_image_width = 800
original_image_height = 800
original_focal_x = 1111.1111350971692
original_focal_y = 1111.1111350971692
else:
raise NotImplementedError
# TODO This can be modified.
image_width = 64
image_height = 64
# TODO keep fov unchanged?
focal_x = original_focal_x * image_width / original_image_width
focal_y = original_focal_y * image_height / original_image_height
camera_temp = Camera(
image_width=image_width,
image_height=image_height,
focal_x=focal_x,
focal_y=focal_y,
# don't use the initialization of view_matrix
R=torch.eye(3),
t=torch.tensor(
[0.0, 0.0, 0.0],
dtype=torch.float,
),
)
camera_temp.view_matrix = T @ R
return camera_temp
def DeriveSixDirections(
center: torch.Tensor,
distance: float,
asset_name: str = "donut",
) -> list[Camera]:
# TODO explore this! how to give the parameters
if asset_name == "donut":
original_image_width = 800
original_image_height = 800
original_focal_x = 1111.1111350971692
original_focal_y = 1111.1111350971692
else:
raise NotImplementedError
# (1, 3) -> (3,)
center = center[0]
# TODO This can be modified.
image_width = 64
image_height = 64
# TODO keep fov unchanged?
focal_x = original_focal_x * image_width / original_image_width
focal_y = original_focal_y * image_height / original_image_height
# front, left, right, back, up, down
R_front = torch.tensor(
scipy.spatial.transform.Rotation.from_rotvec(
[0, 0, 180], degrees=True
).as_matrix(),
dtype=torch.float,
) @ torch.tensor(
scipy.spatial.transform.Rotation.from_rotvec(
[-90, 0, 0], degrees=True
).as_matrix(),
dtype=torch.float,
)
cameras: list[Camera] = [
Camera(
image_width=image_width,
image_height=image_height,
focal_x=focal_x,
focal_y=focal_y,
R=R_front,
t=torch.tensor(
[center[0], center[1] + distance, center[2]], dtype=torch.float
),
),
Camera(
image_width=image_width,
image_height=image_height,
focal_x=focal_x,
focal_y=focal_y,
R=torch.tensor(
scipy.spatial.transform.Rotation.from_rotvec(
[0, 0, -90], degrees=True
).as_matrix(),
dtype=torch.float,
)
@ R_front,
t=torch.tensor(
[center[0] + distance, center[1], center[2]], dtype=torch.float
),
),
Camera(
image_width=image_width,
image_height=image_height,
focal_x=focal_x,
focal_y=focal_y,
R=torch.tensor(
scipy.spatial.transform.Rotation.from_rotvec(
[0, 0, 90], degrees=True
).as_matrix(),
dtype=torch.float,
)
@ R_front,
t=torch.tensor(
[center[0] - distance, center[1], center[2]], dtype=torch.float
),
),
Camera(
image_width=image_width,
image_height=image_height,
focal_x=focal_x,
focal_y=focal_y,
R=torch.tensor(
scipy.spatial.transform.Rotation.from_rotvec(
[0, 0, 180], degrees=True
).as_matrix(),
dtype=torch.float,
)
@ R_front,
t=torch.tensor(
[center[0], center[1] - distance, center[2]], dtype=torch.float
),
),
Camera(
image_width=image_width,
image_height=image_height,
focal_x=focal_x,
focal_y=focal_y,
R=torch.tensor(
scipy.spatial.transform.Rotation.from_rotvec(
[90, 0, 0], degrees=True
).as_matrix(),
dtype=torch.float,
)
@ R_front,
t=torch.tensor(
[center[0], center[1], center[2] + distance], dtype=torch.float
),
),
Camera(
image_width=image_width,
image_height=image_height,
focal_x=focal_x,
focal_y=focal_y,
R=torch.tensor(
scipy.spatial.transform.Rotation.from_rotvec(
[-90, 0, 0], degrees=True
).as_matrix(),
dtype=torch.float,
)
@ R_front,
t=torch.tensor(
[center[0], center[1], center[2] - distance], dtype=torch.float
),
),
]
return cameras
def FocalToFov(focal, pixels):
return 2 * math.atan(pixels / (2 * focal))
def GetProjectionMatrix(z_near, z_far, fov_x, fov_y):
tan_half_fov_x = math.tan((fov_x / 2))
tan_half_fov_y = math.tan((fov_y / 2))
top = tan_half_fov_y * z_near
bottom = -top
right = tan_half_fov_x * z_near
left = -right
P = torch.zeros(4, 4)
z_sign = 1.0
P[0, 0] = 2.0 * z_near / (right - left)
P[1, 1] = 2.0 * z_near / (top - bottom)
P[0, 2] = (right + left) / (right - left)
P[1, 2] = (top + bottom) / (top - bottom)
P[3, 2] = z_sign
P[2, 2] = z_sign * z_far / (z_far - z_near)
P[2, 3] = -(z_far * z_near) / (z_far - z_near)
return P
def __init__(self, image_width, image_height, focal_x, focal_y, R, t) -> None:
self.image_width = image_width
self.image_height = image_height
self.focal_x = focal_x
self.focal_y = focal_y
self.fov_x = Camera.FocalToFov(focal=self.focal_x, pixels=self.image_width)
self.fov_y = Camera.FocalToFov(focal=self.focal_y, pixels=self.image_height)
# [view matrix]
Rt = torch.zeros((4, 4), dtype=torch.float)
Rt[:3, :3] = R
Rt[:3, 3] = t
Rt[3, 3] = 1.0
Rt_inv: torch.Tensor = torch.linalg.inv(Rt)
# homogenous coordinate, row vector
self.view_matrix = Rt_inv.transpose(0, 1)
# [projection matrix]
z_far = 100.0 # no use
z_near = 0.01 # no use
# homogenous coordinate, row vector
self.projection_matrix = Camera.GetProjectionMatrix(
z_near=z_near, z_far=z_far, fov_x=self.fov_x, fov_y=self.fov_y
).transpose(0, 1)
class LearnableGaussians(torch.nn.Module):
def ActivationScales(x: torch.Tensor) -> torch.Tensor:
return torch.exp(x)
def InverseActivationScales(y: torch.Tensor) -> torch.Tensor:
return torch.log(y)
def ActivationQauternions(x: torch.Tensor) -> torch.Tensor:
return torch.nn.functional.normalize(x)
def ActivationOpacities(x: torch.Tensor) -> torch.Tensor:
return torch.sigmoid(x)
def InverseActivationOpacities(y: torch.Tensor) -> torch.Tensor:
return torch.log(y / (1 - y))
def ActivationSh0(x: torch.Tensor) -> torch.Tensor:
SH_C0 = 0.28209479177387814
return torch.clip(x * SH_C0 + 0.5, min=0.0, max=None)
def InverseActivationSh0(y: torch.Tensor) -> torch.Tensor:
SH_C0 = 0.28209479177387814
return (y - 0.5) / SH_C0
def __init__(
self,
vg_build_config: VGBuildConfig,
original_gaussians: Cluster,
gaussians: Cluster,
center: torch.Tensor,
distance: float,
) -> None:
"""
pass in initialized 3D Gaussians. LearnableGaussians is only responsible for the optimization task. The count of 3D Gaussians won't change during optimization.
"""
super().__init__()
self.vg_build_config = vg_build_config
self.count = gaussians.count
self.center = center
self.distance = distance
self.original_gaussians = original_gaussians
if gaussians.positions.isnan().any():
ExLog("LearnableGaussian.__init__() has nan!!!", "ERROR")
exit(-1)
with torch.no_grad():
self.parameters_positions: torch.Tensor = torch.nn.Parameter(
gaussians.positions.clone(), requires_grad=True
)
self.parameters_scales: torch.Tensor = torch.nn.Parameter(
LearnableGaussians.InverseActivationScales(gaussians.scales.clone()),
requires_grad=True,
)
self.parameters_quaternions: torch.Tensor = torch.nn.Parameter(
gaussians.quaternions.clone(), requires_grad=True
)
self.parameters_opacities: torch.Tensor = torch.nn.Parameter(
LearnableGaussians.InverseActivationOpacities(
gaussians.opacities.clone()
),
requires_grad=True,
)
self.parameters_sh0: torch.Tensor = torch.nn.Parameter(
LearnableGaussians.InverseActivationSh0(gaussians.rgbs.clone()),
requires_grad=True,
)
@property
def positions(self) -> torch.Tensor:
return self.parameters_positions
@property
def scales(self) -> torch.Tensor:
return LearnableGaussians.ActivationScales(self.parameters_scales)
@property
def quaternions(self) -> torch.Tensor:
return LearnableGaussians.ActivationQauternions(self.parameters_quaternions)
@property
def opacities(self) -> torch.Tensor:
return LearnableGaussians.ActivationOpacities(self.parameters_opacities)
@property
def rgbs(self) -> torch.Tensor:
return LearnableGaussians.ActivationSh0(self.parameters_sh0)
# NOTICE: Directly call functions in class Cluster.
def render(self, *args, **kwargs):
return Cluster.render(self, *args, **kwargs)
def renderReturnCountAndDuration(self, *args, **kwargs):
return Cluster.renderReturnCountAndDuration(self, *args, **kwargs)
def renderFullImageConsolidatingSixDirections(self, *args, **kwargs):
return Cluster.renderFullImageConsolidatingSixDirections(self, *args, **kwargs)
def train(self) -> None:
# https://pytorch.org/docs/stable/optim.html
parameters = [
{
"params": [self.parameters_positions],
"lr": self.vg_build_config.SIMPLIFICATION_LEARNING_RATE_POSITION,
},
{
"params": [self.parameters_scales],
"lr": self.vg_build_config.SIMPLIFICATION_LEARNING_RATE_SCALE,
},
{
"params": [self.parameters_quaternions],
"lr": self.vg_build_config.SIMPLIFICATION_LEARNING_RATE_QUATERNION,
},
{
"params": [self.parameters_opacities],
"lr": self.vg_build_config.SIMPLIFICATION_LEARNING_RATE_OPACITY,
},
{
"params": [self.parameters_sh0],
"lr": self.vg_build_config.SIMPLIFICATION_LEARNING_RATE_SH0,
},
]
optimizer = torch.optim.Adam(parameters, lr=0.0, eps=1e-15)
# DEBUG save intermediate results
current_time_str = datetime.datetime.now(
tz=zoneinfo.ZoneInfo("Asia/Shanghai")
).strftime("%y%m%d-%H%M%S")
if self.vg_build_config.SAVE_IMAGES_DURING_OPTIMIZATION:
UTILITY.SaveImage(
self.original_gaussians.renderFullImageConsolidatingSixDirections(
center=self.center, distance=self.distance
),
self.vg_build_config.OUTPUT_FOLDER_PATH
/ f"images/{current_time_str}-original.png",
)
for iter in range(self.vg_build_config.SIMPLIFICATION_ITERATION + 1):
# [calculate loss]
random_camera_looking_at_center = Camera.DeriveRandomPoseLookingAtOrigin(
center=self.center[0], radius=self.distance
)
# (4, h, w)
image_gt: torch.Tensor = self.original_gaussians.render(
camera=random_camera_looking_at_center
)
image_render: torch.Tensor = self.render(
camera=random_camera_looking_at_center
)
if self.vg_build_config.SAVE_IMAGES_DURING_OPTIMIZATION:
if iter % 160 == 0:
UTILITY.SaveImage(
self.renderFullImageConsolidatingSixDirections(
center=self.center, distance=self.distance
),
self.vg_build_config.OUTPUT_FOLDER_PATH
/ f"images/{current_time_str}-iter{iter}.png",
)
# add black background
loss_l1: torch.Tensor = UTILITY.L1Loss(
image=image_render[:3] * image_render[3],
target=image_gt[:3] * image_gt[3],
)
ssim: torch.Tensor = UTILITY.Ssim(
image=image_render[:3] * image_render[3],
target=image_gt[:3] * image_gt[3],
)
loss_dssim: torch.Tensor = 1.0 - ssim
# add alpha channel supervision here
loss: torch.Tensor = (
(1.0 - self.vg_build_config.SIMPLIFICATION_LOSS_LAMBDA_DSSIM) * loss_l1
+ self.vg_build_config.SIMPLIFICATION_LOSS_LAMBDA_DSSIM * loss_dssim
+ 0.1 * torch.abs((image_render[3] - image_gt[3])).mean()
)
# [backward]
optimizer.zero_grad()
loss.backward()
optimizer.step()
def toGaussians(self, lod_level: int) -> Cluster:
return Cluster(
vg_build_config=self.vg_build_config,
count=self.count,
positions=self.positions.clone().detach().requires_grad_(False),
scales=self.scales.clone().detach().requires_grad_(False),
quaternions=self.quaternions.clone().detach().requires_grad_(False),
opacities=self.opacities.clone().detach().requires_grad_(False),
rgbs=self.rgbs.clone().detach().requires_grad_(False),
lod_level=lod_level,
)
class ClustersList:
def __init__(
self,
vg_build_config: VGBuildConfig,
clusters_list: list[Clusters],
) -> None:
self.vg_build_config = vg_build_config
self.clusters_list: list[Clusters] = clusters_list
self.count: int = len(self.clusters_list)
def append(self, clusters: Clusters) -> None:
self.clusters_list.append(clusters)
self.count = len(self.clusters_list)
def extend(self, clusters_list: list[Clusters]) -> None:
self.clusters_list.extend(clusters_list)
self.count = len(self.clusters_list)
def consolidateIntoClusters(self) -> Clusters:
clusters: list[Cluster] = functools.reduce(
lambda a, b: a + b.clusters, self.clusters_list, []
)
return Clusters(
vg_build_config=self.vg_build_config, clusters=clusters, lod_level=None
)
def savePlyWithDifferentColors(self, path: pathlib.Path) -> None:
color_choices = np.random.randint(
low=0, high=255, size=(self.count, 3), dtype=np.uint8
)
ply_points = np.concatenate(
[
np.concatenate(
[
clusters.consolidateIntoASingleCluster()
.positions.cpu()
.numpy(),
np.zeros(
clusters.consolidateIntoASingleCluster().positions.shape,
dtype=np.uint8,
)
+ color_choices[i],
],
axis=1,
)
for i, clusters in enumerate(self.clusters_list)
],
axis=0,
)
ply_properties = [
("x", "f4"),
("y", "f4"),
("z", "f4"),
] + [
("red", "u1"),
("green", "u1"),
("blue", "u1"),
]
UTILITY.SavePlyUsingPlyfilePackage(
path=path,
points=ply_points,
properties=ply_properties,
)
ExLog(f"Save {self.count} cluster groups at {path}.")
def saveBundle(self) -> None:
# [save clusters.npz]
clusters_count = 0
for clusters in self.clusters_list:
clusters_count += clusters.count
ExLog(
f"LOD{clusters.lod_level}, {clusters.count} clusters, gaussians in each cluster {[cluster.count for cluster in clusters.clusters]}",
"DEBUG",
)
lod_levels = np.zeros((clusters_count, 1), dtype=np.int32)
start_indices = np.zeros((clusters_count, 1), dtype=np.int32)
counts = np.zeros((clusters_count, 1), dtype=np.int32)
child_centers = np.zeros((clusters_count, 3), dtype=np.float32)
parent_centers = np.zeros((clusters_count, 3), dtype=np.float32)
child_radii = np.zeros((clusters_count, 1), dtype=np.float32)
parent_radii = np.zeros((clusters_count, 1), dtype=np.float32)
start_index = 0
i_cluster = 0
for clusters in self.clusters_list:
for cluster in clusters.clusters:
lod_levels[i_cluster] = cluster.lod_level
start_indices[i_cluster] = start_index
counts[i_cluster] = cluster.count
child_centers[i_cluster] = cluster.child_center_in_cluster_group
parent_centers[i_cluster] = cluster.parent_center_in_cluster_group
child_radii[i_cluster] = cluster.child_radius_in_cluster_group
parent_radii[i_cluster] = cluster.parent_radius_in_cluster_group
start_index += cluster.count
i_cluster += 1
np.savez(
self.vg_build_config.BUNDLE_CLUSTERS_NPZ_PATH,
lod_levels=lod_levels,
start_indices=start_indices,
counts=counts,
child_centers=child_centers,
parent_centers=parent_centers,
child_radii=child_radii,
parent_radii=parent_radii,
)
# [save gaussians.npz]
np.savez(
self.vg_build_config.BUNDLE_GAUSSIANS_NPZ_PATH,
positions=np.concatenate(
[
cluster.positions.cpu().numpy()
for cluster in self.consolidateIntoClusters().clusters
],
axis=0,
),
scales=np.concatenate(
[
cluster.scales.cpu().numpy()
for cluster in self.consolidateIntoClusters().clusters
],
axis=0,
),
quaternions=np.concatenate(
[
cluster.quaternions.cpu().numpy()
for cluster in self.consolidateIntoClusters().clusters
],
axis=0,
),
opacities=np.concatenate(
[
cluster.opacities.cpu().numpy()
for cluster in self.consolidateIntoClusters().clusters
],
axis=0,
),
rgbs=np.concatenate(
[
cluster.rgbs.cpu().numpy()
for cluster in self.consolidateIntoClusters().clusters
],
axis=0,
),
)
class Clusters:
def __init__(
self,
clusters: list[Cluster],
vg_build_config: VGBuildConfig = None,
lod_level: int | None = None,
) -> None:
"""
Assign `lod_level` an int if all clusters are at the same lod level.
"""
self.vg_build_config = vg_build_config
self.clusters = clusters
self.count = len(self.clusters)
self.lod_level = lod_level
def updatePositionsOfAllClusters(self) -> None:
# 241105 change property of positions to instance variable
positions_of_all_clusters = torch.zeros((self.count, 3), dtype=torch.float32)
for i_cluster in range(self.count):
positions_of_all_clusters[i_cluster] = self.clusters[i_cluster].getCenter()
self.positions = positions_of_all_clusters
def append(self, cluster: Cluster) -> None:
self.clusters.append(cluster)
self.count = len(self.clusters)
def extend(self, clusters: list[Cluster]) -> None:
self.clusters.extend(clusters)
self.count = len(self.clusters)
def consolidateIntoASingleCluster(self) -> Cluster:
count_simplified = sum([c.count for c in self.clusters])
positions_simplified = torch.cat([c.positions for c in self.clusters], dim=0)
scales_simplified = torch.cat([c.scales for c in self.clusters], dim=0)
quaternions_simplified = torch.cat(
[c.quaternions for c in self.clusters], dim=0
)
opacities_simplified = torch.cat([c.opacities for c in self.clusters], dim=0)
rgbs_simplified = torch.cat([c.rgbs for c in self.clusters], dim=0)
return Cluster(
vg_build_config=self.vg_build_config,
count=count_simplified,
positions=positions_simplified,
scales=scales_simplified,
quaternions=quaternions_simplified,
opacities=opacities_simplified,
rgbs=rgbs_simplified,
lod_level=self.lod_level,
)
def splitIntoClusterGroups(self) -> ClustersList:
# # [clusters -> cluster groups]
# count_cluster_groups = int(
# self.count
# / self.vg_build_config.BUILD_APPROPRIATE_COUNT_OF_CLUSTERS_IN_ONE_CLUSTER_GROUP
# )
# if count_cluster_groups >= 2:
# cluster_centers = np.zeros((self.count, 3))
# for i_cluster_group in range(self.count):
# cluster_centers[i_cluster_group] = (
# self.clusters[i_cluster_group].positions.mean(dim=0).cpu()
# )
# with ExTimer("kmeans"):
# kmeans = sklearn.cluster.MiniBatchKMeans(
# n_clusters=count_cluster_groups,
# init="k-means++",
# n_init="auto",
# random_state=0,
# ).fit(cluster_centers)
# labels = torch.from_numpy(kmeans.labels_)
# cluster_groups: ClustersList = ClustersList(
# vg_build_config=self.vg_build_config, clusters_list=[]
# )
# with ExTimer("form CG"):
# # find clusters in current cluster group
# for i_cluster_group in range(count_cluster_groups):
# cluster_group: Clusters = Clusters(
# vg_build_config=self.vg_build_config,
# clusters=[
# self.clusters[c]
# for c in torch.where(labels == i_cluster_group)[0]
# ],
# lod_level=self.lod_level,
# )
# ExLog(f"{i_cluster_group=} {cluster_group.count=} clusters.counts={[cluster.count for cluster in cluster_group.clusters]}", "DEBUG")
# if cluster_group.count >= 2:
# cluster_groups.append(cluster_group)
# else:
# # only one cluster group
# cluster_groups: ClustersList = ClustersList(
# vg_build_config=self.vg_build_config, clusters_list=[self]
# )
# cluster_groups.savePlyWithDifferentColors(
# path=self.vg_build_config.OUTPUT_FOLDER_PATH
# / f"plys/lod{self.lod_level}-to-lod{self.lod_level+1}-cluster-groups.ply"
# )
# [new version: replace kmeans with median split]
if (
self.count
> self.vg_build_config.BUILD_APPROPRIATE_COUNT_OF_CLUSTERS_IN_ONE_CLUSTER_GROUP
):
all_complete_cluster_groups: list[Clusters] = []
all_incomplete_cluster_groups: list[Clusters] = [self]
while len(all_incomplete_cluster_groups) != 0:
current_incomplete_cluster_groups: list[Clusters] = []
for incomplete_cluster_group in all_incomplete_cluster_groups:
lengths = torch.tensor(
[
incomplete_cluster_group.positions[:, 0].max().item()
- incomplete_cluster_group.positions[:, 0].min().item(),
incomplete_cluster_group.positions[:, 1].max().item()
- incomplete_cluster_group.positions[:, 1].min().item(),
incomplete_cluster_group.positions[:, 2].max().item()
- incomplete_cluster_group.positions[:, 2].min().item(),
]
)
axis_to_split = lengths.argmax().item()
axis_median = (
incomplete_cluster_group.positions[:, axis_to_split]
.median()
.item()
)
cluster_group_left: Clusters = Clusters(
clusters=[],
vg_build_config=self.vg_build_config,
lod_level=self.lod_level,
)
cluster_group_right: Clusters = Clusters(
clusters=[],
vg_build_config=self.vg_build_config,
lod_level=self.lod_level,
)
for i_cluster in range(incomplete_cluster_group.count):
if (
incomplete_cluster_group.positions[i_cluster, axis_to_split]
<= axis_median
):
cluster_group_left.append(
incomplete_cluster_group.clusters[i_cluster]
)
else:
cluster_group_right.append(
incomplete_cluster_group.clusters[i_cluster]
)
# update positions
cluster_group_left.positions = incomplete_cluster_group.positions[
incomplete_cluster_group.positions[:, axis_to_split]
<= axis_median
]
cluster_group_right.positions = incomplete_cluster_group.positions[
incomplete_cluster_group.positions[:, axis_to_split]
> axis_median
]
# ExLog(
# f"{cluster_group_left.positions.shape=} {cluster_group_right.positions.shape=}",
# "DEBUG",
# )
if (
cluster_group_left.count
<= self.vg_build_config.BUILD_APPROPRIATE_COUNT_OF_CLUSTERS_IN_ONE_CLUSTER_GROUP
):
all_complete_cluster_groups.append(cluster_group_left)
else:
current_incomplete_cluster_groups.append(cluster_group_left)
if (
cluster_group_right.count
<= self.vg_build_config.BUILD_APPROPRIATE_COUNT_OF_CLUSTERS_IN_ONE_CLUSTER_GROUP
):
all_complete_cluster_groups.append(cluster_group_right)
else:
current_incomplete_cluster_groups.append(cluster_group_right)
# ExLog(
# f"{len(all_complete_clusters)=} {len(all_incomplete_clusters)=} {len(current_incomplete_clusters)=} {incomplete_cluster.count=} {cluster_left.count=} {cluster_right.count=}"
# )
all_incomplete_cluster_groups = current_incomplete_cluster_groups
cluster_groups: ClustersList = ClustersList(
vg_build_config=self.vg_build_config,
clusters_list=all_complete_cluster_groups,
)
else:
# only one cluster group
cluster_groups: ClustersList = ClustersList(
vg_build_config=self.vg_build_config,
clusters_list=[self],
)
cluster_groups.savePlyWithDifferentColors(
path=self.vg_build_config.OUTPUT_FOLDER_PATH
/ f"plys/lod{self.lod_level}-to-lod{self.lod_level+1}-cluster-groups.ply"
)
# ExLog(f"There are {cluster_groups.count} cluster groups.", "DEBUG")
# for i_cluster_group in range(cluster_groups.count):
# current_cluster_group = cluster_groups.clusters_list[i_cluster_group]
# ExLog(
# f"CG_{i_cluster_group}: {current_cluster_group.count} clusters; gaussians in clusters={[cluster.count for cluster in current_cluster_group.clusters]}",
# "DEBUG",
# )
return cluster_groups
def setParentCenterAndRadiusValueForFinerLodLayerInClusterGroup(
self, center: list[float], radius_value: float
) -> None:
for cluster in self.clusters:
cluster.parent_radius_in_cluster_group = radius_value
cluster.parent_center_in_cluster_group = center
def setChildCenterAndRadiusValueForCoarserLodLayerInClusterGroup(
self, center: list[float], radius_value: float
) -> None:
for cluster in self.clusters:
cluster.child_radius_in_cluster_group = radius_value
cluster.child_center_in_cluster_group = center
def buildCoarserLodLayer(self) -> Clusters:
"""
For all clusters in current lod layer, first form cluster groups.
Then for each cluster group, merge, simplify, split to derive coarser clusters.
Finally consolidate all coarser clusters to form the coarser lod layer.
"""
current_lod_layer = self
cluster_groups = current_lod_layer.splitIntoClusterGroups()
ExLog(
f"Cluster Group: {current_lod_layer.count} clusters -> {cluster_groups.count} cluster groups.",
)
coarser_lod_layer: Clusters = Clusters(
vg_build_config=self.vg_build_config,
clusters=[],
lod_level=self.lod_level + 1,
)
ExLog(f"For each cluster group, execute Merge(), Simplify(), Split()...")
for original_clusters_in_cluster_group in tqdm.tqdm(
cluster_groups.clusters_list,
bar_format=r"simplify cluster groups |{bar}| {n_fmt}/{total_fmt} {rate_fmt} {elapsed} ",
):
# [merge]
original_gaussians_in_cluster_group: Cluster = (
original_clusters_in_cluster_group.consolidateIntoASingleCluster()
)
# [simplify]
simplified_gaussians_in_cluster_group = (
original_gaussians_in_cluster_group.downSampleHalf()
)
if self.vg_build_config.SIMPLIFICATION_ITERATION != 0:
simplified_gaussians_in_cluster_group = (
simplified_gaussians_in_cluster_group.optimizeUsingLocalSplatting(
original_gaussians_in_cluster_group
)
)
if simplified_gaussians_in_cluster_group.count == 0:
ExLog(f"[ERROR]", f"{original_gaussians_in_cluster_group.count=}")
exit(-1)
# [split]
simplified_clusters_in_cluster_group = (
simplified_gaussians_in_cluster_group.splitIntoClusters()
)
# [calculate and set value for selection]
# 240809-0910: use original_gaussians instead of simplified_gaussians
cluster_group_center = original_gaussians_in_cluster_group.getCenter()
# 240809-0910: use original_gaussians instead of simplified_gaussians
# ensure monotonic for selection in parallel
cluster_group_radius_value = max(
original_gaussians_in_cluster_group.getRadiusValueInClusterGroupForSelection(),
max(
[
cluster.child_radius_in_cluster_group
for cluster in original_clusters_in_cluster_group.clusters
]
),
)
original_clusters_in_cluster_group.setParentCenterAndRadiusValueForFinerLodLayerInClusterGroup(
center=cluster_group_center.reshape((3,)).tolist(),
radius_value=cluster_group_radius_value,
)
simplified_clusters_in_cluster_group.setChildCenterAndRadiusValueForCoarserLodLayerInClusterGroup(
center=cluster_group_center.reshape((3,)).tolist(),
radius_value=cluster_group_radius_value,
)
# [collect clusters in coarser lod layer]
coarser_lod_layer.extend(simplified_clusters_in_cluster_group.clusters)
return coarser_lod_layer
def savePlyWithDifferentColors(
self,
path: pathlib.Path,
) -> None:
color_choices = np.random.randint(
low=0, high=255, size=(self.count, 3), dtype=np.uint8
)
ply_points = np.concatenate(
[
np.concatenate(
[
cluster.positions.cpu().numpy(),
np.zeros(cluster.positions.shape, dtype=np.uint8)
+ color_choices[i],
],
axis=1,
)
for i, cluster in enumerate(self.clusters)
],
axis=0,
)
ply_properties = [
("x", "f4"),
("y", "f4"),
("z", "f4"),
] + [
("red", "u1"),
("green", "u1"),
("blue", "u1"),
]