Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Facebookresearch Habitat lab Core Utils

From Leeroopedia
Knowledge Sources
Domains Embodied_AI, Utility
Last Updated 2026-02-15 00:00 GMT

Overview

This module provides disconnected core utilities for Habitat, including image tiling, attribute validation, a Singleton metaclass, and custom JSON encoders for dataset serialization.

Description

The module contains several utility classes and functions:

  • tile_images(images) -- Takes a list of images (each of shape height x width x channels) and tiles them into a single square-ish image. Pads with blank images if the count is not a perfect square. Note: This function is marked as a candidate for deprecation in the source code (see line 35), as a possible duplicate exists at habitat-lab/habitat/utils/visualizations/utils.py.
  • not_none_validator(self, attribute, value) -- An attrs validator that raises a ValueError if a particular attribute's value is None. Used with the attrs library for dataclass validation.
  • Singleton -- A metaclass that ensures only one instance of a class is created. All subsequent calls to the class constructor return the existing instance. Used for global registry-like objects.
  • DatasetJSONEncoder -- Extends json.JSONEncoder to handle common Habitat dataset types:
    • np.ndarray -- converted via .tolist()
    • quaternion.quaternion -- converted via quaternion_to_list()
    • OmegaConf DictConfig -- converted via OmegaConf.to_container()
    • dataclasses -- converted via dataclasses.asdict()
    • Falls back to __getstate__() or __dict__
  • DatasetFloatJSONEncoder -- Extends DatasetJSONEncoder to limit float precision to 5 decimal places for space savings. It overrides iterencode with a custom float formatter, handling NaN, Infinity, and -Infinity edge cases. Compatible with JSON version 2.0.9.

Usage

Use tile_images for visualization of multiple image observations. Use DatasetJSONEncoder and DatasetFloatJSONEncoder when serializing Habitat datasets to JSON files. Use Singleton when creating classes that should have exactly one instance (e.g., global registries).

Code Reference

Source Location

Signature

def tile_images(images: List[np.ndarray]) -> np.ndarray:

def not_none_validator(
    self: Any, attribute: attr.Attribute, value: Optional[Any]
) -> None:

class Singleton(type):
    _instances: Dict["Singleton", "Singleton"] = {}
    def __call__(cls, *args, **kwargs):

class DatasetJSONEncoder(json.JSONEncoder):
    def default(self, obj: Any) -> Any:

class DatasetFloatJSONEncoder(DatasetJSONEncoder):
    def iterencode(self, o, _one_shot=False) -> str:

Import

from habitat.core.utils import (
    tile_images,
    not_none_validator,
    Singleton,
    DatasetJSONEncoder,
    DatasetFloatJSONEncoder,
)

I/O Contract

Inputs (tile_images)

Name Type Required Description
images List[np.ndarray] Yes List of images, each of shape (height, width, channels)

Inputs (not_none_validator)

Name Type Required Description
self Any Yes The calling attrs class instance
attribute attr.Attribute Yes The attribute being validated
value Optional[Any] Yes The value to check for None

Outputs

Name Type Description
tile_images() np.ndarray Single tiled image of shape (new_height, new_width, channels)
DatasetJSONEncoder.default() Any Serializable JSON object for the given input

Usage Examples

Basic Usage

import json
import numpy as np
from habitat.core.utils import (
    tile_images,
    DatasetJSONEncoder,
    DatasetFloatJSONEncoder,
    Singleton,
)

# Tile multiple observation images into a grid
images = [np.random.rand(64, 64, 3) for _ in range(4)]
tiled = tile_images(images)  # Shape: (128, 128, 3)

# Serialize a dataset with numpy arrays and quaternions
data = {"positions": np.array([1.0, 2.0, 3.0]), "name": "episode_1"}
json_str = json.dumps(data, cls=DatasetJSONEncoder)

# Use reduced float precision for compact output
json_compact = json.dumps(data, cls=DatasetFloatJSONEncoder)

# Create a singleton class
class MyRegistry(metaclass=Singleton):
    def __init__(self):
        self.items = {}

reg1 = MyRegistry()
reg2 = MyRegistry()
assert reg1 is reg2  # Same instance

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment