Skip to content

Box3D

SUMMARY

An axis-aligned bounding box in 3D space.

python
from telekinesis import datatypes
box3d = datatypes.Box3D([1, 2, 2.5, 5, 3, 5])
API Reference
Complete API documentation for Box3D, including parameters, attributes, and methods.
View Reference →

Parameters

ParameterTypeDefaultDescription
datanp.ndarray | list | tupleRequiredBox coordinates [cx, cy, cz, width, height, depth] (center point + size, the native CXCYCZWHD format).

Raises

ExceptionCondition
TypeErrordata can't be converted into a uniform float32 array (e.g. ragged nested lists)
ValueErrordata is not rank-1 (e.g. a (N, 6) batch — use Boxes3D instead)
ValueErrordata does not have exactly 6 elements
ValueErrorAny element is non-finite (NaN/Inf)
ValueErrorwidth, height, or depth (data[3:6]) is negative

A zero-sized width/height/depth is allowed but logs a warning (volume will be 0).

Attributes

AttributeTypeDescription
datanp.ndarrayDefensive copy of the underlying (6,) array [cx, cy, cz, width, height, depth]. Reading it returns a copy; writing re-validates the same way as construction.
shapetuple[int, ...]Always (6,).
ndimintAlways 1.
dtypenp.dtypeAlways float32.
sizeintAlways 6.
shape_spectuple[int, ...]Class-level shape spec (6,).
centernp.ndarray[cx, cy, cz]data[:3] directly. This is the native storage format, so no offset computation is needed to get the center.
dimensionsnp.ndarray[width, height, depth], data[3:6], non-negative.
volumenp.ndarray (scalar)width * height * depth.

Methods

MethodTypeDescription
Box3D.coerce(value)Box3DConverts array-like data into a Box3D. If value is already a Box3D, it is returned unchanged; otherwise it goes through the same checks as constructing one directly.
Box3D.from_xyzwhd(data)Box3DBuilds a box from [x_min, y_min, z_min, width, height, depth], converting it to the native center-based format.
Box3D.from_xyzxyz(data)Box3DBuilds a box from [x_min, y_min, z_min, x_max, y_max, z_max], converting it to the native center-based format.
as_xyzwhd()np.ndarrayReturns this box as [x_min, y_min, z_min, width, height, depth] (min corner + size) instead of the native center-based format.
as_xyzxyz()np.ndarrayReturns this box as [x_min, y_min, z_min, x_max, y_max, z_max] (corner-to-corner) instead of the native center-based format.
to_numpy(copy=True)np.ndarrayReturns the box as a plain array. Pass copy=False for a zero-copy view instead — mutating it mutates the Box3D.
copy()Box3DReturns a new, independent Box3D with the same data.

Operators

OperationBehavior
box == otherTrue only if other is also a Box3D with element-equal data. False for anything else.
len(box)Returns 6 — the length of the coordinate vector, not a box count (a single box is conceptually one item).
box[i]Raises TypeErrorBox3D defines no __getitem__, so a single box isn't indexable like a batch. Use .data[i] for raw coordinate access instead.
for x in boxRaises TypeError — with no __getitem__/__iter__, a single Box3D isn't iterable.
np.asarray(box)Returns a copy of data as an np.ndarray; NumPy functions accept a Box3D directly.

Visualization

python
import rerun as rr

# Your code block
# ....

rr.init("box3d_example", spawn=True)
datatypes.visualize(box3d, entity_path="/box3d", label="Box3D")

Example

python
"""Demonstrates the Telekinesis Box3D datatype."""

import time

import numpy as np
import rerun as rr
from loguru import logger

from telekinesis import datatypes

