forked from openvdb/fvdb-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrid_batch.py
More file actions
2004 lines (1533 loc) · 80.8 KB
/
Copy pathgrid_batch.py
File metadata and controls
2004 lines (1533 loc) · 80.8 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
# Copyright Contributors to the OpenVDB Project
# SPDX-License-Identifier: Apache-2.0
#
"""
Batch of sparse grids data structure and operations for FVDB.
This module provides the core GridBatch class for managing batches of sparse voxel grids:
Classes:
- GridBatch: A batch of sparse voxel grids with support for efficient operations
Class-methods for creating GridBatch objects from various sources:
- :meth:`GridBatch.from_zero_grids()`: for an empty grid batch where grid-count = 0.
- :meth:`GridBatch.from_zero_voxels()`: for a grid batch where each grid has zero voxels.
- :meth:`GridBatch.from_dense()`: for a grid batch where each grid is dense data
- :meth:`GridBatch.from_dense_axis_aligned_bounds()`: for a grid batch where each grid is dense data defined by axis-aligned bounds
- :meth:`GridBatch.from_ijk()`: for a grid batch from explicit voxel coordinates
- :meth:`GridBatch.from_mesh()`: for a grid batch from triangle meshes
- :meth:`GridBatch.from_points()`: for a grid batch from point clouds
- :meth:`GridBatch.from_nearest_voxels_to_points()`: for a grid batch from nearest voxels to points
Class/Instance-methods for loading and saving grids:
- from_nanovdb/save_nanovdb: Load and save grid batches to/from .nvdb files
GridBatch supports operations like convolution, pooling, interpolation, ray casting,
mesh extraction, and coordinate transformations on sparse voxel data.
"""
from collections.abc import Iterator
from typing import TYPE_CHECKING, Any, Sequence, overload
import numpy as np
import torch
from . import _fvdb_cpp, _parse_device_string
from .jagged_tensor import JaggedTensor
from .types import DeviceIdentifier, GridBatchIndex, NumericMaxRank1, NumericMaxRank2
if TYPE_CHECKING:
from .grid import Grid
class GridBatch:
"""
A batch of sparse voxel grids with support for efficient operations.
:class:`GridBatch` represents a collection of sparse 3D voxel grids that can be processed
together efficiently on GPU. Each grid in the batch can have different resolutions,
origins, and voxel sizes. The class provides methods for common operations like
sampling, convolution, pooling, dilation, union, etc. It also provides more advanced features
such as marching cubes, TSDF fusion, and fast ray marching.
A :class:`GridBatch` can be thought of as a mini-batch of sparse grids and
does not collect the sparse voxel grids' data but only collects
their structure (or topology). Voxel data (e.g., features, colors, densities) for the
collection of grids is stored separately as an :class:`JaggedTensor` associated with
the :class:`GridBatch`. This separation allows for flexibility in the type and number of
channels of data with which a grid can be used to index into. This also allows multiple grids to
share the same data storage if desired.
When using a :class:`GridBatch`, there are three important coordinate systems
to be aware of:
- **World Space**: The continuous 3D coordinate system in which each grid in the batch exists.
- **Voxel Space**: The discrete voxel index system of each grid in the batch, where each voxel is identified by its integer indices (i, j, k).
- **Index Space**: The linear indexing of active voxels in each grid's internal storage.
At its core, a :class:`GridBatch` uses a very fast mapping from each grid's voxel space into
index space to perform operations on a :class:`fvdb.JaggedTensor` of data associated with the
grids in the batch. This mapping allows for efficient access and manipulation of voxel data.
For example:
.. code-block:: python
voxel_coords = torch.tensor([[8, 7, 6], [1, 2, 3], [4, 5, 6]], device="cuda") # Voxel space coordinates
batch_voxel_coords = fvdb.JaggedTensor(
[voxel_coords, voxel_coords + 44, voxel_coords - 44]
) # Voxel space coordinates for 3 grids in the batch
# Create a GridBatch containing 3 grids with the 3 sets of voxel coordinates such that the voxels
# have a world space size of 1x1x1, and where the [0, 0, 0] voxel in voxel space of each grid is at world space origin (0, 0, 0).
grid_batch = fvdb.GridBatch.from_ijk(batch_voxel_coords, voxel_sizes=1.0, origins=0.0)
# Create some data associated with the grids - here we have 9 voxels and 2 channels per voxel
voxel_data = torch.randn(grid_batch.total_voxels, 2, device="cuda") # Index space data
# Map voxel space coordinates to index space
indices = grid_batch.ijk_to_index(batch_voxel_coords, cumulative=True).jdata # Shape: (9,)
# Access the data for the specified voxel coordinates
selected_data = voxel_data[indices] # Shape: (9, 2)
.. note::
A :class:`GridBatch` may contain zero grids, in which case it has no voxel sizes nor origins
that can be queried. It may also contain one or more empty grids, which means grids that
have zero voxels. An empty grid still has a voxel size and origin, which can be queried.
.. note::
The grids are stored in a sparse format using `NanoVDB <https://github.com/AcademySoftwareFoundation/openvdb/tree/feature/nanovdb>`_
where only active (non-empty) voxels are allocated, making it extremely memory efficient for representing large volumes with sparse
occupancy.
.. note::
The :class:`GridBatch` constructor is for internal use only. To create a :class:`GridBatch` with actual content, use the classmethods:
- :meth:`from_zero_grids()`: for an empty grid batch where grid-count = 0.
- :meth:`from_zero_voxels()`: for a grid batch where each grid has zero voxels.
- :meth:`from_dense()`: for a grid batch where each grid is dense data
- :meth:`from_dense_axis_aligned_bounds()`: for a grid batch where each grid is dense data defined by axis-aligned bounds
- :meth:`from_ijk()`: for a grid batch from explicit voxel coordinates
- :meth:`from_mesh()`: for a grid batch from triangle meshes
- :meth:`from_points()`: for a grid batch from point clouds
- :meth:`from_nearest_voxels_to_points()`: for a grid batch from nearest voxels to points
- :meth:`from_cat()`: for a grid batch from concatenating other grids and grid batches
Attributes:
max_grids_per_batch (int): Maximum number of grids that can be stored in a single :class:`fvdb.GridBatch`.
"""
__slots__ = ("data",)
#: :meta private: # NOTE: This is here for sphinx to not complain that the attribute is double defined in the class and in the class documentation.
max_grids_per_batch: int = _fvdb_cpp.GridBatchData.MAX_GRIDS_PER_BATCH
def __init__(self, *, data: "_fvdb_cpp.GridBatchData") -> None:
"""Internal constructor -- use ``GridBatch.from_*`` classmethods instead.
Args:
data (_fvdb_cpp.GridBatchData): The underlying C++ grid batch data object.
"""
object.__setattr__(self, "data", data)
def __setattr__(self, name: str, value: Any) -> None:
raise AttributeError("GridBatch is immutable")
def __getstate__(self) -> dict:
return {"data": self.data}
def __setstate__(self, state: dict) -> None:
object.__setattr__(self, "data", state["data"])
# ============================================================
# GridBatch from_* constructors
# ============================================================
@classmethod
def from_dense(
cls,
num_grids: int,
dense_dims: NumericMaxRank1,
ijk_min: NumericMaxRank1 = 0,
voxel_sizes: NumericMaxRank2 = 1,
origins: NumericMaxRank2 = 0,
mask: torch.Tensor | None = None,
device: DeviceIdentifier | None = None,
) -> "GridBatch":
"""Create a grid batch of dense grids from dimensions and an optional mask.
Args:
num_grids (int): Number of grids to create.
dense_dims (NumericMaxRank1): Dimensions of the dense grid, broadcastable to shape ``(3,)``, integer dtype.
ijk_min (NumericMaxRank1): Minimum voxel index for all grids, broadcastable to shape ``(3,)``, integer dtype.
voxel_sizes (NumericMaxRank2): World-space size of each voxel, per-grid; broadcastable to
shape ``(num_grids, 3)``, floating dtype.
origins (NumericMaxRank2): World-space origin of each grid, per-grid; broadcastable to
shape ``(num_grids, 3)``, floating dtype.
mask (torch.Tensor | None): Optional boolean mask with shape ``(W, H, D)`` selecting active voxels.
device (DeviceIdentifier | None): Device to create the grid batch on. Defaults to ``None``.
Returns:
grid_batch (GridBatch): A new :class:`GridBatch` of dense grids.
.. seealso:: :meth:`Grid.from_dense`
"""
from . import functional
return functional.gridbatch_from_dense(num_grids, dense_dims, ijk_min, voxel_sizes, origins, mask, device)
@classmethod
def from_dense_axis_aligned_bounds(
cls,
num_grids: int,
dense_dims: NumericMaxRank1,
bounds_min: NumericMaxRank1 = 0,
bounds_max: NumericMaxRank1 = 1,
voxel_center: bool = False,
device: DeviceIdentifier = "cpu",
) -> "GridBatch":
"""Create a grid batch of dense grids defined by axis-aligned world-space bounds.
Args:
num_grids (int): Number of grids to create.
dense_dims (NumericMaxRank1): Dimensions of the dense grids, broadcastable to shape ``(3,)``, integer dtype.
bounds_min (NumericMaxRank1): Minimum world-space coordinate, broadcastable to shape ``(3,)``, floating dtype.
bounds_max (NumericMaxRank1): Maximum world-space coordinate, broadcastable to shape ``(3,)``, floating dtype.
voxel_center (bool): Whether bounds correspond to voxel centers (``True``) or edges (``False``).
device (DeviceIdentifier): Device to create the grids on. Defaults to ``"cpu"``.
Returns:
grid_batch (GridBatch): A new :class:`GridBatch` of dense grids.
.. seealso:: :meth:`Grid.from_dense_axis_aligned_bounds`
"""
from . import functional
return functional.gridbatch_from_dense_axis_aligned_bounds(
num_grids, dense_dims, bounds_min, bounds_max, voxel_center, device
)
@classmethod
def from_ijk(
cls,
ijk: JaggedTensor,
voxel_sizes: NumericMaxRank2 = 1,
origins: NumericMaxRank2 = 0,
) -> "GridBatch":
"""Create a grid batch from explicit voxel-space coordinates.
Args:
ijk (JaggedTensor): Per-grid voxel coordinates. Shape: ``(batch_size, num_voxels_for_grid_b, 3)``, integer dtype.
voxel_sizes (NumericMaxRank2): Size of each voxel, per-grid; broadcastable to shape ``(batch_size, 3)``, floating dtype.
origins (NumericMaxRank2): World-space origin of each grid, per-grid; broadcastable to shape ``(batch_size, 3)``, floating dtype.
Returns:
grid_batch (GridBatch): A new :class:`GridBatch` with the specified voxel coordinates.
.. seealso:: :meth:`Grid.from_ijk`
"""
from . import functional
return functional.gridbatch_from_ijk(ijk, voxel_sizes, origins)
@classmethod
def from_mesh(
cls,
mesh_vertices: JaggedTensor,
mesh_faces: JaggedTensor,
voxel_sizes: NumericMaxRank2 = 1,
origins: NumericMaxRank2 = 0,
) -> "GridBatch":
"""Create a grid batch by voxelizing the surface of triangle meshes.
Args:
mesh_vertices (JaggedTensor): Per-grid mesh vertex positions. Shape: ``(batch_size, num_vertices_for_grid_b, 3)``.
mesh_faces (JaggedTensor): Per-grid mesh face indices. Shape: ``(batch_size, num_faces_for_grid_b, 3)``.
voxel_sizes (NumericMaxRank2): Size of each voxel, per-grid; broadcastable to shape ``(batch_size, 3)``, floating dtype.
origins (NumericMaxRank2): World-space origin of each grid, per-grid; broadcastable to shape ``(batch_size, 3)``, floating dtype.
Returns:
grid_batch (GridBatch): A new :class:`GridBatch` with voxels covering mesh surfaces.
.. seealso:: :meth:`Grid.from_mesh`
"""
from . import functional
return functional.gridbatch_from_mesh(mesh_vertices, mesh_faces, voxel_sizes, origins)
# Load and save functions
@overload
@classmethod
def from_nanovdb(
cls,
path: str,
*,
device: DeviceIdentifier = "cpu",
verbose: bool = False,
) -> "tuple[GridBatch, JaggedTensor, list[str]]": ...
@overload
@classmethod
def from_nanovdb(
cls,
path: str,
*,
indices: list[int],
device: DeviceIdentifier = "cpu",
verbose: bool = False,
) -> "tuple[GridBatch, JaggedTensor, list[str]]": ...
@overload
@classmethod
def from_nanovdb(
cls,
path: str,
*,
index: int,
device: DeviceIdentifier = "cpu",
verbose: bool = False,
) -> "tuple[GridBatch, JaggedTensor, list[str]]": ...
@overload
@classmethod
def from_nanovdb(
cls,
path: str,
*,
names: list[str],
device: DeviceIdentifier = "cpu",
verbose: bool = False,
) -> "tuple[GridBatch, JaggedTensor, list[str]]": ...
@overload
@classmethod
def from_nanovdb(
cls,
path: str,
*,
name: str,
device: DeviceIdentifier = "cpu",
verbose: bool = False,
) -> "tuple[GridBatch, JaggedTensor, list[str]]": ...
@classmethod
def from_nanovdb(
cls,
path: str,
*,
indices: list[int] | None = None,
index: int | None = None,
names: list[str] | None = None,
name: str | None = None,
device: DeviceIdentifier = "cpu",
verbose: bool = False,
) -> "tuple[GridBatch, JaggedTensor, list[str]]":
"""Load a grid batch from a .nvdb file.
Args:
path (str): Path to the .nvdb file to load.
indices (list[int] | None): Optional list of grid indices to load.
index (int | None): Optional single grid index to load.
names (list[str] | None): Optional list of grid names to load.
name (str | None): Optional single grid name to load.
device (DeviceIdentifier): Device to load the grid batch on. Defaults to ``"cpu"``.
verbose (bool): If ``True``, print information about the loaded grids.
Returns:
grid_batch (GridBatch): A :class:`GridBatch` containing the loaded grids.
data (JaggedTensor): A :class:`JaggedTensor` containing voxel data.
names (list[str]): Names of each loaded grid.
.. seealso:: :meth:`Grid.from_nanovdb`
"""
from . import functional
if indices is not None:
return functional.load_nanovdb(path, indices=indices, device=device, verbose=verbose)
elif index is not None:
return functional.load_nanovdb(path, index=index, device=device, verbose=verbose)
elif names is not None:
return functional.load_nanovdb(path, names=names, device=device, verbose=verbose)
elif name is not None:
return functional.load_nanovdb(path, name=name, device=device, verbose=verbose)
else:
return functional.load_nanovdb(path, device=device, verbose=verbose)
@classmethod
def from_nearest_voxels_to_points(
cls,
points: JaggedTensor,
voxel_sizes: NumericMaxRank2 = 1,
origins: NumericMaxRank2 = 0,
) -> "GridBatch":
"""Create a grid batch by adding the eight nearest voxels to every input point.
Args:
points (JaggedTensor): Per-grid world-space point positions. Shape: ``(batch_size, num_points_for_grid_b, 3)``.
voxel_sizes (NumericMaxRank2): Size of each voxel, per-grid; broadcastable to shape ``(batch_size, 3)``, floating dtype.
origins (NumericMaxRank2): World-space origin of each grid, per-grid; broadcastable to shape ``(batch_size, 3)``, floating dtype.
Returns:
grid_batch (GridBatch): A new :class:`GridBatch` with voxels surrounding each point.
.. seealso:: :meth:`Grid.from_nearest_voxels_to_points`
"""
from . import functional
return functional.gridbatch_from_nearest_voxels_to_points(points, voxel_sizes, origins)
@classmethod
def from_points(
cls,
points: JaggedTensor,
voxel_sizes: NumericMaxRank2 = 1,
origins: NumericMaxRank2 = 0,
) -> "GridBatch":
"""Create a grid batch from point clouds by voxelizing each point's location.
Args:
points (JaggedTensor): Per-grid world-space point positions. Shape: ``(batch_size, num_points_for_grid_b, 3)``.
voxel_sizes (NumericMaxRank2): Size of each voxel, per-grid; broadcastable to shape ``(batch_size, 3)``, floating dtype.
origins (NumericMaxRank2): World-space origin of each grid, per-grid; broadcastable to shape ``(batch_size, 3)``, floating dtype.
Returns:
grid_batch (GridBatch): A new :class:`GridBatch` with one voxel per occupied point location.
.. seealso:: :meth:`Grid.from_points`
"""
from . import functional
return functional.gridbatch_from_points(points, voxel_sizes, origins)
@classmethod
def from_zero_grids(cls, device: DeviceIdentifier = "cpu") -> "GridBatch":
"""Create an empty grid batch containing zero grids.
Args:
device (DeviceIdentifier): Device to create the grid batch on. Defaults to ``"cpu"``.
Returns:
grid_batch (GridBatch): A new empty :class:`GridBatch` with ``grid_count == 0``.
"""
from . import functional
return functional.gridbatch_from_zero_grids(device)
@classmethod
def from_zero_voxels(
cls, device: DeviceIdentifier = "cpu", voxel_sizes: NumericMaxRank2 = 1, origins: NumericMaxRank2 = 0
) -> "GridBatch":
"""Create a grid batch with one or more grids that each have zero active voxels.
Args:
device (DeviceIdentifier): Device to create the grid batch on. Defaults to ``"cpu"``.
voxel_sizes (NumericMaxRank2): Voxel size per grid, broadcastable to shape ``(num_grids, 3)``, floating dtype.
origins (NumericMaxRank2): World-space origin per grid, broadcastable to shape ``(num_grids, 3)``, floating dtype.
Returns:
grid_batch (GridBatch): A new :class:`GridBatch` with zero-voxel grids.
.. seealso:: :meth:`Grid.from_zero_voxels`
"""
from . import functional
return functional.gridbatch_from_zero_voxels(device, voxel_sizes, origins)
@classmethod
def from_cat(cls, grids: "Sequence[GridBatch | Grid]") -> "GridBatch":
"""Create a grid batch by concatenating a sequence of grids or grid batches along the batch dimension.
Args:
grids (Sequence[GridBatch | Grid]): Grids or grid batches to concatenate.
Returns:
grid_batch (GridBatch): A new :class:`GridBatch` containing all grids from the inputs.
"""
from . import functional
return functional.concatenate_grids(grids)
# ============================================================
# Regular Instance Methods Begin
# ============================================================
def avg_pool(
self,
pool_factor: NumericMaxRank1,
data: JaggedTensor,
stride: NumericMaxRank1 = 0,
coarse_grid: "GridBatch | None" = None,
) -> tuple[JaggedTensor, "GridBatch"]:
"""Apply average pooling to voxel data associated with this grid batch.
Supports backpropagation.
Args:
pool_factor (NumericMaxRank1): Downsample factor, broadcastable to shape ``(3,)``, integer dtype.
data (JaggedTensor): Voxel data to pool. Shape: ``(batch_size, total_voxels, channels)``.
stride (NumericMaxRank1): Pooling stride; if ``0``, equals ``pool_factor``. Broadcastable to shape ``(3,)``, integer dtype.
coarse_grid (GridBatch | None): Optional pre-allocated coarse grid batch for output.
Returns:
pooled_data (JaggedTensor): Pooled voxel data. Shape: ``(batch_size, coarse_total_voxels, channels)``.
coarse_grid (GridBatch): The coarse grid batch topology after pooling.
.. seealso:: :meth:`Grid.avg_pool`
"""
from . import functional
return functional.avg_pool_batch(self, pool_factor, data, stride, coarse_grid)
def bbox_at(self, bi: int) -> torch.Tensor:
"""Get the voxel-space bounding box of a specific grid in this grid batch.
Args:
bi (int): Batch index of the grid.
Returns:
bbox (torch.Tensor): Bounding box of shape ``(2, 3)`` as ``[[bmin_i, bmin_j, bmin_k], [bmax_i, bmax_j, bmax_k]]``.
"""
# There's a quirk with zero-voxel grids that we handle here.
if self.has_zero_voxels_at(bi):
return torch.zeros((2, 3), dtype=torch.int32, device=self.device)
else:
return self.data.bbox_at(bi)
def clip(
self, features: JaggedTensor, ijk_min: NumericMaxRank2, ijk_max: NumericMaxRank2
) -> tuple[JaggedTensor, "GridBatch"]:
"""Clip voxels and their features to a bounding box range for this grid batch.
Supports backpropagation.
Args:
features (JaggedTensor): Voxel features to clip. Shape: ``(batch_size, total_voxels, channels)``.
ijk_min (NumericMaxRank2): Minimum voxel-space bounds, broadcastable to shape ``(batch_size, 3)``, integer dtype.
ijk_max (NumericMaxRank2): Maximum voxel-space bounds, broadcastable to shape ``(batch_size, 3)``, integer dtype.
Returns:
clipped_features (JaggedTensor): Clipped voxel features. Shape: ``(batch_size, clipped_total_voxels, channels)``.
clipped_grid (GridBatch): A new :class:`GridBatch` containing only voxels within bounds.
.. seealso:: :meth:`Grid.clip`
"""
from . import functional
return functional.clip_batch(self, features, ijk_min, ijk_max)
def clipped_grid(
self,
ijk_min: NumericMaxRank2,
ijk_max: NumericMaxRank2,
) -> "GridBatch":
"""Return a new grid batch clipped to a voxel-space bounding box for this grid batch.
Args:
ijk_min (NumericMaxRank2): Minimum voxel-space bounds, broadcastable to shape ``(batch_size, 3)``, integer dtype.
ijk_max (NumericMaxRank2): Maximum voxel-space bounds, broadcastable to shape ``(batch_size, 3)``, integer dtype.
Returns:
clipped_grid (GridBatch): A new :class:`GridBatch` containing only voxels within bounds.
.. seealso:: :meth:`Grid.clipped_grid`
"""
from . import functional
return functional.clipped_grid_batch(self, ijk_min, ijk_max)
def coarsened_grid(self, coarsening_factor: NumericMaxRank1) -> "GridBatch":
"""Return a coarsened version of this grid batch by keeping every N-th voxel.
Args:
coarsening_factor (NumericMaxRank1): Coarsening factor, broadcastable to shape ``(3,)``, integer dtype.
Returns:
coarsened_grid (GridBatch): A new coarsened :class:`GridBatch`.
.. seealso:: :meth:`Grid.coarsened_grid`
"""
from . import functional
return functional.coarsened_grid_batch(self, coarsening_factor)
def contiguous(self) -> "GridBatch":
"""Return a contiguous copy of this grid batch in memory.
Returns:
grid_batch (GridBatch): A new :class:`GridBatch` with contiguous memory layout.
.. seealso:: :meth:`Grid.contiguous`
"""
from . import functional
return functional.contiguous_batch(self)
def conv_grid(self, kernel_size: NumericMaxRank1, stride: NumericMaxRank1 = 1) -> "GridBatch":
"""Return the output grid topology for a convolution applied to this grid batch.
Args:
kernel_size (NumericMaxRank1): Convolution kernel size, broadcastable to shape ``(3,)``, integer dtype.
stride (NumericMaxRank1): Convolution stride, broadcastable to shape ``(3,)``, integer dtype.
Returns:
conv_grid (GridBatch): A :class:`GridBatch` representing the convolution output topology.
.. seealso:: :meth:`Grid.conv_grid`
"""
from . import functional
return functional.conv_grid_batch(self, kernel_size, stride)
def conv_transpose_grid(self, kernel_size: NumericMaxRank1, stride: NumericMaxRank1 = 1) -> "GridBatch":
"""Return the output grid topology for a transposed convolution applied to this grid batch.
Args:
kernel_size (NumericMaxRank1): Convolution kernel size, broadcastable to shape ``(3,)``, integer dtype.
stride (NumericMaxRank1): Convolution stride, broadcastable to shape ``(3,)``, integer dtype.
Returns:
conv_transpose_grid (GridBatch): A :class:`GridBatch` representing the transposed convolution output topology.
.. seealso:: :meth:`Grid.conv_transpose_grid`
"""
from . import functional
return functional.conv_transpose_grid_batch(self, kernel_size, stride)
def coords_in_grid(self, ijk: JaggedTensor) -> JaggedTensor:
"""Check which voxel-space coordinates lie on active voxels in this grid batch.
Args:
ijk (JaggedTensor): Voxel coordinates to test. Shape: ``(batch_size, num_queries_for_grid_b, 3)``, integer dtype.
Returns:
mask (JaggedTensor): Boolean mask indicating active voxel hits. Shape: ``(batch_size, num_queries_for_grid_b)``.
.. seealso:: :meth:`Grid.coords_in_grid`
"""
from . import functional
return functional.coords_in_grid_batch(self, ijk)
def cpu(self) -> "GridBatch":
"""Move this grid batch to CPU.
Returns:
grid_batch (GridBatch): A new :class:`GridBatch` on CPU device.
.. seealso:: :meth:`Grid.cpu`
"""
return self.to("cpu")
def cubes_in_grid(
self, cube_centers: JaggedTensor, cube_min: NumericMaxRank1 = 0, cube_max: NumericMaxRank1 = 0
) -> JaggedTensor:
"""Check if axis-aligned cubes are fully contained within active voxels of this grid batch.
Args:
cube_centers (JaggedTensor): Cube centers in world coordinates. Shape: ``(batch_size, num_cubes_for_grid_b, 3)``.
cube_min (NumericMaxRank1): Minimum offsets from center, broadcastable to shape ``(3,)``, floating dtype.
cube_max (NumericMaxRank1): Maximum offsets from center, broadcastable to shape ``(3,)``, floating dtype.
Returns:
mask (JaggedTensor): Boolean mask of fully contained cubes. Shape: ``(batch_size, num_cubes_for_grid_b)``.
.. seealso:: :meth:`Grid.cubes_in_grid`
"""
from . import functional
return functional.cubes_in_grid_batch(self, cube_centers, cube_min, cube_max)
def cubes_intersect_grid(
self, cube_centers: JaggedTensor, cube_min: NumericMaxRank1 = 0, cube_max: NumericMaxRank1 = 0
) -> JaggedTensor:
"""Check if axis-aligned cubes intersect any active voxels in this grid batch.
Args:
cube_centers (JaggedTensor): Cube centers in world coordinates. Shape: ``(batch_size, num_cubes_for_grid_b, 3)``.
cube_min (NumericMaxRank1): Minimum offsets from center, broadcastable to shape ``(3,)``, floating dtype.
cube_max (NumericMaxRank1): Maximum offsets from center, broadcastable to shape ``(3,)``, floating dtype.
Returns:
mask (JaggedTensor): Boolean mask of intersecting cubes. Shape: ``(batch_size, num_cubes_for_grid_b)``.
.. seealso:: :meth:`Grid.cubes_intersect_grid`
"""
from . import functional
return functional.cubes_intersect_grid_batch(self, cube_centers, cube_min, cube_max)
def cuda(self) -> "GridBatch":
"""Move this grid batch to CUDA device.
Returns:
grid_batch (GridBatch): A new :class:`GridBatch` on CUDA device.
.. seealso:: :meth:`Grid.cuda`
"""
return self.to("cuda")
def cum_voxels_at(self, bi: int) -> int:
"""Get the cumulative voxel count up to and including a specific grid in this grid batch.
Args:
bi (int): Batch index of the grid.
Returns:
cum_voxels (int): Cumulative number of voxels up to and including grid ``bi``.
"""
return self.data.cum_voxels_at(bi)
def dilated_grid(self, dilation: int) -> "GridBatch":
"""Return a dilated version of this grid batch by expanding active regions.
Args:
dilation (int): Dilation radius in voxels.
Returns:
dilated_grid (GridBatch): A new :class:`GridBatch` with dilated active regions.
.. seealso:: :meth:`Grid.dilated_grid`
"""
from . import functional
return functional.dilated_grid_batch(self, dilation)
def dual_bbox_at(self, bi: int) -> torch.Tensor:
"""Get the dual voxel-space bounding box of a specific grid in this grid batch.
Args:
bi (int): Batch index of the grid.
Returns:
dual_bbox (torch.Tensor): Dual bounding box of shape ``(2, 3)``.
"""
if self.has_zero_voxels_at(bi):
return torch.zeros((2, 3), dtype=torch.int32, device=self.device)
else:
return self.data.dual_bbox_at(bi)
def dual_grid(self, exclude_border: bool = False) -> "GridBatch":
"""Return the dual grid of this grid batch where voxel centers correspond to primal voxel corners.
Args:
exclude_border (bool): If ``True``, excludes border voxels beyond primal grid bounds.
Returns:
dual_grid (GridBatch): A new :class:`GridBatch` representing the dual grid.
.. seealso:: :meth:`Grid.dual_grid`
"""
from . import functional
return functional.dual_grid_batch(self, exclude_border)
def voxel_to_world(self, ijk: JaggedTensor) -> JaggedTensor:
"""Transform voxel-space coordinates to world-space positions for this grid batch.
Supports backpropagation.
Args:
ijk (JaggedTensor): Voxel-space coordinates to convert. Shape: ``(batch_size, num_points_for_grid_b, 3)``.
Returns:
world_coords (JaggedTensor): World-space coordinates. Shape: ``(batch_size, num_points_for_grid_b, 3)``.
.. seealso:: :meth:`Grid.voxel_to_world`
"""
from . import functional
return functional.voxel_to_world_batch(self, ijk)
def has_same_address_and_grid_count(self, other: Any) -> bool:
"""Check if another object shares the same underlying data address and grid count as this grid batch.
Args:
other (Any): Object to compare with.
Returns:
result (bool): ``True`` if both address and grid count match, ``False`` otherwise.
.. seealso:: :meth:`Grid.has_same_address_and_grid_count`
"""
if isinstance(other, GridBatch):
return self.address == other.address and self.grid_count == other.grid_count
else:
return False
def has_zero_voxels_at(self, bi: int) -> bool:
"""Check if a specific grid in this grid batch has zero active voxels.
Args:
bi (int): Batch index of the grid.
Returns:
is_empty (bool): ``True`` if the grid has zero voxels, ``False`` otherwise.
"""
return self.num_voxels_at(bi) == 0
def ijk_to_index(self, ijk: JaggedTensor, cumulative: bool = False) -> JaggedTensor:
"""Convert voxel-space coordinates to linear indices for this grid batch.
Args:
ijk (JaggedTensor): Voxel coordinates to convert. Shape: ``(batch_size, num_queries_for_grid_b, 3)``, integer dtype.
cumulative (bool): If ``True``, return batch-cumulative indices; otherwise per-grid.
Returns:
indices (JaggedTensor): Linear indices, or ``-1`` for inactive voxels. Shape: ``(batch_size, num_queries_for_grid_b)``.
.. seealso:: :meth:`Grid.ijk_to_index`
"""
from . import functional
return functional.ijk_to_index_batch(self, ijk, cumulative)
def ijk_to_inv_index(self, ijk: JaggedTensor, cumulative: bool = False) -> JaggedTensor:
"""Get the inverse permutation of :meth:`ijk_to_index` for this grid batch.
Args:
ijk (JaggedTensor): Voxel coordinates to convert. Shape: ``(batch_size, num_queries_for_grid_b, 3)``, integer dtype.
cumulative (bool): If ``True``, return batch-cumulative indices; otherwise per-grid.
Returns:
inv_map (JaggedTensor): Inverse permutation indices. Shape: ``(batch_size, num_queries_for_grid_b)``.
.. seealso:: :meth:`Grid.ijk_to_inv_index`
"""
from . import functional
return functional.ijk_to_inv_index_batch(self, ijk, cumulative)
def inject_from(
self,
src_grid: "GridBatch",
src: JaggedTensor,
dst: JaggedTensor | None = None,
default_value: float | int | bool = 0,
) -> JaggedTensor:
"""Inject data from a source grid batch into this grid batch in voxel space.
Supports backpropagation.
Args:
src_grid (GridBatch): Source grid batch to inject data from.
src (JaggedTensor): Source data. Shape: ``(batch_size, src_grid.total_voxels, *)``.
dst (JaggedTensor | None): Optional destination data modified in-place, or ``None`` to create new.
default_value (float | int | bool): Fill value for unmapped voxels when ``dst`` is ``None``.
Returns:
dst (JaggedTensor): Data after injection into this grid batch's topology.
.. seealso:: :meth:`Grid.inject_from`
"""
from . import functional
return functional.inject_batch(self, src_grid, src, dst, default_value)
def inject_from_ijk(
self,
src_ijk: JaggedTensor,
src: JaggedTensor,
dst: JaggedTensor | None = None,
default_value: float | int | bool = 0,
):
"""Inject data from explicit voxel coordinates into this grid batch.
Supports backpropagation.
Args:
src_ijk (JaggedTensor): Source voxel coordinates. Shape: ``(batch_size, num_src_voxels, 3)``.
src (JaggedTensor): Source data to inject. Shape: ``(batch_size, num_src_voxels, *)``.
dst (JaggedTensor | None): Optional destination data modified in-place, or ``None`` to create new.
default_value (float | int | bool): Fill value for unmapped voxels when ``dst`` is ``None``.
Returns:
dst (JaggedTensor): Data after injection into this grid batch's topology.
.. seealso:: :meth:`Grid.inject_from_ijk`
"""
from . import functional
return functional.inject_from_ijk_batch(self, src_ijk, src, dst, default_value)
def inject_to(
self,
dst_grid: "GridBatch",
src: JaggedTensor,
dst: JaggedTensor | None = None,
default_value: float | int | bool = 0,
) -> JaggedTensor:
"""Inject data from this grid batch into a destination grid batch in voxel space.
Supports backpropagation.
Args:
dst_grid (GridBatch): Destination grid batch to inject data into.
src (JaggedTensor): Source data from this grid batch. Shape: ``(batch_size, total_voxels, *)``.
dst (JaggedTensor | None): Optional destination data modified in-place, or ``None`` to create new.
default_value (float | int | bool): Fill value for unmapped voxels when ``dst`` is ``None``.
Returns:
dst (JaggedTensor): Data after injection into the destination grid batch's topology.
.. seealso:: :meth:`Grid.inject_to`
"""
from . import functional
return functional.inject_batch(dst_grid, self, src, dst, default_value)
def integrate_tsdf(
self,
truncation_distance: float,
projection_matrices: torch.Tensor,
cam_to_world_matrices: torch.Tensor,
tsdf: JaggedTensor,
weights: JaggedTensor,
depth_images: torch.Tensor,
weight_images: torch.Tensor | None = None,
) -> tuple["GridBatch", JaggedTensor, JaggedTensor]:
"""Integrate depth images into a TSDF volume for this grid batch.
Args:
truncation_distance (float): Maximum TSDF truncation distance in world units.
projection_matrices (torch.Tensor): Camera projection matrices. Shape: ``(batch_size, 3, 3)``.
cam_to_world_matrices (torch.Tensor): Camera-to-world transforms. Shape: ``(batch_size, 4, 4)``.
tsdf (JaggedTensor): Current TSDF values. Shape: ``(batch_size, total_voxels, 1)``.
weights (JaggedTensor): Current integration weights. Shape: ``(batch_size, total_voxels, 1)``.
depth_images (torch.Tensor): Depth images. Shape: ``(batch_size, height, width)``.
weight_images (torch.Tensor | None): Per-pixel weights, or ``None`` for uniform.
Returns:
updated_grid (GridBatch): Updated :class:`GridBatch` with potentially expanded voxels.
updated_tsdf (JaggedTensor): Updated TSDF values.
updated_weights (JaggedTensor): Updated integration weights.
.. seealso:: :meth:`Grid.integrate_tsdf`
"""
from . import functional
return functional.integrate_tsdf_batch(
self,
truncation_distance,
projection_matrices,
cam_to_world_matrices,
tsdf,
weights,
depth_images,
weight_images,
)
def integrate_tsdf_with_features(
self,
truncation_distance: float,
projection_matrices: torch.Tensor,
cam_to_world_matrices: torch.Tensor,
tsdf: JaggedTensor,
features: JaggedTensor,
weights: JaggedTensor,
depth_images: torch.Tensor,
feature_images: torch.Tensor,
weight_images: torch.Tensor | None = None,
) -> tuple["GridBatch", JaggedTensor, JaggedTensor, JaggedTensor]:
"""Integrate depth and feature images into a TSDF volume for this grid batch.
Args:
truncation_distance (float): Maximum TSDF truncation distance in world units.
projection_matrices (torch.Tensor): Camera projection matrices. Shape: ``(batch_size, 3, 3)``.
cam_to_world_matrices (torch.Tensor): Camera-to-world transforms. Shape: ``(batch_size, 4, 4)``.
tsdf (JaggedTensor): Current TSDF values. Shape: ``(batch_size, total_voxels, 1)``.
features (JaggedTensor): Current feature values. Shape: ``(batch_size, total_voxels, feature_dim)``.
weights (JaggedTensor): Current integration weights. Shape: ``(batch_size, total_voxels, 1)``.
depth_images (torch.Tensor): Depth images. Shape: ``(batch_size, height, width)``.
feature_images (torch.Tensor): Feature images (e.g., RGB). Shape: ``(batch_size, height, width, feature_dim)``.
weight_images (torch.Tensor | None): Per-pixel weights, or ``None`` for uniform.
Returns:
updated_grid (GridBatch): Updated :class:`GridBatch` with potentially expanded voxels.
updated_tsdf (JaggedTensor): Updated TSDF values.
updated_weights (JaggedTensor): Updated integration weights.
updated_features (JaggedTensor): Updated per-voxel features.
.. seealso:: :meth:`Grid.integrate_tsdf_with_features`
"""
from . import functional
return functional.integrate_tsdf_with_features_batch(
self,
truncation_distance,
projection_matrices,
cam_to_world_matrices,
tsdf,
features,
weights,
depth_images,
feature_images,
weight_images,
)
def is_contiguous(self) -> bool:
"""Check if this grid batch is stored contiguously in memory.
Returns:
is_contiguous (bool): ``True`` if data is contiguous, ``False`` otherwise.
.. seealso:: :meth:`Grid.is_contiguous`
"""
return self.data.is_contiguous
def is_same(self, other: "GridBatch") -> bool:
"""Check if another grid batch shares the same underlying data in memory as this grid batch.
Args:
other (GridBatch): Grid batch to compare with.
Returns:
is_same (bool): ``True`` if both share the same underlying data, ``False`` otherwise.
.. seealso:: :meth:`Grid.is_same`
"""
return self.data.is_same(other.data)
def jagged_like(self, data: torch.Tensor) -> JaggedTensor: