Skip to content

Bring your own dataset

apairo reads a dataset as a set of channels — one directory per channel, holding per-frame files (or a single stacked file) in a format the loader registry understands (npy, npys, bin, img, zarr, pcd, csv, hdf5, video). Turning your directories into a loadable dataset comes down to three small questions per channel. Two have always been implicit; this page makes all three explicit — and shows how the key and order fields let a channel carry its own alignment clock and enumeration policy right in its filenames, with nothing ever written into your data tree.

This is the entry point for the asynchronous family: the profile-free RawDataset (channels read straight from .apairo/channels.yaml) and its fixed-channel subclasses such as TartanKittiDataset.


The three contracts

Every channel answers three questions. apairo ships a sensible default for each, so a plain directory of numbered files needs no configuration at all (frames are read in numeric order: 2.npy before 10.npy, padded or not).

Contract Question it answers Built-in default
order how are this channel's frames listed and ordered? files matching the frame-file convention (is_frame_file), sorted numerically
load how is one frame decoded to a numpy array? the loader named in channels.yaml (npy / npys / bin / img / zarr / pcd / csv)
key what is each frame's alignment key — the value synchronize() matches on? the channel's own timestamps.txt, else a borrowed one (timestamps_from)

order and load were always there; key used to be hardwired to timestamps.txt. The additive change is that key and order are now declarable per channel — and both default to today's behavior, so everything you already load keeps loading identically.

Every channel needs a clock

A channel with no timestamps.txt, no key and no timestamps_from is refused at load, and apairo check names it: frames are never paired by position behind your back. When a channel's frames are numbered like another's (KITTI-style), say so: timestamps_from borrows that channel's clock, or key: {name: '(\d+)'} makes the frame index the key. (A synchronous, position-paired layout is what the ProfiledDataset family reads -- see Not in scope.)


Nothing is written — keys are read-time, in memory

The key is computed in memory, at read time: apairo never writes a clock, nor touches your data files. A filename-keyed channel derives its clock from the filenames it already has, so it needs no timestamps.txt sidecar at all. The only thing loading writes is apairo's own registry, a .apairo/ directory next to the data, on first open; on a read-only mount, a shared cluster volume or an ro container it keeps that registry in memory instead, and loading works the same. Materializing a self-contained clock belongs to the write side (export, the extractor), never to reading.

Where to declare — apairo.yaml, not the machine registry

The key / order / fields / alias contracts are human knowledge — no scan can regenerate them. Start from apairo declare <dir> (a scaffold with the detected channels and commented hints), then write them in a declaration: <seq>/apairo.yaml, a visible file apairo never writes, safe from init --force and versionable in git. The examples below show the channel entries; they work identically in apairo.yaml (preferred) and in .apairo/channels.yaml (the machine registry — hand-editing it works but mixes your knowledge into a regenerable file).

For a tree you cannot or do not want to touch at all, keep the declaration outside it and pass it at load time:

ds = apairo.RawDataset(root, declare="eval/my_dataset.yaml")

