Build a Declarative 3D Point-Cloud Processing Pipeline

Hard · Software Engineering Fundamentals · Machine Learning Engineer · Technical Screen

Problem Statement

3D spatial sensing stacks routinely pass raw point scans through configurable sequences of geometric operations—such as axis-aligned region clipping and coordinate-frame conversion—before downstream inference. Build a modular, fail-fast processing framework in Python and expose it through run_point_cloud_pipeline:

def run_point_cloud_pipeline(
    points: List[List[float]],
    metadata: Dict[str, Any],
    config: List[Dict[str, Any]],
) -> Dict[str, Any]:

Structure your implementation around four collaborating components:

  1. PointCloud container (PointCloud(points, metadata=None)):
    • Stores points as a 2D NumPy float array of shape (N, D) with N >= 0 and D >= 3, where columns 0, 1, 2 hold (x, y, z) coordinates and columns 3 .. D - 1 hold optional per-point channels (such as reflectance or beam index).
    • Stores a metadata dictionary (defaulting to {}), ensuring "applied_transforms" is initialized as a list while preserving any pre-existing keys and history entries without mutating caller-owned dictionaries or lists.
  2. Abstract stage interface & class registry:
    • BaseTransform(ABC) defines an abstract apply(self, pc: PointCloud) -> PointCloud method.
    • TransformRegistry (with decorator @register_transform(name)) maps string stage names to BaseTransform subclasses and instantiates stages from configuration dictionaries.
  3. Registered stages:
    • "CropBoundingBox": expects params containing "min_bound" ([x_min, y_min, z_min]) and "max_bound" ([x_max, y_max, z_max]), each a 3-element sequence of finite real numbers satisfying min_bound[i] <= max_bound[i] on every axis. Retains points where min_bound <= (x, y, z) <= max_bound along all three axes (inclusive), keeps all D columns and relative row order, and appends {"name": "CropBoundingBox", "remaining_points": count} to metadata["applied_transforms"].
    • "RigidTransform": expects params containing a non-empty string "target_frame" and "matrix", a 4 x 4 homogeneous matrix of finite real numbers whose fourth row is [0, 0, 0, 1]. Applies matrix @ [x, y, z, 1]^T to each point's (x, y, z) coordinates while leaving columns 3 .. D - 1 untouched, sets metadata["frame_id"] = target_frame, and appends {"name": "RigidTransform"} to metadata["applied_transforms"].
  4. TransformPipeline(config) & entry wrapper:
    • config is a list of step dictionaries [{"name": "<stage>", "params": {...}}, ...] (missing or None "params" is treated as {}).
    • TransformPipeline.__init__ must validate every step up front—raising ValueError immediately if any step has an unknown stage name, missing or unexpected parameter keys, non-numeric or boolean entries, wrong dimensions, or inverted bounds—before any scan is processed.
    • TransformPipeline.run(pc) applies the instantiated stages in order without mutating prior PointCloud instances.
    • run_point_cloud_pipeline(points, metadata, config) builds TransformPipeline(config), wraps points (treating [] as an empty (0, 3) cloud) and metadata into a PointCloud, runs all stages, and returns {"points": <list of float lists>, "metadata": <updated metadata dict>}.

Examples

Example 1

Input:
  points = [[2.0, -1.0, 0.5, 0.9], [12.0, 0.0, 1.0, 0.4], [-4.0, 3.0, -1.0, 0.7]]
  metadata = {"frame_id": "roof_sensor"}
  config = [
    {
      "name": "CropBoundingBox",
      "params": {"min_bound": [-5.0, -5.0, -2.0], "max_bound": [5.0, 5.0, 2.0]}
    },
    {
      "name": "RigidTransform",
      "params": {
        "target_frame": "base_link",
        "matrix": [
          [1.0, 0.0, 0.0, 1.5],
          [0.0, 1.0, 0.0, -0.5],
          [0.0, 0.0, 1.0, 2.0],
          [0.0, 0.0, 0.0, 1.0]
        ]
      }
    }
  ]

Output:
  {
    "points": [[3.5, -1.5, 2.5, 0.9], [-2.5, 2.5, 1.0, 0.7]],
    "metadata": {
      "frame_id": "base_link",
      "applied_transforms": [
        {"name": "CropBoundingBox", "remaining_points": 2},
        {"name": "RigidTransform"}
      ]
    }
  }

CropBoundingBox drops [12.0, 0.0, 1.0, 0.4] because x = 12.0 exceeds 5.0, leaving 2 points and logging remaining_points: 2. RigidTransform then translates (x, y, z) by (+1.5, -0.5, +2.0), keeps the fourth feature channel (0.9 and 0.7) unchanged, and updates frame_id to "base_link".

Example 2

Input:
  points = []
  metadata = {"frame_id": "front_radar", "seq": 7}
  config = [
    {
      "name": "CropBoundingBox",
      "params": {"min_bound": [0.0, -3.0, -1.0], "max_bound": [8.0, 3.0, 2.0]}
    },
    {
      "name": "RigidTransform",
      "params": {
        "target_frame": "chassis",
        "matrix": [
          [0.0, -1.0, 0.0, 0.0],
          [1.0, 0.0, 0.0, 0.0],
          [0.0, 0.0, 1.0, 0.5],
          [0.0, 0.0, 0.0, 1.0]
        ]
      }
    }
  ]

