Skip to content

CSV files, ROS bags and arrays: the readers

iter_csv, iter_rosbag and iter_array read a file, a ROS bag or an array and give a stream of Signal and, when there is one, of a target y. The overview of the section is on Streams.

1. A robot log file becomes a stream

A CSV file with the columns of the CASPER recording as it is distributed on Kaggle (Kayan et al. 2023), one row per sample, with a timestamp column and a column holding the six joint velocities as a list; here three joints and three rows.

from pathlib import Path
from dense_armor.core.signals.stream import iter_csv

p = Path("arm.csv")
p.write_text(
    "Timestamp,Actual Joint Velocities\n"
    '0.00,"[0.1, -0.2, 0.0]"\n'
    '0.05,"[0.2, -0.1, 0.0]"\n'
    '0.10,"[0.3, 0.0, 0.1]"\n'
)
for sig, y in iter_csv(p, time_col="Timestamp", array_cols=["Actual Joint Velocities"]):
    print(sig.t, {k: round(float(v), 2) for k, v in sig.items()})
0.0 {'Actual_Joint_Velocities_0': 0.1, 'Actual_Joint_Velocities_1': -0.2, 'Actual_Joint_Velocities_2': 0.0}
0.05 {'Actual_Joint_Velocities_0': 0.2, 'Actual_Joint_Velocities_1': -0.1, 'Actual_Joint_Velocities_2': 0.0}
0.1 {'Actual_Joint_Velocities_0': 0.3, 'Actual_Joint_Velocities_1': 0.0, 'Actual_Joint_Velocities_2': 0.1}

Each row becomes one Signal with its timestamp; the list column is split into one channel per joint. The file is read one row at a time, so a 24-hour log uses the same memory as a three-row one; start and stop read only a time window and stop at the end of it. An empty or unreadable cell becomes a missing channel, not an error.

API reference

csv

Read a CSV file as a stream of :class:Signal samples.

Examples:

>>> import tempfile
>>> from pathlib import Path
>>> from dense_armor.core.signals.stream import iter_csv
>>> d = tempfile.mkdtemp()
>>> p = Path(d) / "t.csv"
>>> _ = p.write_text("t,a,b\n0,1,2\n1,3,4\n")
>>> for sig, y in iter_csv(p, time_col="t"):
...     print(sig["a"], sig["b"], sig.t)
1.0 2.0 0.0
3.0 4.0 1.0

iter_csv

iter_csv(
    path: str | Path,
    target: str | None = None,
    time_col: str | None = None,
    columns: list[str] | None = None,
    array_cols: list[str] | None = None,
    start: float | None = None,
    stop: float | None = None,
) -> Iterator[tuple[Signal, Any]]

Iterate rows of a CSV file as (Signal, y) pairs.

Parameters:

Name Type Description Default
path str | Path

path to the CSV file.

required
target str | None

label column, or None.

None
time_col str | None

timestamp column in seconds, or None.

None
columns list[str] | None

scalar feature columns. None = every column but target, time_col and array_cols.

None
array_cols list[str] | None

columns holding a list literal "[...]", expanded into <name>_0, ..., <name>_{k-1} channels; k from the first row.

None
start float | None

skip rows before this time; needs time_col.

None
stop float | None

stop at the first row past this time; needs time_col.

None

Yields:

Type Description
tuple[Signal, Any]

(signal, label) pairs in file order.

Raises:

Type Description
ValueError

on a requested column that is not in the file, or on start or stop without time_col.

Source code in dense_armor/core/signals/stream/csv.py
def iter_csv(
    path: str | Path,
    target: str | None = None,
    time_col: str | None = None,
    columns: list[str] | None = None,
    array_cols: list[str] | None = None,
    start: float | None = None,
    stop: float | None = None,
) -> Iterator[tuple[Signal, Any]]:
    """Iterate rows of a CSV file as ``(Signal, y)`` pairs.

    Args:
        path: path to the CSV file.
        target: label column, or ``None``.
        time_col: timestamp column in seconds, or ``None``.
        columns: scalar feature columns. ``None`` = every column but
            ``target``, ``time_col`` and ``array_cols``.
        array_cols: columns holding a list literal ``"[...]"``, expanded
            into ``<name>_0, ..., <name>_{k-1}`` channels; ``k`` from the
            first row.
        start: skip rows before this time; needs ``time_col``.
        stop: stop at the first row past this time; needs ``time_col``.

    Yields:
        ``(signal, label)`` pairs in file order.

    Raises:
        ValueError: on a requested column that is not in the file, or on
            ``start`` or ``stop`` without ``time_col``.
    """
    if time_col is None and (start is not None or stop is not None):
        raise ValueError("start and stop need time_col")
    array_cols = [] if array_cols is None else list(array_cols)
    path = Path(path)
    with path.open(newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        header = list(reader.fieldnames or [])
        for name in columns or []:
            if name not in header:
                raise ValueError(f"column {name!r} not in {header}")
        for name in array_cols:
            if name not in header:
                raise ValueError(f"column {name!r} not in {header}")
        if target is not None and target not in header:
            raise ValueError(f"target {target!r} not in {header}")
        if time_col is not None and time_col not in header:
            raise ValueError(f"time_col {time_col!r} not in {header}")
        if columns is None:
            col_list = [
                c
                for c in header
                if c != target and c != time_col and c not in array_cols
            ]
        else:
            col_list = list(columns)
        try:
            first = next(reader)
        except StopIteration:
            return
        array_lengths: dict[str, int] = {}
        for name in array_cols:
            parsed = _parse_array_cell(first.get(name))
            array_lengths[name] = 0 if parsed is None else len(parsed)
        feat_names: list[str] = list(col_list)
        for name in array_cols:
            clean = name.replace(" ", "_")
            for i in range(array_lengths[name]):
                feat_names.append(f"{clean}_{i}")
        feat_units: list[str] = ["" for _ in feat_names]
        for row in chain([first], reader):
            t_val: float | None = None
            if time_col is not None:
                t_val = _parse_scalar_cell(row.get(time_col))
            if t_val is not None:
                if start is not None and t_val < start:
                    continue
                if stop is not None and t_val > stop:
                    return
            vals: list[float] = []
            mask: list[bool] = []
            for name in col_list:
                v = _parse_scalar_cell(row.get(name))
                if v is None:
                    vals.append(float("nan"))
                    mask.append(True)
                else:
                    vals.append(v)
                    mask.append(False)
            for name in array_cols:
                k = array_lengths[name]
                parsed = _parse_array_cell(row.get(name))
                if parsed is None or len(parsed) != k:
                    for _ in range(k):
                        vals.append(float("nan"))
                        mask.append(True)
                else:
                    for v in parsed:
                        vals.append(v)
                        mask.append(False)
            if not vals:
                sig = Signal(values=np.zeros(0, dtype=get_default_dtype()), names=[], units=[], t=t_val)
            else:
                sig = Signal(
                    values=as_default_array(vals),
                    names=feat_names,
                    units=feat_units,
                    t=t_val,
                    missing=np.asarray(mask, dtype=bool),
                )
            if target is not None:
                raw = row.get(target)
                if raw is None or str(raw).strip() == "":
                    label: Any = None
                else:
                    try:
                        label = float(raw)
                    except (TypeError, ValueError):
                        label = raw
            else:
                label = None
            yield sig, label

rosbag

Read ROS 1 and ROS 2 bags as a stream of :class:Signal samples.

The pure Python package rosbags reads both formats; it is an optional dependency, installed with the extra [ros], and imported inside :func:iter_rosbag. Every sensor_msgs/msg/JointState message becomes one :class:Signal with channels q_<joint>, qd_<joint>, tau_<joint>.

On Windows the rosbags package cannot generate ROS 1 message definitions (it builds them with PosixPath), so ROS 1 bags are tested on Linux and macOS.

Examples:

>>> from dense_armor.core.signals.stream import iter_rosbag
>>> stream = iter_rosbag("/path/to/bag")

iter_rosbag

iter_rosbag(
    path: str | Path, topics: list[str] | None = None
) -> Iterator[tuple[Signal, Any]]

Iterate a ROS 1 or ROS 2 bag as (Signal, y) pairs.

Parameters:

Name Type Description Default
path str | Path

ROS 1 .bag file, or ROS 2 bag directory.

required
topics list[str] | None

topic names to read. None = every topic with a sensor_msgs/msg/JointState message. A name that is not in the bag (or is not a JointState topic) is ignored without an error, so a typo gives an empty iteration.

None

Yields:

Type Description
tuple[Signal, Any]

(signal, None) pairs, in message order.

Raises:

Type Description
ImportError

if rosbags is not installed.

Source code in dense_armor/core/signals/stream/rosbag.py
def iter_rosbag(
    path: str | Path,
    topics: list[str] | None = None,
) -> Iterator[tuple[Signal, Any]]:
    """Iterate a ROS 1 or ROS 2 bag as ``(Signal, y)`` pairs.

    Args:
        path: ROS 1 ``.bag`` file, or ROS 2 bag directory.
        topics: topic names to read. ``None`` = every topic with a
            ``sensor_msgs/msg/JointState`` message. A name that is not in
            the bag (or is not a ``JointState`` topic) is ignored without
            an error, so a typo gives an empty iteration.

    Yields:
        ``(signal, None)`` pairs, in message order.

    Raises:
        ImportError: if ``rosbags`` is not installed.
    """
    AnyReader = _load_rosbags()
    path = Path(path)
    with AnyReader([path]) as reader:
        if topics is None:
            conns = [c for c in reader.connections if c.msgtype == _JOINT_STATE]
        else:
            wanted = set(topics)
            conns = [
                c
                for c in reader.connections
                if c.msgtype == _JOINT_STATE and c.topic in wanted
            ]
        if not conns:
            return
        for conn, ts_ns, raw in reader.messages(connections=conns):
            msg = reader.deserialize(raw, conn.msgtype)
            name = list(msg.name)
            pos = list(msg.position)
            vel = list(msg.velocity)
            eff = list(msg.effort)
            vals: dict[str, float] = {}
            units: dict[str, str] = {}
            for j, jname in enumerate(name):
                if j < len(pos):
                    vals[f"q_{jname}"] = float(pos[j])
                    units[f"q_{jname}"] = "rad"
                if j < len(vel):
                    vals[f"qd_{jname}"] = float(vel[j])
                    units[f"qd_{jname}"] = "rad/s"
                if j < len(eff):
                    vals[f"tau_{jname}"] = float(eff[j])
                    units[f"tau_{jname}"] = "N*m"
            if not vals:
                continue
            t_s = float(ts_ns) * 1e-9
            sig = Signal.from_dict(vals, units=units, t=t_s)
            yield sig, None

array

Read a numpy or JAX array as a stream of :class:Signal samples.

Examples:

>>> import numpy as np
>>> from dense_armor.core.signals.stream import iter_array
>>> X = np.array([[1.0, 2.0], [3.0, 4.0]])
>>> for sig, y in iter_array(X, names=["a", "b"], units=["m", "s"]):
...     print(sig["a"], sig["b"], sig.t, y)
1.0 2.0 0.0 None
3.0 4.0 1.0 None

iter_array

iter_array(
    X: Any,
    y: Any = None,
    t: Any = None,
    names: Iterable[str] | None = None,
    units: Iterable[str] | None = None,
) -> Iterator[tuple[Signal, Any]]

Iterate rows of an array as (Signal, y) pairs.

Parameters:

Name Type Description Default
X Any

array of shape (n, d) or (n,).

required
y Any

optional labels of shape (n,).

None
t Any

optional timestamps in seconds. If None, t = float(i).

None
names Iterable[str] | None

channel names in column order.

None
units Iterable[str] | None

channel units.

None

Yields:

Type Description
tuple[Signal, Any]

(signal, label) pairs in time order.

Raises:

Type Description
ValueError

if a length does not match.

Source code in dense_armor/core/signals/stream/array.py
def iter_array(
    X: Any,
    y: Any = None,
    t: Any = None,
    names: Iterable[str] | None = None,
    units: Iterable[str] | None = None,
) -> Iterator[tuple[Signal, Any]]:
    """Iterate rows of an array as ``(Signal, y)`` pairs.

    Args:
        X: array of shape ``(n, d)`` or ``(n,)``.
        y: optional labels of shape ``(n,)``.
        t: optional timestamps in seconds. If ``None``, ``t = float(i)``.
        names: channel names in column order.
        units: channel units.

    Yields:
        ``(signal, label)`` pairs in time order.

    Raises:
        ValueError: if a length does not match.
    """
    arr = np.asarray(X)
    if arr.ndim == 1:
        arr = arr[:, None]
    if arr.ndim != 2:
        raise ValueError(f"X must be 1D or 2D, got shape {arr.shape}")
    n, d = arr.shape
    name_list = [f"x{i}" for i in range(d)] if names is None else list(names)
    if len(name_list) != d:
        raise ValueError(f"names has {len(name_list)} entries, X has {d} columns")
    unit_list = ["" for _ in range(d)] if units is None else list(units)
    if len(unit_list) != d:
        raise ValueError(f"units has {len(unit_list)} entries, X has {d} columns")
    y_arr = None if y is None else np.asarray(y)
    if y_arr is not None and len(y_arr) != n:
        raise ValueError(f"y has {len(y_arr)} entries, X has {n} rows")
    if t is None:
        t_arr = np.arange(n, dtype=get_default_dtype())
    else:
        t_arr = as_default_array(t)
        if len(t_arr) != n:
            raise ValueError(f"t has {len(t_arr)} entries, X has {n} rows")
    for i in range(n):
        sig = Signal(
            values=arr[i],
            names=name_list,
            units=unit_list,
            t=float(t_arr[i]),
        )
        yield sig, (None if y_arr is None else y_arr[i])

Details

  • iter_csv uses Python's csv module, one row at a time; a list cell "[a, b, c]" becomes channels <name>_0, <name>_1, ... (spaces in the name become underscores); start / stop select a window on time_col and stop reading after stop.
  • iter_rosbag(path, topics=None) reads ROS 1 and ROS 2 bags with the pure Python package rosbags (extra [ros]); sensor_msgs/msg/JointState becomes channels q_<joint>, qd_<joint>, tau_<joint> with the time of the message header.