Per-field precedence: declare= > <seq>/apairo.yaml > <root>/apairo.yaml > .apairo/channels.yaml (a dataset root's file applies to every sequence).


The key field

Add key: to a channel entry (in apairo.yaml, or the registry). Three forms.

key: {name: <regex>} — parse the key from the filename

The regex is matched against each file's stem (its name without the extension); the capture groups are combined into a number:

  • one group → an integer index or a float — frame(\d+)- on frame000123-... yields 123;
  • two groups → '<int>.<frac>' by the default rule float('.'.join(groups)) — a Rellis frame000123-1581624652_750 stem under frame\d+-(\d+)_(\d+) yields 1581624652.750.
camera: {loader: img, key: {name: 'frame\d+-(\d+)_(\d+)'}}   # timestamp from the filename
seg:    {loader: img, key: {name: 'frame(\d+)-'}}            # integer index from the filename

scale: — an explicit unit combine

When joining the groups as a decimal string is not what you want — the fractional part is not zero-padded, or the groups are in different units — give an explicit scale, one factor per group, summed as sum(int(group_i) * scale_i):

camera:
  loader: img
  key: {name: 'frame\d+-(\d+)_(\d+)', scale: [1, 0.001]}   # seconds + milliseconds

<sec> counts as seconds and <ms> as milliseconds, so 1581624652_750 becomes 1581624652 + 750 * 0.001 = 1581624652.750 regardless of how the millisecond field is padded.

units: — the readable form of scale

Raw scale factors are terse. When every capture group is a time field, name the units instead — units: compiles to scale (s → 1, ms → 1e-3, us → 1e-6, ns → 1e-9):

camera: {loader: img, key: {name: 'frame\d+-(\d+)_(\d+)', units: [s, ms]}}

reads exactly as scale: [1, 0.001] but says what it means. units and scale are mutually exclusive.

Heterogeneous names — a timestamp and an index

units only combines time fields. A stem like camera_<sec>_<frame-index> mixes a clock with a counter, and an index is not a duration — don't fold it into the key. Capture only the key field and let order handle the rest:

camera:
  loader: img
  key:   {name: 'camera_(\d+)_\d+', units: [s]}   # the seconds are the key
  order: {name: 'camera_\d+_(\d+)'}                # the index only sorts

The index never pollutes the alignment key. Frames that share a second then share a key — synchronize() treats them as simultaneous; if you need sub-second ordering from the index, a _key_providers callable is the escape hatch.

key: {file: <name>} — read the key from a sidecar

Read the key array from a named file inside the channel directory, one float per line, in frame order. This generalizes timestamps.txt to any filename:

imu: {loader: npy, key: {file: stamps.txt}}

key: {column: <index or name>} — read the key from a table column

A csv channel is one delimited text table, one row per frame — the shape of IMU logs and ground-truth trajectories in most SLAM datasets. Its clock is one of its columns: name it by index or by header name, with an optional one-entry units (or scale). The key column is kept out of the frame data.

imu0: {loader: csv, key: {column: timestamp, units: [ns]}}   # EuRoC imu0/data.csv

The table is the directory's single .csv, or the file named by array_file (required for a .txt table, or when several tables share a directory). Rows may be comma-, tab- or whitespace-separated; # lines are comments. Column names come from a non-numeric first row, else from the last comment line when it has one name per column — EuRoC's #timestamp [ns],w_RS_S_x [rad s^-1],... and TUM's # timestamp tx ty tz qx qy qz qw both qualify. A trailing [unit] is dropped from a name (w_RS_S_x). fields: [...] keeps only the named columns, in that order.

A table that sits beside the channel directories rather than in one — TUM RGB-D's groundtruth.txt at the sequence root — is reached with directory: ".":

# TUM RGB-D: rgb/1305031102.175304.png, depth/..., groundtruth.txt
rgb:         {loader: img, key: {name: '(\d+)\.(\d+)'}}
depth:       {loader: img, key: {name: '(\d+)\.(\d+)'}}
groundtruth: {loader: csv, directory: ".", array_file: groundtruth.txt,
              key: {column: timestamp}}

ds.synchronize(reference="rgb", method="nearest", tolerance=0.02) is then the association TUM's associate.py computes, for every channel at once and with each match's offset reported. The TUM RGB-D guide walks through a real sequence, and the EuRoC guide through the data.csv layout.

latency — a sensor that stamps its readings late

A clock tells when a reading reached the computer, not when it was captured. A sensor read over a bus and forwarded by a microcontroller arrives late by a fixed delay, and its timestamps cannot show it -- they are all late together. When the delay is known, declare it on the channel, in seconds:

channels:
  imu:
    key: {column: t, units: [us]}
    latency: 0.008416        # documented: the IMU's readings arrive 8416 us late

The channel's clock is moved back by that much -- whether it comes from a key, a timestamps.txt or timestamps_from -- before synchronize() aligns it. The KUKA F/T and IMU guide measures such a delay in the data and checks the declared one against it.


A directory on its own

A directory that holds its data files itself, with no sub-directory, is a dataset too. Point apairo at a channel directory (seq/velodyne_0, frames and their timestamps.txt) or at a logger's folder of CSV files, and each one is a channel that reads from directory: ".": the frames are one channel named after the directory, every table is one channel named after its file.

$ apairo init kuka/          # 1-baseline_accel.csv  1-baseline_orientations.csv  1-baseline_wrench.csv
$ apairo declare kuka/       # writes key: {column: t, units: [us]} for each table
$ apairo status kuka/
channel                  kind  loader  frames  rate      span        shape
1-baseline_accel         raw   csv     1593    254.1 Hz  0.00-6.27s  (3) float64
1-baseline_orientations  raw   csv     627     100.0 Hz  0.00-6.26s  (9) float64
1-baseline_wrench        raw   csv     4376    698.1 Hz  0.00-6.27s  (6) float64

That is a real recording: a KUKA arm's IMU, orientation and force/torque sensor on three clocks (Zenodo 10.5281/zenodo.11096791).

A directory with a sub-directory keeps its meaning -- a sequence whose channels are its sub-directories, or a root. A table lying beside channel directories (a KITTI-style poses.txt) is not picked up on its own; declare it with directory: "." and array_file, as the TUM RGB-D guide does.


The order field

order is a separate contract from key: it decides which files are enumerated and in what order, independently of how the key is computed.

order: {name: <regex>} — the files whose stem matches, sorted lexicographically (which is frame order for zero-padded names).

You rarely set it, because it defaults sensibly:

  • absent and key: {name: ...} is set → order reuses the key's name regex;
  • absent otherwise → the default frame-file convention (is_frame_file, which reserves _ for suffixes and sorts numerically).

When order is required

The default convention reserves _ for channel suffixes and rejects any stem that carries one. A channel whose filenames embed an underscore the default would skip — a Rellis <epoch>_<ms> stem — must therefore be enumerated by a regex. Setting key: {name: ...} covers this automatically (its regex doubles as the order). Set order: {name: ...} explicitly only when the key comes from elsewhere (a file: key, or a callable) and the filenames still carry a _.


How it feeds synchronize()

The alignment engine is unchanged. Once a channel's key populates ds.timestamps[channel], synchronize() aligns it exactly as always — reference=, method= (nearest / previous / next), tolerance=. Sparse subsets fall out for free: a reference tick where a channel has no event within the tolerance is dropped from the view, so the view holds the moments where every channel has one.

ds = apairo.RawDataset(root, keys=["camera", "seg"])
view = ds.synchronize(reference="camera", method="nearest", tolerance=0.0)
# the camera frames that have a label, each with it; the others are dropped

Escape hatch — a callable per channel (the 10%)

Anything the DSL can't express, hand in as a callable from a subclass. Before super().__init__(), populate either provider dict — they are checked before the YAML specs:

class MyDataset(RawDataset):
    def __init__(self, directory, keys=None):
        self._key_providers = {
            "camera": lambda files: np.array([parse_epoch(f) for f in files]),
        }
        self._order_providers = {
            "camera": lambda directory: sorted(exotic_listing(directory)),
        }
        super().__init__(directory, keys=keys)
  • self._key_providers[channel] — callable(files: list[str]) -> np.ndarray, the channel's key array.
  • self._order_providers[channel] — callable(directory: str) -> list[str], the ordered filenames.

Either can be set on its own; the YAML key / order specs cover the remaining channels. Open such a dataset on the channels its providers explain (MyDataset(seq, keys=["camera"])): a channel whose stems carry a _ is otherwise read by the scan as a base channel and its suffixed variants.


Worked example — Rellis-3D camera

Rellis-3D historically loaded only lidar + labels: its camera could not be added. The files are named frame000123-<epoch>_<ms>.jpg — an index identical to the lidar, dressed with a timestamp and carrying a _ the default convention rejects — and its hand-labels are a ~half-rate subset, neither expressible by the equal-count positional reader. Two lines in channels.yaml express both, with no subclass and no transcode:

pylon_camera_node:          {loader: img, key: {name: 'frame\d+-(\d+)_(\d+)'}}   # <epoch>_<ms> timestamp
pylon_camera_node_label_id: {loader: img, key: {name: 'frame\d+-(\d+)_(\d+)'}}   # SAME timestamp -> label lands on its camera tick
  • pylon_camera_node — the key is the <epoch>_<ms> timestamp parsed from each stem. Because key: {name} is set, that same regex enumerates the underscore-bearing files, so order needs nothing.
  • pylon_camera_node_label_id — keyed by the same timestamp. The labels exist on a subset of frames, each sharing its camera frame's <epoch>_<ms>, so synchronize(..., tolerance=0.0) lands every label on its exact camera tick and keeps only the labeled frames. Both channels must key in the same space — an index-keyed label against an epoch-keyed camera would never match.
ds = apairo.RawDataset(rellis_seq,
                       keys=["pylon_camera_node", "pylon_camera_node_label_id"])
view = ds.synchronize(reference="pylon_camera_node", method="nearest", tolerance=0.0)

On real Rellis-3D this parses 2847 camera frames at 10 Hz straight from the filenames (median Δt 100.0 ms, monotonic) and synchronizes the 1200 sparse image-labels onto the dense camera — with zero writes into the Rellis tree.


Not in scope

This is the additive key / order contract for the asynchronous family. Unifying the synchronous ProfiledDataset family (SemanticKITTI, Rellis, GOOSE) behind the same key — making position-as-default one setting of a single order/load/key contract shared by both families, instead of two separate dataset families — is a larger architectural step and is not part of this feature. See IDEAS.md.