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:
PointCloudcontainer (PointCloud(points, metadata=None)):- Stores
pointsas a 2D NumPyfloatarray of shape(N, D)withN >= 0andD >= 3, where columns0, 1, 2hold(x, y, z)coordinates and columns3 .. D - 1hold optional per-point channels (such as reflectance or beam index). - Stores a
metadatadictionary (defaulting to{}), ensuring"applied_transforms"is initialized as alistwhile preserving any pre-existing keys and history entries without mutating caller-owned dictionaries or lists.
- Stores
- Abstract stage interface & class registry:
BaseTransform(ABC)defines an abstractapply(self, pc: PointCloud) -> PointCloudmethod.TransformRegistry(with decorator@register_transform(name)) maps string stage names toBaseTransformsubclasses and instantiates stages from configuration dictionaries.
- Registered stages:
"CropBoundingBox": expectsparamscontaining"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 satisfyingmin_bound[i] <= max_bound[i]on every axis. Retains points wheremin_bound <= (x, y, z) <= max_boundalong all three axes (inclusive), keeps allDcolumns and relative row order, and appends{"name": "CropBoundingBox", "remaining_points": count}tometadata["applied_transforms"]."RigidTransform": expectsparamscontaining a non-empty string"target_frame"and"matrix", a4 x 4homogeneous matrix of finite real numbers whose fourth row is[0, 0, 0, 1]. Appliesmatrix @ [x, y, z, 1]^Tto each point's(x, y, z)coordinates while leaving columns3 .. D - 1untouched, setsmetadata["frame_id"] = target_frame, and appends{"name": "RigidTransform"}tometadata["applied_transforms"].
TransformPipeline(config)& entry wrapper:configis a list of step dictionaries[{"name": "<stage>", "params": {...}}, ...](missing orNone"params"is treated as{}).TransformPipeline.__init__must validate every step up front—raisingValueErrorimmediately 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 priorPointCloudinstances.run_point_cloud_pipeline(points, metadata, config)buildsTransformPipeline(config), wrapspoints(treating[]as an empty(0, 3)cloud) andmetadatainto aPointCloud, 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 >= 0andD >= 3for every non-emptypointsinput (points == []representsN = 0).- Every stage and pipeline call must leave the caller's input
pointslist andmetadatadictionary unmutated. - Any invalid configuration or stage parameter must raise
ValueErrorduringTransformPipelineconstruction, even whenpointsis empty.
Step-by-step walkthrough
Understand the goal and pipeline contract
A LiDAR sensor produces a point cloud: a 2D table of
Npoints andD >= 3columns 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 laserintensityor ring ID. Alongside the array travels ametadatadictionary tracking the coordinate frame (frame_id), timestamps, and anapplied_transformsaudit log.We need to build four modular pieces and connect them through the judged entry function
run_point_cloud_pipeline(points, metadata, config):PointCloud: Holds the(N, D)NumPy array andmetadatawithout mutating the caller's original lists or dictionaries.BaseTransformandTransformRegistry(@register_transform): Maps string names from a YAML config ("CropBoundingBox","RigidTransform") to transform classes without a brittleif / elifchain.CropBoundingBoxandRigidTransform: Validate their parameters on construction (ValueErroron 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"}).TransformPipeline: Instantiates and validates every step inside__init__before a single point is processed, then applies them sequentially inrun.
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 thenrunis called 10–20 times per second on live LiDAR frames. If step 4 has a typo ("VoxleDownsample"ormin_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)Build the PointCloud container without mutating caller data
When a transform produces a new
PointCloud, a shallow copydict(self.metadata)is not enough on its own: both dictionaries would still point to the exact sameapplied_transformslist 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)withD >= 3insidePointCloud.__init__, copy both the dictionary andapplied_transforms, and provide a smallwith_stephelper that creates the next stage'sPointCloudcleanly.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)Create BaseTransform and the @register_transform registry
BaseTransforminherits from Python'sABC(Abstract Base Class) and marksapplywith@abstractmethod, which prevents anyone from instantiating a transform class that forgot to implementapply.TransformRegistryholds a class-level dictionary_classesmapping string names to classes. Writing@register_transform("CropBoundingBox")above a class runsdecorator(CropBoundingBox)at import time, storing"CropBoundingBox": CropBoundingBoxin_classesso adding a new transform later never requires editingTransformPipeline.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.registerWrite 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_boundsinstead of silently ignoring it. boolis a subclass ofintin Python!isinstance(True, int)evaluates toTrue, and YAML parsestrueoryesasTrue. We explicitly rejectbooland non-finite values (NaN,inf).- Fixed-length numeric vectors:
_parse_float_vectorverifies exact length (3 for box bounds, 4 for matrix rows) before converting entries tofloat.
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- Typos in parameter keys: Checking both missing keys and unexpected extra keys catches a typo like
Implement CropBoundingBox with vectorized NumPy masks
CropBoundingBoxchecks thatmin_boundandmax_boundeach have 3 finite numbers withmin_bound <= max_boundon all three axes (min == maxis allowed for a flat plane crop;min > maxraisesValueError).At runtime, we slice
xyz = pc.points[:, :3](shape(N, 3)) and compare againstself.min_boundandself.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 -> KEEPIndexing
pc.points[inside_box_mask]filters allDcolumns at once (keepingreflectanceattached) and always allocates a fresh NumPy array, even whenN == 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)Implement RigidTransform with 4x4 homogeneous coordinates
Why does 3D robotics use a
4 x 4matrix to move(x, y, z)points? A3 x 3matrix can rotate(x, y, z), but it cannot add a shift(tx, ty, tz). Appending a fourth coordinate1—called homogeneous coordinates[x, y, z, 1]—lets a single4 x 4matrix multiplication perform both rotationRand translationtat 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.pointsstores each point as a row rather than a column, multiplying a batch of row vectors[x, y, z, 1]on the right requires the transposeM.T(since(M @ p)^T = p^T @ M^T). And as long as the bottom row ofMis[0, 0, 0, 1], the fourth output column stays1, so slicing[:, :3]gives(x', y', z')directly!Two important engineering details:
- Transform only
[:, :3], then copy extra channels: Never multiply a(N, 4)[x, y, z, intensity]cloud directly byM.T—that would plugintensityin place of1and scale the translation byintensity! Instead, transformpc.points[:, :3]and write the result into a copy ofpc.points. - Do not reject hand-rounded calibration YAML matrices: Real sensor calibration YAML files often write
0.866forcos(30°)instead of 16 digits of float precision, soR.T @ Rdiffers fromIby ~4e-5. We validate thatMis4 x 4finite numbers with bottom row[0, 0, 0, 1](within1e-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)- Transform only
Wire up TransformPipeline and the judge entry point
TransformPipeline.__init__validates the outer list, checks each step dictionary, and callsTransformRegistry.create(step["name"], params)for every step up front—attachingstep_indexto anyValueErrorso 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! Whenlen(points) == 0, we constructnp.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, }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"throughTransformRegistryand validates bounds[-5, -5, -2] <= [5, 5, 2]and the4 x 4matrix 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 reflectance0.9and0.7, and appends{"name": "CropBoundingBox", "remaining_points": 2}. - Stage 2 (
RigidTransform): Converts(x, y, z)to[x, y, z, 1], multiplies bymatrix.Tto shift by(+1.5, -0.5, +2.0), writes[[3.5, -1.5, 2.5], [-2.5, 2.5, 1.0]]alongside untouched reflectance0.9and0.7, updatesframe_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 a4 x 4matrix), andO(S * N * D)to execute a scan acrossSstages (cropping checks3 * Ncoordinates and copies up toN * Dfloats; rigid transformation multiplies an(N, 4)array by(4, 4)inO(N)operations and copiesN * Dfloats). - Space:
O(S)for the instantiated stage list, plusO(N * D)peak auxiliary memory per stage for the output(N, D)array and(N, 4)homogeneous buffer.
Edge cases
- Empty scan (
N = 0): Becausenp.asarray([])produces a 1D(0,)array,run_point_cloud_pipelineinitializespoints = []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 countD = 5even at0rows, letting subsequentRigidTransformstages run cleanly. - Extra per-point channels (
D > 3): Columns3 .. D - 1remain untouched across both region cropping and 3D rigid transformations. - Inclusive box faces and zero-thickness planes: Points lying directly on
min_boundormax_boundsatisfy>=and<=and stay;min_bound == max_boundon an axis is valid. - Caller immutability and existing metadata: Custom keys such as
seqortimestampsurvive intact,applied_transformsextends a fresh list copy, and callerpointsandmetadataare never mutated. - YAML quirks (
Noneparams and booleans): Missing orNoneparamsnormalizes to{}, andTrue/Falseare rejected as numbers despiteboolsubclassingintin Python.
Common mistakes
- Validating lazily inside
run(): Deferring stage lookup or parameter checks untilapplyfails the startup-validation contract wheneverpoints = []or an invalid step sits after a stage that drops all points. - Shallow-copying
metadataalone: A shallow copy (duplicating only the outer dictionary while aliasing inner mutable lists) mutates the caller'sapplied_transformslist in place; copy the list too. - Multiplying all
Dcolumns by the4 x 4matrix: Passing[x, y, z, reflectance]directly into@ matrix.Ttreatsreflectanceas homogeneousw = 1(scaling translations byreflectance) and crashes wheneverD != 4. - Forgetting the transpose
matrix.T: Column-vector math usesM @ p, so row-vector batches of shape(N, 4)requirehomogeneous_xyz @ matrix.T. - Overly strict rotation-orthogonality tolerance (
R.T @ R == Iwithin1e-6): Calibration files often store rounded decimals like0.866forcos(30°); rejecting slight rounding breaks valid real-world configs. - Calling
np.asarray([])directly: Yields 1D shape(0,)instead of 2D(0, 3), triggeringIndexErroron[:, :3].
Alternative approaches
- Subclass hook (
__init_subclass__): Defining__init_subclass__onBaseTransformauto-registers subclasses without a decorator, though@register_transform("...")decouples external config names from internal class renames. - Separate
3 x 3rotation +3translation (xyz @ R.T + t): SlicingR = matrix[:3, :3]andt = 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
BaseModelconfigured withextra="forbid", fixed-length float tuples, and a@model_validatorenforcingmin_bound <= max_bound) insideTransformRegistry. 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
float32rather thanfloat64to cut memory bandwidth in half, and adopt a structure of arrays (SoA) layout (keepingx,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 consecutiveRigidTransformmatrices into one composite4 x 4matrix, 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 instreams: Dict[str, PointCloud], clonemetadataindependently per output branch so"surface"and"obstacles"maintain separate audit logs, and return the requested terminal streams.
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?
- 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?
- 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)?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes