Skip to main content

Multi-Channel Storage & Cross-Channel Transforms

Overview

This document describes the implemented infrastructure for representing multi-channel acquisition data (e.g. 32–384 channels from an analog-to-digital converter) using TensorData as the canonical owner, with zero-copy AnalogTimeSeries column views for compatibility with existing single-channel widgets and transforms.

See GitHub Issue #240 for the original feature request. For planned future work (spatial whitening, tensor IIR filtering, block-cached mmap, tensor-backed binary loading), see Multi-Channel Roadmap.

Design Principles

  • TensorData is the canonical owner for multi-channel data. AnalogTimeSeries objects become lightweight column views.
  • LibTorch is the compute backend for cross-channel transforms. Armadillo remains the default storage backend for TensorData and provides zero-copy column access for AnalogTimeSeries views.
  • GPU acceleration is opt-in via device selection; the same LibTorch code runs on CPU or GPU.

Compute Backend: Armadillo (Storage) + LibTorch (Compute)

Cross-channel transforms use LibTorch as the single compute backend, even on CPU-only systems. This avoids maintaining separate Armadillo and LibTorch code paths for the same operations.

Armadillo vs LibTorch comparison for cross-channel compute
Concern Armadillo LibTorch
CPU/GPU unification Separate code paths Same code, change torch::Device
Memory layout Column-major Row-major default (natural for row-wise cross-channel ops like CAR)
Median/mean arma::median(mat, 1) torch::median(t, 1)
Eigendecomposition arma::eig_sym torch::linalg::eigh
Bulk type conversion Manual loop tensor.to(torch::kFloat32) — fused, SIMD-friendly

The use_gpu parameter reduces to device selection rather than an entirely different algorithm:

auto t = tensor.toLibTorch();
if (use_gpu) {
    t = DeviceManager::instance().toDevice(t);
}
auto ref = torch::median(t, /*dim=*/1).values;
t = t - ref.unsqueeze(1);

Armadillo serves as the default storage backend for TensorData (ArmadilloTensorStorage). Its column-major layout is ideal for TensorColumnAnalogStorage because each column is contiguous — perfect for AnalogTimeSeries span access. The toLibTorch() conversion bridges storage to compute when transforms are applied.

Storage Layout

A 32-channel, 1M-sample recording stored in-memory as a TensorData lives in an Armadillo arma::fmat(1000000, 32) — column-major. Each column is one channel, contiguous in memory. \(N\) AnalogTimeSeries objects (one per channel) reference this same matrix through TensorColumnAnalogStorage, which hands DataViewer a zero-copy std::span<float const> via fmat.colptr(c).

┌──────────────────────────────────────────────────────┐
│          arma::fmat  (column-major in memory)        │
│                                                      │
│  col 0 (ch0)  col 1 (ch1)  col 2 (ch2)  …  col 31  │
│  ┌─────────┐  ┌─────────┐  ┌─────────┐     ┌──────┐ │
│  │ t0      │  │ t0      │  │ t0      │     │ t0   │ │
│  │ t1      │  │ t1      │  │ t1      │     │ t1   │ │
│  │ …       │  │ …       │  │ …       │     │ …    │ │
│  │ t999999 │  │ t999999 │  │ t999999 │     │ …    │ │
│  └─────────┘  └─────────┘  └─────────┘     └──────┘ │
│  ↑ contiguous  ↑ contiguous  ↑ contiguous            │
└──────────────────────────────────────────────────────┘
        │               │               │
        ▼               ▼               ▼
  AnalogTimeSeries  AnalogTimeSeries  AnalogTimeSeries
  (TensorColumn     (TensorColumn     (TensorColumn
   Storage, ch0)     Storage, ch1)     Storage, ch2)

This layout is the right canonical format for multi-channel data that fits in memory. Each AnalogTimeSeries is a lightweight view — no copies, no duplication, full compatibility with DataViewer_Widget and existing single-channel infrastructure.

Why not one flat AnalogTimeSeries?

An alternative would be concatenating all channels end-to-end in a single AnalogTimeSeries ([ch0_all_t, ch1_all_t, ...]). This is essentially what Armadillo column-major memory already is — a contiguous buffer of \(N_{\text{channels}} \times N_{\text{samples}}\) floats. But the matrix representation is strictly better: it carries shape, column names, TimeFrame metadata, and 2D indexing. Cross-channel transforms index mat.col(c) instead of manually computing offset + c * num_samples. And each TensorColumnAnalogStorage view is a first-class AnalogTimeSeries that plugs into DataViewer, transforms, and export without special-casing.

Armadillo ↔︎ LibTorch Conversion

When a cross-channel transform runs, data moves from Armadillo (storage) to LibTorch (compute) and back. TensorData::toLibTorch() uses torch::from_blob with column-major strides for a zero-copy view of Armadillo’s memory, followed by .contiguous() to produce a row-major tensor:

auto const & mat = arma_storage->matrix();
auto t = torch::from_blob(
    const_cast<float*>(mat.memptr()),
    {static_cast<int64_t>(mat.n_rows), static_cast<int64_t>(mat.n_cols)},
    {1, static_cast<int64_t>(mat.n_rows)},  // column-major strides
    torch::kFloat32
);
// t is a zero-copy strided view — no data movement

This eliminates the \(O(n)\) virtual calls from the old materializeFlat() path and reduces the conversion to a single contiguous memcpy.

The full round-trip cost for applying a transform is:

Round-trip cost for applying a cross-channel transform
Step Operation Copies
Storage arma::fmat(time, channels) — column-major canonical
View \(N\) TensorColumnAnalogStorage views → DataViewer 0
To compute toLibTorch() → strided view of Armadillo memory 0
Transform e.g. whitening — allocates result tensor (row-major) 1 (result only)
Back to storage result.toArmadillo() → new arma::fmat (col-major) 1 (layout convert)
New views \(N\) new TensorColumnAnalogStorage on result 0

Total: one copy for the transform input (zero-copy via strides), one copy for the output (layout conversion). For 128 MB of data (32ch × 1M × 4B), the output copy is ~30ms — negligible compared to the eigendecomposition in whitening.

Transform Responsibility: AnalogTimeSeries vs TensorData

A key architectural question arises when both single-channel and multi-channel data exist in the same system: where should per-channel transforms (like IIR filtering) live?

Principle: Single-channel transforms stay on AnalogTimeSeries. Multi-channel transforms — including “apply the same filter to all channels” — go on TensorData.

Transform responsibility by data origin
Data origin Transform target Why
Single-channel source (e.g. one sensor) AnalogTimeSeries Data is naturally a contiguous std::vector<float>. Existing filter code runs at full speed on a tight span.
Multi-channel source (e.g. 32-ch ADC) TensorData Data lives in a matrix. Per-column iteration on Armadillo columns is contiguous and fast. Cross-channel ops (CAR) need the full matrix.

Heavy compute (filtering, CAR, whitening) happens after materializing into a proper TensorData where columns are contiguous and LibTorch can operate on the full matrix. This avoids a problematic design where single-channel transforms need to be aware of their storage backend’s memory layout.

AnalogToTensor & TensorToAnalog Transforms

AnalogToTensor Container Transform

Files:

  • src/TransformsV2/algorithms/AnalogToTensor/AnalogToTensor.hpp
  • src/TransformsV2/algorithms/AnalogToTensor/AnalogToTensor.cpp

Transform type: N-ary container (N AnalogTimeSeries → 1 TensorData).

Parameters struct (reflect-cpp):

struct AnalogToTensorParams {
    std::string channel_prefix;                // prefix to match AnalogTimeSeries keys
    std::vector<std::string> channel_keys;     // selected DataManager keys (populated from prefix)
};

The first-pass UI uses a hybrid prefix + multi-select approach:

  • channel_prefix is a dynamic_combo field populated with unique prefixes discovered from AnalogTimeSeries keys in DataManager (e.g. "voltage", "emg").
  • When a prefix is selected, channel_keys (a dynamic_combo std::vector<std::string> field) is populated with all matching keys and rendered as a multi-select QListWidget with all items checked by default. The user can uncheck individual channels to exclude them.

This is enabled by the std::vector<T> support in ParameterSchema and AutoParamWidget (see ParameterSchema developer docs).

Note

Infrastructure dependency resolved: ParameterSchema now detects std::vector<T> fields at compile time (is_vector, vector_element_type), and AutoParamWidget renders them as multi-select lists (for vector<string> + dynamic_combo) or CSV line edits (for vector<int>, vector<float>). All items are checked by default on first population. The list has a max height of 200px with scrolling for large channel counts.

Algorithm (implemented):

  1. Validate all channels are non-null, share the same TimeFrame (pointer identity), and have identical sample counts.
  2. Build flat row-major data by iterating each channel via viewValues() (mmap-safe; avoids the empty-span problem).
  3. Return TensorData::createTimeSeries2D(...) preserving the shared TimeFrame and TimeIndexStorage. Column names come from channel_keys when sizes match, otherwise auto-generated as "ch0", "ch1", etc.

TensorToAnalog Container Transform

Files:

  • src/TransformsV2/algorithms/TensorToAnalog/TensorToAnalog.hpp
  • src/TransformsV2/algorithms/TensorToAnalog/TensorToAnalog.cpp

Parameters struct:

struct TensorToAnalogParams {
    std::string output_key_prefix; // prefix for generated AnalogTimeSeries keys
    std::vector<int> columns;      // which columns to extract (empty = all)
};

output_key_prefix uses a standard QLineEdit. columns uses a CSV QLineEdit (e.g. "0, 1, 2") via the std::vector<int> widget support. An empty list means “extract all columns”.

Algorithm (implemented):

  1. For each selected column, extract data via TensorData::getColumn(i).
  2. When the tensor has RowType::TimeFrameIndex, recover time indices via RowDescriptor::timeStoragePtr()->getAllTimeIndices() and construct the AnalogTimeSeries with those indices to preserve temporal alignment.
  3. Set the source TimeFrame on each output series.

This transform creates zero-copy TensorColumnAnalogStorage views instead of owning copies (see TensorColumnAnalogStorage below).

Registration & Tests

  • Both transforms registered via registerPipelineStepFactoryFor in RegisteredTransforms.cpp.
  • 12 Catch2 test cases (484 assertions) in src/TransformsV2/algorithms/AnalogToTensor/AnalogToTensor.test.cpp:
    • Round-trip: N AnalogTimeSeries → AnalogToTensor → TensorToAnalog → values match exactly.
    • Single channel, default column name generation.
    • Mismatched TimeFrames → nullptr (graceful failure).
    • Mismatched sample counts → nullptr (graceful failure).
    • Empty channels vector → nullptr.
    • TimeFrame and RowType::TimeFrameIndex preserved in output.
    • TensorToAnalog column selection, out-of-range index rejection.
    • Ordinal tensor extraction.

Common Average Reference (CAR) Transform

See developer docs for full API reference.

Files:

  • src/TransformsV2/algorithms/TensorCAR/TensorCAR.hpp
  • src/TransformsV2/algorithms/TensorCAR/TensorCAR.cpp

Transform type: Container (TensorData → TensorData).

Parameters struct:

struct TensorCARParams {
    CARMethod method = CARMethod::Median; // Mean or Median
    std::vector<int> exclude_channels;    // channels excluded from reference
    bool use_gpu = false;
};

Algorithm (CPU via Armadillo):

  1. auto t = tensor.toLibTorch() — convert from Armadillo storage.
  2. If use_gpu: t = DeviceManager::instance().toDevice(t) — move to GPU.
  3. Compute reference:
    • Mean: auto ref = torch::mean(t, /*dim=*/1).values
    • Median: auto ref = torch::median(t, /*dim=*/1).values
  4. Subtract: t = t - ref.unsqueeze(1).
  5. Return TensorData wrapping the result LibTorchTensorStorage.