Output:
  {
    "points": [],
    "metadata": {
      "frame_id": "chassis",
      "seq": 7,
      "applied_transforms": [
        {"name": "CropBoundingBox", "remaining_points": 0},
        {"name": "RigidTransform"}
      ]
    }
  }

An empty scan (N = 0) passes cleanly through both stages without shape errors, preserving custom metadata key "seq": 7, updating "frame_id" to "chassis", and recording both stage entries.

Constraints

  • N >= 0 and D >= 3 for every non-empty points input (points == [] represents N = 0).
  • Every stage and pipeline call must leave the caller's input points list and metadata dictionary unmutated.
  • Any invalid configuration or stage parameter must raise ValueError during TransformPipeline construction, even when points is empty.

Step-by-step walkthrough

  1. Understand the goal and pipeline contract

    A LiDAR sensor produces a point cloud: a 2D table of N points and D >= 3 columns where the first three columns are 3D coordinates (x, y, z) and any extra columns (3 .. D - 1) hold per-point sensor features such as laser intensity or ring ID. Alongside the array travels a metadata dictionary tracking the coordinate frame (frame_id), timestamps, and an applied_transforms audit log.

    We need to build four modular pieces and connect them through the judged entry function run_point_cloud_pipeline(points, metadata, config):

    1. PointCloud: Holds the (N, D) NumPy array and metadata without mutating the caller's original lists or dictionaries.
    2. BaseTransform and TransformRegistry (@register_transform): Maps string names from a YAML config ("CropBoundingBox", "RigidTransform") to transform classes without a brittle if / elif chain.
    3. CropBoundingBox and RigidTransform: Validate their parameters on construction (ValueError on bad types, shapes, or bounds), transform (x, y, z) while preserving extra columns, and record history entries ({"name": "CropBoundingBox", "remaining_points": count} and {"name": "RigidTransform"}).
    4. TransformPipeline: Instantiates and validates every step inside __init__ before a single point is processed, then applies them sequentially in run.
  2. Architecture: separate setup-time validation from runtime execution

    Why split construction (__init__) from execution (run)? In a self-driving vehicle, a YAML config is loaded once at startup, and then run is called 10–20 times per second on live LiDAR frames. If step 4 has a typo ("VoxleDownsample" or min_bound > max_bound), we want the system to reject the config immediately at startup rather than crashing halfway through frame processing.

    Startup (once):
      YAML config list
            |
            v
      TransformPipeline.__init__
            |---> step 0: TransformRegistry.create("CropBoundingBox", params)  -> validates bounds
            +---> step 1: TransformRegistry.create("RigidTransform", params)   -> validates 4x4 matrix
    
    Runtime (every LiDAR frame):
      pc_0  --->  [CropBoundingBox.apply]  --->  pc_1  --->  [RigidTransform.apply]  --->  pc_2
                  (filters rows, logs count)                 (rotates/shifts xyz,
                                                              updates frame_id)
    
  3. Build the PointCloud container without mutating caller data

    When a transform produces a new PointCloud, a shallow copy dict(self.metadata) is not enough on its own: both dictionaries would still point to the exact same applied_transforms list in memory, so .append(...) would silently corrupt the input cloud's history!

    Bad (shared inner list):
      input_pc.metadata  ---> {"frame_id": "lidar",   "applied_transforms": [ ... ]}
                                                                               ^
      output_pc.metadata ---> {"frame_id": "vehicle", "applied_transforms": ---+}
    
    Good (fresh dict + fresh list via `+`):
      input_pc.metadata  ---> {"frame_id": "lidar",   "applied_transforms": [A]}
      output_pc.metadata ---> {"frame_id": "vehicle", "applied_transforms": [A, B]}
    

    We enforce shape (N, D) with D >= 3 inside PointCloud.__init__, copy both the dictionary and applied_transforms, and provide a small with_step helper that creates the next stage's PointCloud cleanly.

    class PointCloud:
        """Immutable-style container for (N, D) 3D point data (D >= 3) and sensor metadata."""
    
        def __init__(self, points: np.ndarray, metadata: Dict[str, Any] = None):
            # points: 2D float64 array of shape (N, D) where columns 0..2 are (x, y, z)
            # and columns 3..D-1 are optional per-point features (intensity, ring ID, etc.).
            point_array = np.asarray(points, dtype=float)
            if point_array.ndim != 2 or point_array.shape[1] < 3:
                raise ValueError(f"points must have shape (N, D) with D >= 3, got {point_array.shape}")
            self.points = point_array
    
            # Copy both the outer dict and the applied_transforms list so caller dicts stay untouched.
            copied_meta = dict(metadata) if metadata is not None else {}
            existing_history = copied_meta.get("applied_transforms", [])
            if not isinstance(existing_history, list):
                raise ValueError("metadata['applied_transforms'] must be a list")
            copied_meta["applied_transforms"] = list(existing_history)
            self.metadata = copied_meta
    
        def with_step(
            self,
            new_points: np.ndarray,
            step_record: Dict[str, Any],
            new_frame_id: Optional[str] = None,
        ) -> "PointCloud":
            """Return a new PointCloud with updated points, appended history record, and optional new frame_id."""
            next_meta = dict(self.metadata)
            # Use list concatenation (+) so self.metadata['applied_transforms'] is never mutated in place.
            next_meta["applied_transforms"] = self.metadata["applied_transforms"] + [step_record]
            if new_frame_id is not None:
                next_meta["frame_id"] = new_frame_id
            return PointCloud(new_points, next_meta)
    
  4. Create BaseTransform and the @register_transform registry

    BaseTransform inherits from Python's ABC (Abstract Base Class) and marks apply with @abstractmethod, which prevents anyone from instantiating a transform class that forgot to implement apply.

    TransformRegistry holds a class-level dictionary _classes mapping string names to classes. Writing @register_transform("CropBoundingBox") above a class runs decorator(CropBoundingBox) at import time, storing "CropBoundingBox": CropBoundingBox in _classes so adding a new transform later never requires editing TransformPipeline.

    class BaseTransform(ABC):
        """Abstract interface that every point-cloud pipeline stage must implement."""
    
        name = "BaseTransform"
    
        @abstractmethod
        def apply(self, pc: PointCloud) -> PointCloud:
            pass
    
    
    class TransformRegistry:
        """Global lookup table mapping YAML transform names (e.g. 'CropBoundingBox') to classes."""
    
        # _classes: dict mapping registered string identifier -> BaseTransform subclass.
        _classes: Dict[str, type] = {}
    
        @classmethod
        def register(cls, name: str):
            def decorator(transform_cls: type) -> type:
                if name in cls._classes:
                    raise ValueError(f"transform {name!r} is already registered")
                transform_cls.name = name
                cls._classes[name] = transform_cls
                return transform_cls
    
            return decorator
    
        @classmethod
        def create(cls, name: str, params: Dict[str, Any]) -> BaseTransform:
            if name not in cls._classes:
                known_names = sorted(cls._classes)
                raise ValueError(f"unknown transform {name!r}; registered transforms: {known_names}")
            return cls._classes[name](params)
    
    
    register_transform = TransformRegistry.register
    
  5. Write strict parameter validation helpers

    YAML configs parsed into Python contain plain dicts, lists, strings, numbers, and booleans, with a few classic traps:

    • Typos in parameter keys: Checking both missing keys and unexpected extra keys catches a typo like max_bounds instead of silently ignoring it.
    • bool is a subclass of int in Python! isinstance(True, int) evaluates to True, and YAML parses true or yes as True. We explicitly reject bool and non-finite values (NaN, inf).
    • Fixed-length numeric vectors: _parse_float_vector verifies exact length (3 for box bounds, 4 for matrix rows) before converting entries to float.
    def _validate_param_keys(params: Any, required_keys: List[str], owner: str) -> None:
        """Ensure params is a dict containing all required_keys and no unexpected typos."""
        if not isinstance(params, dict):
            raise ValueError(f"{owner}: params must be a dict, got {type(params).__name__}")
        for key in required_keys:
            if key not in params:
                raise ValueError(f"{owner}: missing required parameter {key!r}")
        for key in params:
            if key not in required_keys:
                raise ValueError(f"{owner}: unexpected parameter {key!r}")
    
    
    def _is_finite_real(value: Any) -> bool:
        """Return True only for finite real numbers, rejecting bool (since bool subclasses int in Python)."""
        return isinstance(value, numbers.Real) and not isinstance(value, bool) and math.isfinite(value)
    
    
    def _parse_float_vector(value: Any, expected_len: int, field_name: str) -> List[float]:
        """Validate a 1D sequence of expected_len finite real numbers and convert to floats."""
        if isinstance(value, np.ndarray):
            if value.ndim != 1 or value.shape[0] != expected_len:
                raise ValueError(f"{field_name} must be a 1D sequence of length {expected_len}")
            items = value.tolist()
        elif isinstance(value, (list, tuple)) and len(value) == expected_len:
            items = value
        else:
            raise ValueError(f"{field_name} must be a list of {expected_len} numbers, got {value!r}")
    
        parsed: List[float] = []
        for item in items:
            if not _is_finite_real(item):
                raise ValueError(f"{field_name} must contain only finite numbers, got {item!r}")
            parsed.append(float(item))
        return parsed
    
  6. Implement CropBoundingBox with vectorized NumPy masks

    CropBoundingBox checks that min_bound and max_bound each have 3 finite numbers with min_bound <= max_bound on all three axes (min == max is allowed for a flat plane crop; min > max raises ValueError).

    At runtime, we slice xyz = pc.points[:, :3] (shape (N, 3)) and compare against self.min_bound and self.max_bound. A point stays only if all three coordinates (axis=1) pass both inclusive >= and <= checks:

    Points (x, y, z, reflectance):       min_bound = [-5, -5, -2], max_bound = [5, 5, 2]
      row 0: [  2.0, -1.0,  0.5, 0.9] -> [True,  True,  True ]  -> all True  -> KEEP
      row 1: [ 12.0,  0.0,  1.0, 0.4] -> [False, True,  True ]  -> all False -> DROP (x = 12.0 > 5)
      row 2: [ -4.0,  3.0, -1.0, 0.7] -> [True,  True,  True ]  -> all True  -> KEEP
    

    Indexing pc.points[inside_box_mask] filters all D columns at once (keeping reflectance attached) and always allocates a fresh NumPy array, even when N == 0.

    @register_transform("CropBoundingBox")
    class CropBoundingBox(BaseTransform):
        """Keep only points whose (x, y, z) coordinates lie within [min_bound, max_bound] inclusive."""
    
        def __init__(self, params: Dict[str, Any]):
            _validate_param_keys(params, ["min_bound", "max_bound"], "CropBoundingBox")
            self.min_bound = np.array(_parse_float_vector(params["min_bound"], 3, "CropBoundingBox.min_bound"))
            self.max_bound = np.array(_parse_float_vector(params["max_bound"], 3, "CropBoundingBox.max_bound"))
            # Equal bounds (min == max) form a valid flat plane/point box, whereas min > max is inverted.
            if np.any(self.min_bound > self.max_bound):
                raise ValueError("CropBoundingBox: min_bound must be <= max_bound on every axis")
    
        def apply(self, pc: PointCloud) -> PointCloud:
            xyz = pc.points[:, :3]
            above_min = xyz >= self.min_bound
            below_max = xyz <= self.max_bound
            # A point is kept only if all 3 coordinates (axis=1) satisfy both inclusive bounds.
            inside_box_mask = np.all(above_min & below_max, axis=1)
            kept_points = pc.points[inside_box_mask]
            record = {"name": self.name, "remaining_points": int(kept_points.shape[0])}
            return pc.with_step(kept_points, record)
    
  7. Implement RigidTransform with 4x4 homogeneous coordinates

    Why does 3D robotics use a 4 x 4 matrix to move (x, y, z) points? A 3 x 3 matrix can rotate (x, y, z), but it cannot add a shift (tx, ty, tz). Appending a fourth coordinate 1—called homogeneous coordinates [x, y, z, 1]—lets a single 4 x 4 matrix multiplication perform both rotation R and translation t at once:

    Column-vector view (1 point):            Row-vector view (N points at once):
    [ r00 r01 r02 | tx ]   [ x ]   [ x' ]
    [ r10 r11 r12 | ty ] @ [ y ] = [ y' ]    [ x  y  z  1 ]  @  M.T  =  [ x'  y'  z'  1 ]
    [ r20 r21 r22 | tz ]   [ z ]   [ z' ]     shape (N, 4)     (4,4)      shape (N, 4)
    [  0   0   0  |  1 ]   [ 1 ]   [ 1  ]
    

    Because pc.points stores each point as a row rather than a column, multiplying a batch of row vectors [x, y, z, 1] on the right requires the transpose M.T (since (M @ p)^T = p^T @ M^T). And as long as the bottom row of M is [0, 0, 0, 1], the fourth output column stays 1, so slicing [:, :3] gives (x', y', z') directly!

    Two important engineering details:

    1. Transform only [:, :3], then copy extra channels: Never multiply a (N, 4) [x, y, z, intensity] cloud directly by M.T—that would plug intensity in place of 1 and scale the translation by intensity! Instead, transform pc.points[:, :3] and write the result into a copy of pc.points.
    2. Do not reject hand-rounded calibration YAML matrices: Real sensor calibration YAML files often write 0.866 for cos(30°) instead of 16 digits of float precision, so R.T @ R differs from I by ~4e-5. We validate that M is 4 x 4 finite numbers with bottom row [0, 0, 0, 1] (within 1e-9) without rejecting slightly rounded rotations.
    # Small floating-point tolerance for checking that a 4x4 matrix's bottom row is [0, 0, 0, 1].
    LAST_ROW_TOLERANCE = 1e-9
    
    @register_transform("RigidTransform")
    class RigidTransform(BaseTransform):
        """Apply a 4x4 homogeneous transform matrix to (x, y, z) while preserving extra channels."""
    
        def __init__(self, params: Dict[str, Any]):
            _validate_param_keys(params, ["target_frame", "matrix"], "RigidTransform")
            target_frame = params["target_frame"]
            if not isinstance(target_frame, str) or target_frame == "":
                raise ValueError("RigidTransform.target_frame must be a non-empty string")
    
            raw_rows = params["matrix"]
            if isinstance(raw_rows, np.ndarray):
                if raw_rows.ndim != 2 or raw_rows.shape != (4, 4):
                    raise ValueError("RigidTransform.matrix must have shape (4, 4)")
                raw_rows = raw_rows.tolist()
            elif not isinstance(raw_rows, (list, tuple)) or len(raw_rows) != 4:
                raise ValueError("RigidTransform.matrix must be a 4x4 list of numbers")
    
            parsed_rows = [_parse_float_vector(row, 4, "RigidTransform.matrix row") for row in raw_rows]
            matrix = np.array(parsed_rows, dtype=float)
    
            # Bottom row must be [0, 0, 0, 1] so homogeneous w stays 1 and slicing [:, :3] is exact.
            if not np.allclose(matrix[3], [0.0, 0.0, 0.0, 1.0], rtol=0.0, atol=LAST_ROW_TOLERANCE):
                raise ValueError("RigidTransform.matrix: bottom row must be [0, 0, 0, 1]")
    
            self.target_frame = target_frame
            self.matrix = matrix
    
        def apply(self, pc: PointCloud) -> PointCloud:
            num_points = pc.points.shape[0]
            xyz = pc.points[:, :3]
    
            # Convert (N, 3) -> (N, 4) homogeneous row vectors [x, y, z, 1].
            ones_col = np.ones((num_points, 1), dtype=float)
            homogeneous_xyz = np.hstack([xyz, ones_col])
    
            # Row vectors multiply by matrix.T on the right; slice back to (x', y', z').
            transformed_xyz = (homogeneous_xyz @ self.matrix.T)[:, :3]
    
            # Copy full (N, D) array so extra features (columns 3..D-1) remain unchanged.
            new_points = pc.points.copy()
            new_points[:, :3] = transformed_xyz
            record = {"name": self.name}
            return pc.with_step(new_points, record, new_frame_id=self.target_frame)
    
  8. Wire up TransformPipeline and the judge entry point

    TransformPipeline.__init__ validates the outer list, checks each step dictionary, and calls TransformRegistry.create(step["name"], params) for every step up front—attaching step_index to any ValueError so debugging a broken YAML config points straight to the offending step.

    In run_point_cloud_pipeline, watch out for one NumPy pitfall on empty input (points = [], Example 2): np.asarray([]) produces a 1D array of shape (0,), which would fail the 2D (N, D) check! When len(points) == 0, we construct np.zeros((0, 3), dtype=float) explicitly so every NumPy slice [:, :3], matrix product, and .tolist() ([]) executes cleanly with zero special cases inside the transforms.

    class TransformPipeline:
        """Sequential point-cloud pipeline that validates all configured stages at initialization."""
    
        def __init__(self, config: List[Dict[str, Any]]):
            if not isinstance(config, list):
                raise ValueError("config must be a list of transform step dicts")
    
            # self.transforms: ordered list of validated BaseTransform instances.
            self.transforms: List[BaseTransform] = []
            for step_index, step in enumerate(config):
                if not isinstance(step, dict) or not isinstance(step.get("name"), str):
                    raise ValueError(f"config step {step_index}: expected a dict with string 'name'")
                for key in step:
                    if key not in ("name", "params"):
                        raise ValueError(f"config step {step_index}: unknown key {key!r}")
    
                # An empty `params:` block in YAML parses as None; treat missing/None as {}.
                params = step.get("params")
                if params is None:
                    params = {}
    
                try:
                    transform = TransformRegistry.create(step["name"], params)
                except ValueError as exc:
                    raise ValueError(f"config step {step_index}: {exc}") from exc
                self.transforms.append(transform)
    
        def run(self, pc: PointCloud) -> PointCloud:
            current_pc = pc
            for transform in self.transforms:
                current_pc = transform.apply(current_pc)
            return current_pc
    
    
    def run_point_cloud_pipeline(
        points: List[List[float]],
        metadata: Dict[str, Any],
        config: List[Dict[str, Any]],
    ) -> Dict[str, Any]:
        # Phase 1: build and validate the entire pipeline before touching any point data.
        pipeline = TransformPipeline(config)
    
        # Phase 2: convert input rows into a 2D array; empty [] has no column count so use shape (0, 3).
        if len(points) == 0:
            point_array = np.zeros((0, 3), dtype=float)
        else:
            point_array = np.asarray(points, dtype=float)
    
        # Phase 3: wrap in PointCloud (copies metadata safely), run stages, and serialize back to lists.
        initial_cloud = PointCloud(point_array, metadata)
        final_cloud = pipeline.run(initial_cloud)
        return {
            "points": final_cloud.points.tolist(),
            "metadata": final_cloud.metadata,
        }
    
  9. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from abc import ABC, abstractmethod
    import math
    import numbers
    
    import numpy as np
    
    # Small floating-point tolerance for checking that a 4x4 matrix's bottom row is [0, 0, 0, 1].
    LAST_ROW_TOLERANCE = 1e-9
    
    
    class PointCloud:
        """Immutable-style container for (N, D) 3D point data (D >= 3) and sensor metadata."""
    
        def __init__(self, points: np.ndarray, metadata: Dict[str, Any] = None):
            # points: 2D float64 array of shape (N, D) where columns 0..2 are (x, y, z)
            # and columns 3..D-1 are optional per-point features (intensity, ring ID, etc.).
            point_array = np.asarray(points, dtype=float)
            if point_array.ndim != 2 or point_array.shape[1] < 3:
                raise ValueError(f"points must have shape (N, D) with D >= 3, got {point_array.shape}")
            self.points = point_array
    
            # Copy both the outer dict and the applied_transforms list so caller dicts stay untouched.
            copied_meta = dict(metadata) if metadata is not None else {}
            existing_history = copied_meta.get("applied_transforms", [])
            if not isinstance(existing_history, list):
                raise ValueError("metadata['applied_transforms'] must be a list")
            copied_meta["applied_transforms"] = list(existing_history)
            self.metadata = copied_meta
    
        def with_step(
            self,
            new_points: np.ndarray,
            step_record: Dict[str, Any],
            new_frame_id: Optional[str] = None,
        ) -> "PointCloud":
            """Return a new PointCloud with updated points, appended history record, and optional new frame_id."""
            next_meta = dict(self.metadata)
            # Use list concatenation (+) so self.metadata['applied_transforms'] is never mutated in place.
            next_meta["applied_transforms"] = self.metadata["applied_transforms"] + [step_record]
            if new_frame_id is not None:
                next_meta["frame_id"] = new_frame_id
            return PointCloud(new_points, next_meta)
    
    
    class BaseTransform(ABC):
        """Abstract interface that every point-cloud pipeline stage must implement."""
    
        name = "BaseTransform"
    
        @abstractmethod
        def apply(self, pc: PointCloud) -> PointCloud:
            pass
    
    
    class TransformRegistry:
        """Global lookup table mapping YAML transform names (e.g. 'CropBoundingBox') to classes."""
    
        # _classes: dict mapping registered string identifier -> BaseTransform subclass.
        _classes: Dict[str, type] = {}
    
        @classmethod
        def register(cls, name: str):
            def decorator(transform_cls: type) -> type:
                if name in cls._classes:
                    raise ValueError(f"transform {name!r} is already registered")
                transform_cls.name = name
                cls._classes[name] = transform_cls
                return transform_cls
    
            return decorator
    
        @classmethod
        def create(cls, name: str, params: Dict[str, Any]) -> BaseTransform:
            if name not in cls._classes:
                known_names = sorted(cls._classes)
                raise ValueError(f"unknown transform {name!r}; registered transforms: {known_names}")
            return cls._classes[name](params)
    
    
    register_transform = TransformRegistry.register
    
    
    def _validate_param_keys(params: Any, required_keys: List[str], owner: str) -> None:
        """Ensure params is a dict containing all required_keys and no unexpected typos."""
        if not isinstance(params, dict):
            raise ValueError(f"{owner}: params must be a dict, got {type(params).__name__}")
        for key in required_keys:
            if key not in params:
                raise ValueError(f"{owner}: missing required parameter {key!r}")
        for key in params:
            if key not in required_keys:
                raise ValueError(f"{owner}: unexpected parameter {key!r}")
    
    
    def _is_finite_real(value: Any) -> bool:
        """Return True only for finite real numbers, rejecting bool (since bool subclasses int in Python)."""
        return isinstance(value, numbers.Real) and not isinstance(value, bool) and math.isfinite(value)
    
    
    def _parse_float_vector(value: Any, expected_len: int, field_name: str) -> List[float]:
        """Validate a 1D sequence of expected_len finite real numbers and convert to floats."""
        if isinstance(value, np.ndarray):
            if value.ndim != 1 or value.shape[0] != expected_len:
                raise ValueError(f"{field_name} must be a 1D sequence of length {expected_len}")
            items = value.tolist()
        elif isinstance(value, (list, tuple)) and len(value) == expected_len:
            items = value
        else:
            raise ValueError(f"{field_name} must be a list of {expected_len} numbers, got {value!r}")
    
        parsed: List[float] = []
        for item in items:
            if not _is_finite_real(item):
                raise ValueError(f"{field_name} must contain only finite numbers, got {item!r}")
            parsed.append(float(item))
        return parsed
    
    
    @register_transform("CropBoundingBox")
    class CropBoundingBox(BaseTransform):
        """Keep only points whose (x, y, z) coordinates lie within [min_bound, max_bound] inclusive."""
    
        def __init__(self, params: Dict[str, Any]):
            _validate_param_keys(params, ["min_bound", "max_bound"], "CropBoundingBox")
            self.min_bound = np.array(_parse_float_vector(params["min_bound"], 3, "CropBoundingBox.min_bound"))
            self.max_bound = np.array(_parse_float_vector(params["max_bound"], 3, "CropBoundingBox.max_bound"))
            # Equal bounds (min == max) form a valid flat plane/point box, whereas min > max is inverted.
            if np.any(self.min_bound > self.max_bound):
                raise ValueError("CropBoundingBox: min_bound must be <= max_bound on every axis")
    
        def apply(self, pc: PointCloud) -> PointCloud:
            xyz = pc.points[:, :3]
            above_min = xyz >= self.min_bound
            below_max = xyz <= self.max_bound
            # A point is kept only if all 3 coordinates (axis=1) satisfy both inclusive bounds.
            inside_box_mask = np.all(above_min & below_max, axis=1)
            kept_points = pc.points[inside_box_mask]
            record = {"name": self.name, "remaining_points": int(kept_points.shape[0])}
            return pc.with_step(kept_points, record)
    
    
    @register_transform("RigidTransform")
    class RigidTransform(BaseTransform):
        """Apply a 4x4 homogeneous transform matrix to (x, y, z) while preserving extra channels."""
    
        def __init__(self, params: Dict[str, Any]):
            _validate_param_keys(params, ["target_frame", "matrix"], "RigidTransform")
            target_frame = params["target_frame"]
            if not isinstance(target_frame, str) or target_frame == "":
                raise ValueError("RigidTransform.target_frame must be a non-empty string")
    
            raw_rows = params["matrix"]
            if isinstance(raw_rows, np.ndarray):
                if raw_rows.ndim != 2 or raw_rows.shape != (4, 4):
                    raise ValueError("RigidTransform.matrix must have shape (4, 4)")
                raw_rows = raw_rows.tolist()
            elif not isinstance(raw_rows, (list, tuple)) or len(raw_rows) != 4:
                raise ValueError("RigidTransform.matrix must be a 4x4 list of numbers")
    
            parsed_rows = [_parse_float_vector(row, 4, "RigidTransform.matrix row") for row in raw_rows]
            matrix = np.array(parsed_rows, dtype=float)
    
            # Bottom row must be [0, 0, 0, 1] so homogeneous w stays 1 and slicing [:, :3] is exact.
            if not np.allclose(matrix[3], [0.0, 0.0, 0.0, 1.0], rtol=0.0, atol=LAST_ROW_TOLERANCE):
                raise ValueError("RigidTransform.matrix: bottom row must be [0, 0, 0, 1]")
    
            self.target_frame = target_frame
            self.matrix = matrix
    
        def apply(self, pc: PointCloud) -> PointCloud:
            num_points = pc.points.shape[0]
            xyz = pc.points[:, :3]
    
            # Convert (N, 3) -> (N, 4) homogeneous row vectors [x, y, z, 1].
            ones_col = np.ones((num_points, 1), dtype=float)
            homogeneous_xyz = np.hstack([xyz, ones_col])
    
            # Row vectors multiply by matrix.T on the right; slice back to (x', y', z').
            transformed_xyz = (homogeneous_xyz @ self.matrix.T)[:, :3]
    
            # Copy full (N, D) array so extra features (columns 3..D-1) remain unchanged.
            new_points = pc.points.copy()
            new_points[:, :3] = transformed_xyz
            record = {"name": self.name}
            return pc.with_step(new_points, record, new_frame_id=self.target_frame)
    
    
    class TransformPipeline:
        """Sequential point-cloud pipeline that validates all configured stages at initialization."""
    
        def __init__(self, config: List[Dict[str, Any]]):
            if not isinstance(config, list):
                raise ValueError("config must be a list of transform step dicts")
    
            # self.transforms: ordered list of validated BaseTransform instances.
            self.transforms: List[BaseTransform] = []
            for step_index, step in enumerate(config):
                if not isinstance(step, dict) or not isinstance(step.get("name"), str):
                    raise ValueError(f"config step {step_index}: expected a dict with string 'name'")
                for key in step:
                    if key not in ("name", "params"):
                        raise ValueError(f"config step {step_index}: unknown key {key!r}")
    
                # An empty `params:` block in YAML parses as None; treat missing/None as {}.
                params = step.get("params")
                if params is None:
                    params = {}
    
                try:
                    transform = TransformRegistry.create(step["name"], params)
                except ValueError as exc:
                    raise ValueError(f"config step {step_index}: {exc}") from exc
                self.transforms.append(transform)
    
        def run(self, pc: PointCloud) -> PointCloud:
            current_pc = pc
            for transform in self.transforms:
                current_pc = transform.apply(current_pc)
            return current_pc
    
    
    def run_point_cloud_pipeline(
        points: List[List[float]],
        metadata: Dict[str, Any],
        config: List[Dict[str, Any]],
    ) -> Dict[str, Any]:
        # Phase 1: build and validate the entire pipeline before touching any point data.
        pipeline = TransformPipeline(config)
    
        # Phase 2: convert input rows into a 2D array; empty [] has no column count so use shape (0, 3).
        if len(points) == 0:
            point_array = np.zeros((0, 3), dtype=float)
        else:
            point_array = np.asarray(points, dtype=float)
    
        # Phase 3: wrap in PointCloud (copies metadata safely), run stages, and serialize back to lists.
        initial_cloud = PointCloud(point_array, metadata)
        final_cloud = pipeline.run(initial_cloud)
        return {
            "points": final_cloud.points.tolist(),
            "metadata": final_cloud.metadata,
        }
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of an automated factory assembly line configured from a declarative checklist. Before switching on the conveyor belt, an engineer walks down the checklist to verify that every station name exists in the catalog and every dial setting makes physical sense (fail-fast validation, checking configuration rules at initialization time so broken configs fail immediately rather than mid-run). Once running, each point cloud (a 2D (N, D) array of 3D coordinates (x, y, z) plus extra per-point attributes such as reflectance) moves from station to station, carrying a fresh copy of its metadata clipboard stamped at each stop without altering the original raw scan.

A naive script that loops over config dicts inside run() using an if step["name"] == ...: chain breaks down in production for three reasons. First, a typo or invalid matrix in step 5 is only caught after steps 1–4 have already burned compute on live scans. Second, adding any new stage forces edits to the central runner instead of plugging in cleanly. Third, multiplying all D columns directly by a 4 x 4 matrix or mutating metadata in place corrupts extra sensor channels and caller history lists.

Our design combines the registry pattern (a central dictionary mapping string identifiers to classes) populated via a Python decorator (@register_transform("..."), a wrapper that registers a class automatically when defined), with homogeneous coordinates (appending 1 to (x, y, z) so a single 4 x 4 matrix product applies both 3D rotation and 3D translation at once):

  • Consider Example 1 with 3 points [2.0, -1.0, 0.5, 0.9], [12.0, 0.0, 1.0, 0.4], and [-4.0, 3.0, -1.0, 0.7] in "roof_sensor".
  • Startup (TransformPipeline.__init__): Resolves "CropBoundingBox" and "RigidTransform" through TransformRegistry and validates bounds [-5, -5, -2] <= [5, 5, 2] and the 4 x 4 matrix before touching any point rows.
  • Stage 1 (CropBoundingBox): Tests (x, y, z) against [-5, -5, -2] .. [5, 5, 2], drops [12.0, 0.0, 1.0, 0.4] (12.0 > 5.0), keeps the other 2 points with reflectance 0.9 and 0.7, and appends {"name": "CropBoundingBox", "remaining_points": 2}.
  • Stage 2 (RigidTransform): Converts (x, y, z) to [x, y, z, 1], multiplies by matrix.T to shift by (+1.5, -0.5, +2.0), writes [[3.5, -1.5, 2.5], [-2.5, 2.5, 1.0]] alongside untouched reflectance 0.9 and 0.7, updates frame_id = "base_link", and appends {"name": "RigidTransform"}.

Complexity

Let S be the number of configured stages, N be the number of points, and D be the number of columns per point.

  • Time: O(S) to construct and validate the pipeline (each stage checks constant-size 3-element bounds or a 4 x 4 matrix), and O(S * N * D) to execute a scan across S stages (cropping checks 3 * N coordinates and copies up to N * D floats; rigid transformation multiplies an (N, 4) array by (4, 4) in O(N) operations and copies N * D floats).
  • Space: O(S) for the instantiated stage list, plus O(N * D) peak auxiliary memory per stage for the output (N, D) array and (N, 4) homogeneous buffer.

Edge cases

  • Empty scan (N = 0): Because np.asarray([]) produces a 1D (0,) array, run_point_cloud_pipeline initializes points = [] as shape (0, 3); boolean masks, np.hstack, (0, 4) @ (4, 4) products, and .tolist() all run cleanly and return [] while still logging stage metadata.
  • Cropping a multi-feature scan down to zero points ((N, 5) -> (0, 5)): Boolean indexing preserves column count D = 5 even at 0 rows, letting subsequent RigidTransform stages run cleanly.
  • Extra per-point channels (D > 3): Columns 3 .. D - 1 remain untouched across both region cropping and 3D rigid transformations.
  • Inclusive box faces and zero-thickness planes: Points lying directly on min_bound or max_bound satisfy >= and <= and stay; min_bound == max_bound on an axis is valid.
  • Caller immutability and existing metadata: Custom keys such as seq or timestamp survive intact, applied_transforms extends a fresh list copy, and caller points and metadata are never mutated.
  • YAML quirks (None params and booleans): Missing or None params normalizes to {}, and True / False are rejected as numbers despite bool subclassing int in Python.

Common mistakes

  • Validating lazily inside run(): Deferring stage lookup or parameter checks until apply fails the startup-validation contract whenever points = [] or an invalid step sits after a stage that drops all points.
  • Shallow-copying metadata alone: A shallow copy (duplicating only the outer dictionary while aliasing inner mutable lists) mutates the caller's applied_transforms list in place; copy the list too.
  • Multiplying all D columns by the 4 x 4 matrix: Passing [x, y, z, reflectance] directly into @ matrix.T treats reflectance as homogeneous w = 1 (scaling translations by reflectance) and crashes whenever D != 4.
  • Forgetting the transpose matrix.T: Column-vector math uses M @ p, so row-vector batches of shape (N, 4) require homogeneous_xyz @ matrix.T.
  • Overly strict rotation-orthogonality tolerance (R.T @ R == I within 1e-6): Calibration files often store rounded decimals like 0.866 for cos(30°); rejecting slight rounding breaks valid real-world configs.
  • Calling np.asarray([]) directly: Yields 1D shape (0,) instead of 2D (0, 3), triggering IndexError on [:, :3].

Alternative approaches

  • Subclass hook (__init_subclass__): Defining __init_subclass__ on BaseTransform auto-registers subclasses without a decorator, though @register_transform("...") decouples external config names from internal class renames.
  • Separate 3 x 3 rotation + 3 translation (xyz @ R.T + t): Slicing R = matrix[:3, :3] and t = matrix[:3, 3] avoids allocating the temporary (N, 4) homogeneous array while producing identical results whenever the bottom row is [0, 0, 0, 1].

Follow-up questions

  • How could you use a typed schema library (such as Pydantic) so nested configuration files are validated automatically and reference docs stay in sync? Pair each registered stage class with a typed parameter model (for instance, a Pydantic BaseModel configured with extra="forbid", fixed-length float tuples, and a @model_validator enforcing min_bound <= max_bound) inside TransformRegistry. Compose all registered step models into a discriminated union keyed by "name" so loading a parsed YAML dictionary validates the entire nested pipeline at once with exact step-and-field error paths. Exporting .model_json_schema() from that union generates machine-readable JSON Schema (a standard specification of allowed fields, types, bounds, and docstrings) that drives both static reference docs and IDE autocomplete automatically.
  • When processing multi-million-point scans under a strict sub-10ms budget, how would you cut memory traffic and eliminate intermediate array copies across stages? Store channels in float32 rather than float64 to cut memory bandwidth in half, and adopt a structure of arrays (SoA) layout (keeping x, y, z, and extra channels in separate contiguous 1D buffers so spatial crops never pull unused feature columns into CPU cache). At pipeline initialization, fuse consecutive RigidTransform matrices into one composite 4 x 4 matrix, and thread a boolean mask or index vector across chained filters so surviving rows are gathered once at the end instead of reallocating after every filter. For tight real-time loops, reuse preallocated scratch buffers (out=) or upload the raw scan to pinned GPU memory once and execute fused CUDA kernels ahead of the 3D backbone.
  • How would you extend a sequential pipeline into a directed graph when one stage splits a scan into multiple outputs (such as drivable surface vs. obstacles)? Replace the flat step list with a directed acyclic graph (DAG) (a network of directed stages containing no cycles) where each node names its input and output streams, such as {"name": "SegmentGround", "inputs": ["cropped"], "outputs": ["surface", "obstacles"], "params": {...}}. During initialization, verify that every referenced input stream already exists upstream, reject duplicate stream names or cycles, and precompute a topological sort (an execution order guaranteeing every node runs after all of its upstream producers). At runtime, hold active clouds in streams: Dict[str, PointCloud], clone metadata independently per output branch so "surface" and "obstacles" maintain separate audit logs, and return the requested terminal streams.

Follow-up questions

Similar questions

More Gatik interview questions

All 1 Gatik questions →