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.
AnalogTimeSeriesobjects become lightweight column views. - LibTorch is the compute backend for cross-channel transforms. Armadillo remains the default storage backend for
TensorDataand provides zero-copy column access forAnalogTimeSeriesviews. - 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.
| 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 movementThis 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:
| 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.
| 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.hppsrc/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_prefixis adynamic_combofield populated with unique prefixes discovered fromAnalogTimeSerieskeys in DataManager (e.g."voltage","emg").- When a prefix is selected,
channel_keys(adynamic_combostd::vector<std::string>field) is populated with all matching keys and rendered as a multi-selectQListWidgetwith 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).
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):
- Validate all channels are non-null, share the same
TimeFrame(pointer identity), and have identical sample counts. - Build flat row-major data by iterating each channel via
viewValues()(mmap-safe; avoids the empty-span problem). - Return
TensorData::createTimeSeries2D(...)preserving the sharedTimeFrameandTimeIndexStorage. Column names come fromchannel_keyswhen sizes match, otherwise auto-generated as"ch0","ch1", etc.
TensorToAnalog Container Transform
Files:
src/TransformsV2/algorithms/TensorToAnalog/TensorToAnalog.hppsrc/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):
- For each selected column, extract data via
TensorData::getColumn(i). - When the tensor has
RowType::TimeFrameIndex, recover time indices viaRowDescriptor::timeStoragePtr()->getAllTimeIndices()and construct theAnalogTimeSerieswith those indices to preserve temporal alignment. - Set the source
TimeFrameon each output series.
This transform creates zero-copy TensorColumnAnalogStorage views instead of owning copies (see TensorColumnAnalogStorage below).
Registration & Tests
- Both transforms registered via
registerPipelineStepFactoryForinRegisteredTransforms.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. TimeFrameandRowType::TimeFrameIndexpreserved in output.TensorToAnalogcolumn selection, out-of-range index rejection.- Ordinal tensor extraction.
- Round-trip: N
Common Average Reference (CAR) Transform
See developer docs for full API reference.
Files:
src/TransformsV2/algorithms/TensorCAR/TensorCAR.hppsrc/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):
auto t = tensor.toLibTorch()— convert from Armadillo storage.- If
use_gpu:t = DeviceManager::instance().toDevice(t)— move to GPU. - Compute reference:
- Mean:
auto ref = torch::mean(t, /*dim=*/1).values - Median:
auto ref = torch::median(t, /*dim=*/1).values
- Mean:
- Subtract:
t = t - ref.unsqueeze(1). - Return
TensorDatawrapping the resultLibTorchTensorStorage.
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:
| 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
AnalogTimeSeriesview shares memory with the sourceTensorDatacolumn. - Span access:
getDataInTimeFrameIndexRangereturns non-empty spans; full and range-based span access verified. - Element access: All elements match
column * 1000 + rowtest pattern. - Edge cases: Single column, single row, span boundary conditions.
- Round-trip:
AnalogToTensor→TensorToAnalogproduces 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
- AnalogToTensor / TensorToAnalog developer docs
- TensorCAR developer docs
- TensorColumnAnalogStorage developer docs
- Multi-Channel Roadmap — planned future work (tensor-backed binary loading, shared block-cached mmap, spatial whitening, per-channel IIR filter, GPU acceleration)