The same code runs on CPU and GPU — the only difference is the device placement in step 2. See Section 3 for rationale.

Pattern reference: TensorPCA (container transform, TensorData → TensorData).

Zero-Copy TensorData Column Views

TensorToAnalog produces zero-copy AnalogTimeSeries views backed by TensorColumnAnalogStorage. This eliminates the data copy by creating an AnalogTimeSeries storage backend that directly references a TensorData column.

TensorColumnAnalogStorage Backend

New file: src/DataObjects/AnalogTimeSeries/storage/TensorColumnAnalogStorage.hpp

Members:

std::shared_ptr<TensorData const> _tensor; // shared ownership of source
std::size_t _column_index;

Key insight: Armadillo uses column-major layout. Each column of an arma::fmat is contiguous in memory. This means fmat.colptr(col_index) gives a float* to a contiguous block of num_rows floats — exactly what AnalogTimeSeries needs for span-based access.

CRTP implementation:

CRTP method implementations for TensorColumnAnalogStorage
Method Implementation
getValueAtImpl(i) _tensor->at({i, _column_index})
sizeImpl() _tensor->numRows()
isContiguousImpl() true if Armadillo backend (column-major)
tryGetCacheImpl() Return {colptr, num_rows, true} if Armadillo
getSpanRangeImpl(s, e) Return span{colptr + s, e - s} if Armadillo

Factory Method

Added a general-purpose createFromStorage factory to AnalogTimeSeries that accepts a pre-constructed AnalogDataStorageWrapper and TimeIndexStorage. This avoids adding a TensorData dependency to the AnalogTimeSeries library:

static std::shared_ptr<AnalogTimeSeries> createFromStorage(
    AnalogDataStorageWrapper storage,
    std::shared_ptr<TimeIndexStorage> time_storage);

The caller (e.g. TensorToAnalog.cpp) constructs the TensorColumnAnalogStorage, wraps it in an AnalogDataStorageWrapper, and passes it to this factory. This keeps the dependency on TensorData in the transform layer, not in the data object layer.

TensorToAnalog Integration

TensorToAnalog now copies the input TensorData into a shared_ptr (so views are self-contained), resolves time storage once, and creates a TensorColumnAnalogStorage for each selected column. Result: applying CAR → TensorToAnalog produces views that share the filtered TensorData memory with zero per-element copies.

Tests

17 Catch2 test cases in TensorColumnAnalogStorage.test.cpp:

  • Zero-copy verification: Pointer comparison confirms AnalogTimeSeries view shares memory with the source TensorData column.
  • Span access: getDataInTimeFrameIndexRange returns non-empty spans; full and range-based span access verified.
  • Element access: All elements match column * 1000 + row test pattern.
  • Edge cases: Single column, single row, span boundary conditions.
  • Round-trip: AnalogToTensor → TensorToAnalog produces zero-copy views matching the original data.
  • TimeFrame preservation: Output series carry the correct TimeFrame.

DataViewer Integration

DataViewer_Widget is the primary consumer of multi-channel AnalogTimeSeries data. It groups channels by naming convention (e.g. voltage_1, voltage_2, … under a voltage group) and plots them as stacked 1D temporal traces.

A critical design goal is that DataViewer_Widget does not need to change. The storage abstraction handles multi-channel efficiency transparently.

In-memory path

The loading path creates one TensorData (Armadillo) and \(N\) TensorColumnAnalogStorage-backed AnalogTimeSeries objects. Each one has a contiguous column span. When DataViewer calls getDataInTimeFrameIndexRange(), it receives a real std::span<float const> pointing into the Armadillo matrix column. This is exactly as fast as the VectorAnalogDataStorage path. DataViewer sees no difference.

See Also