def box3d_example():
    """Demonstrate creation, inspection, operations, visualization, and serialization."""

    # ======================= Create ============================================
    # Box3D format is CXCYCZWHD = [cx, cy, cz, width, height, depth]
    coords = [1, 2, 2.5, 5, 3, 5]
    box3d = datatypes.Box3D(coords)
    logger.info(f"Original Box3D: {box3d}")

    xyzxyz_coords = [1.0, 1.5, 2.0, 4.0, 4.5, 5.0]
    box3d_from_xyzxyz = datatypes.Box3D.from_xyzxyz(xyzxyz_coords)
    logger.info(f"Box3D created from xyzxyz format: {box3d_from_xyzxyz}")

    xyzwhd_coords = [1.0, 1.5, 2.0, 3.0, 3.0, 3.0]
    box3d_from_xyzwhd = datatypes.Box3D.from_xyzwhd(xyzwhd_coords)
    logger.info(f"Box3D created from xyzwhd format: {box3d_from_xyzwhd}")

    # ======================= Inspect ===========================================
    logger.info(f"data={box3d.data}")
    logger.info(f"dtype={box3d.dtype}")
    logger.info(f"ndim={box3d.ndim}")
    logger.info(f"shape={box3d.shape}")
    logger.info(f"size={box3d.size}")
    logger.info(f"dimensions={box3d.dimensions}")
    logger.info(f"volume={box3d.volume}")
    logger.info(f"center={box3d.center}")

    # ======================= Operations =========================================
    updated_coords = [1, 4, 2.5, 5, 2, 7]
    box3d.data = updated_coords
    logger.info(f"Updated Box3D: {box3d}")

    xyzxyz_view = box3d.as_xyzxyz()
    logger.info(f"Box3D converted to xyzxyz format: {xyzxyz_view}")

    xyzwhd_view = box3d.as_xyzwhd()
    logger.info(f"Box3D converted to xyzwhd format: {xyzwhd_view}")

    box3d_copy = box3d.copy()
    logger.info(f"Copied Box3D: {box3d_copy}")

    # Returns the internal data as a NumPy array. If copy=True, returns a copy; otherwise, returns a view.
    box3d_numpy = box3d.to_numpy(copy=False)
    logger.info(f"NumPy Box3D:\n{box3d_numpy}")

    numpy_box3d = np.asarray(box3d)
    logger.info(f"Box3D via __array__:\n{numpy_box3d}")

    # Translate and scale by operating on the underlying NumPy array directly.
    translation = [3, 3, 1]
    translated_data = box3d.data.copy()
    translated_data[:3] += translation
    translated_box3d = datatypes.Box3D(translated_data)
    logger.info(f"Translated Box3D: {translated_box3d}")

    scale_factors = [2, 0.5, 1.5]
    scaled_data = box3d.data.copy()
    scaled_data[3:] *= np.asarray(scale_factors, dtype=np.float32)
    scaled_box3d = datatypes.Box3D(scaled_data)
    logger.info(f"Scaled Box3D: {scaled_box3d}")

    # ======================= Visualize =========================================
    rr.init("box3d_example", spawn=True)
    datatypes.visualize(box3d, entity_path="/box3d/updated", label="Updated Box3D")
    datatypes.visualize(
        translated_box3d, entity_path="/box3d/translated", label="Translated Box3D"
    )
    datatypes.visualize(scaled_box3d, entity_path="/box3d/scaled", label="Scaled Box3D")

    # ======================= Serialize / Deserialize ===========================
    start = time.perf_counter()
    serialized = datatypes.serialize(box3d)
    serialization_ms = (time.perf_counter() - start) * 1000

    start = time.perf_counter()
    deserialized = datatypes.deserialize(serialized)["param_0"]
    deserialization_ms = (time.perf_counter() - start) * 1000

    logger.info(f"Deserialized Box3D: {deserialized}")
    logger.info(f"Round-trip successful: {box3d == deserialized}")
    logger.info(f"Serialization time: {serialization_ms:.3f} ms")
    logger.info(f"Deserialization time: {deserialization_ms:.3f} ms")


if __name__ == "__main__":
    box3d_example()