Skip to content

feat(dynamictable): add addRaggedArray for ragged and doubly ragged columns - #855

Open
ehennestad wants to merge 39 commits into
mainfrom
add-ragged-array-methods
Open

ehennestad wants to merge 39 commits into
mainfrom
add-ragged-array-methods

Conversation

@ehennestad

@ehennestad ehennestad commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Adds DynamicTable.addRaggedArray, which builds a ragged or doubly ragged column and its index columns in one call, replacing manual assembly of the VectorData and VectorIndex objects.

Background — #892, now merged, fixed util.create_indexed_column for column vectors and array rows; this PR builds on that helper. It implements the ragged-column half of #809 (the method is named addRaggedArray after the specification's section title); the enum-column half of #809 is not in scope.

Problem — NWB tables store a variable number of items per row as ragged arrays: a VectorData plus a VectorIndex of cumulative offsets. Units.waveforms is doubly ragged, with a second VectorIndex over the first, and PlaneSegmentation.pixel_mask is a ragged column of compound elements (x, y, weight). MatNWB had no method that builds any of these. A ragged column took util.create_indexed_column followed by addColumn. That helper takes numeric, string, character, struct and object-reference vectors, one per row, but not rows given as cell arrays of character vectors or tables, nor flat data with a count per row, and it reads a character vector as a list of characters. Columns in those forms, and doubly ragged columns, had to be assembled by hand: the VectorData, one VectorIndex per level with ObjectView targets, and the cumulative counts computed by the user. addColumn then rejected a doubly ragged column, because its height check only followed one index level, and it failed on a table that had ids but no columns yet.

Solution — One DynamicTable method, addRaggedArray(name, data), builds and wires the column in a single call. Depth sets the number of index levels; addDoublyRaggedArray is a shorthand for Depth 2. Rows can be numeric, text, compound or object references, given as one cell per row or as data that is already flat plus ElementsPerRow. For Depth 2, ElementsPerSubGroup states the number of elements in each sub-group when it should not be read from the dimensions of the rows. Every numeric array uses the orientation of VectorData.data, with the ragged axes last, so what you pass for a row or a spike event is the slice of data that will hold it. The pynwb round-trip tests compare the resulting Units table with one built by Units.add_unit.

What changed

  • DynamicTable.addRaggedArray(name, data, ...) on every table type: builds the VectorData (or a DynamicTableRegion with the table argument) and one VectorIndex per level, adds them with addColumn, and lists only the data column in colnames. Depth 1 (default) gives <name> and <name>_index; Depth 2 adds <name>_index_index.
  • DynamicTable.addDoublyRaggedArray(name, data): the same as addRaggedArray with Depth 2.
  • util.create_indexed_column takes Depth and returns the data vector followed by one VectorIndex per level, innermost first. Existing two-output calls are unchanged.
  • Element kinds: numeric; text (a string array, a cell array of character vectors or a character vector per row); compound (a table, a struct array or a scalar struct of columns per row), written as a compound dataset; or object references (a vector of types.untyped.ObjectView objects per row, with [] for a row that references nothing), as when a trials table links each trial to the TimeSeries recorded during it. A column holds elements of one kind and keeps the class of its rows where it can: string rows give a string column, struct-array rows a struct column and object rows a column of their class, as util.create_indexed_column does on main; other text gives a column cell array of character vectors, and other compound rows a table. A numeric field of compound rows that are stored as a table must have the same class in every row, as numeric rows must; otherwise NWB:CreateIndexedColumn:InconsistentElementType is raised.
  • A character vector row is one text element. On main, util.create_indexed_column reads a character vector row as a list of characters, one element per character; this is the one change for inputs that main accepts.
  • ElementsPerRow: data that is already flat (the elements of all rows in row order) plus the number of elements in each row builds a column of depth 1 without one array per row, for example pixel masks as one table of all pixels plus the pixel count of each ROI. An empty ElementsPerRow is a table with no rows.
  • A DataPipe or DataStub given as a row or as flat data, and a SoftLink given as a row, raise NWB:CreateIndexedColumn:InvalidRow or NWB:CreateIndexedColumn:InvalidData with a message that names the row and says what to use instead. The column is built in memory, so a pipe or stub would otherwise be loaded silently, and a dataset cannot hold links.
  • Input forms for Depth 2, per row: a nested cell with one [num_samples x num_electrodes] matrix per spike event; one [num_samples x num_electrodes x num_spike_events] array; or one [num_samples x num_waveforms] matrix for a single electrode. The 3-D form is pynwb's (num_spikes, num_electrodes, num_samples) array with the dimensions reversed, as for any other MatNWB dataset. A [num_samples x 0 x num_spike_events] array is that many spike events with no waveforms.
  • MATLAB drops a trailing dimension of 1, so a [k x m] matrix fits both numeric forms for Depth 2. A column is read one way as a whole: if any row is 3-D, every row is read in the 3-D form, and a single-electrode unit is then given as [num_samples x 1 x num_spikes]. The docstring and the how-to page state this.
  • ElementsPerSubGroup, for Depth 2: the number of elements in each sub-group of the numeric rows, as one value or one value per row, on addRaggedArray, addDoublyRaggedArray and util.create_indexed_column. A numeric row is then [elementDims x nElements], with the elements of the first sub-group first and nElements a multiple of the row's value, or [elementDims x value x nSubGroups]. A [k x m] matrix is read the same way whatever the other rows are, and no dimension of 1 is needed. For Units.waveforms the value is the number of electrodes of each unit. A row given as a nested cell states its sub-groups itself and is not compared with the value. Without the argument, rows are read as the previous item describes.
  • addColumn accepts a column with a chain of VectorIndex columns: its height check follows the chain to the outermost index. A chain that returns to a column it already visited raises NWB:DynamicTable:CheckConfig:InfiniteReferenceLoop. On a table that has ids but no columns yet, it takes the table height from the ids and checks every new column against it; before, adding a ragged column to such a table failed and a plain column of any height was accepted.
  • UnitsTableIOTest (renamed from UnitTimesIOTest) builds a multi-electrode Units table in MatNWB and in pynwb (add_unit), in both directions, once with the nested form and once with the 3-D form.
  • A how-to page, Storing Ragged and Doubly-Ragged Array Columns, whose snippets live in a runnable example file that a unit test executes, and an nwb-format-description extlink for the schema's format description page.
Implementation notes

create_indexed_column flattens the nested input with one recursive walk. A scan of the whole column first decides its layout: the element kind, the element shape (the largest number of element dimensions any row shows, with shorter rows padded with ones), and whether the [k x nSubGroups] shortcut applies. A numeric row at depth n is split into element dimensions and n trailing ragged dimensions; merging the trailing dimensions with reshape lists the entries of the first sub-group first, which is the order the index levels describe, so no permutation is needed. Compound rows are held as scalar structs of columns, joined field by field, and turned into one table at the end. The layout also records whether every text row is a string array and every compound row a struct array, which decides the class of the stored column, and the class of the object rows, which must be one class. The scan rejects DataPipe, DataStub and SoftLink items before the kind is decided. With ElementsPerSubGroup the shortcut is not used: a row that lists all its elements along one dimension is divided into sub-groups of the stated size, and a row in the full form is checked against it. addVarargColumn.getIndexInSet loops over getIndex until no further index targets the column.

Examples

A doubly ragged Units.waveforms column

Two units recorded on one electrode. Each unit's waveforms are one matrix with the 4 samples down the rows and one column per spike: 3 spikes for unit 1, 4 for unit 2. The values are chosen so that each waveform can be recognised in the output.

unit1 = reshape(1:12, 4, 3);          % [num_samples x num_spikes]
unit2 = 100 + reshape(1:16, 4, 4);
units = types.core.Units('colnames', {}, 'description', 'units');

Before — the user builds the VectorData from the concatenated waveforms, works out the cumulative offsets by hand (1 to 7 for one waveform per spike; 3 and 7 for the spikes per unit), creates two VectorIndex objects with ObjectView targets, and hands all three to addColumn:

wf = types.hdmf_common.VectorData('description', 'spike waveforms', 'data', [unit1, unit2]);
wfIndex = types.hdmf_common.VectorIndex('description', 'indexes data', ...
    'target', types.untyped.ObjectView(wf), 'data', uint64((1:7)'));
wfIndexIndex = types.hdmf_common.VectorIndex('description', 'indexes data', ...
    'target', types.untyped.ObjectView(wfIndex), 'data', uint64([3; 7]));
units.addColumn('waveforms', wf, 'waveforms_index', wfIndex, 'waveforms_index_index', wfIndexIndex)

addColumn looks up one index level for waveforms, finds waveforms_index and takes its 7 entries as the table height. It then checks waveforms_index against its own index, waveforms_index_index, whose 2 entries do not match, and rejects the column:

Error: Column `waveforms_index` has detected height 2, but the table height is 7.

The only way through was to assign the three properties and colnames on the table directly.

After — one call, with Depth 2 asking for two index levels. The offsets are computed from the input:

units.addRaggedArray('waveforms', {unit1, unit2}, 'description', 'spike waveforms', 'Depth', 2);
fprintf('colnames: %s\n', strjoin(units.colnames, ', '));
fprintf('waveforms.data size: %s\n', strjoin(string(size(units.waveforms.data)), 'x'));
fprintf('waveforms_index: %s\n', mat2str(units.waveforms_index.data.'));
fprintf('waveforms_index_index: %s\n', mat2str(units.waveforms_index_index.data.'));
colnames: waveforms
waveforms.data size: 4x7
waveforms_index: [1 2 3 4 5 6 7]
waveforms_index_index: [3 7]

Reading the output: only waveforms is listed in colnames, because the index columns are companions rather than user-facing columns. The data is 4 samples by 7 waveforms, [unit1, unit2] side by side. waveforms_index climbs by one because every spike has a single waveform. waveforms_index_index is 3 and then 7: unit 1 owns spikes 1 to 3, unit 2 owns spikes 4 to 7.

Several electrodes per spike event

Two units recorded on 3 electrodes, so every spike event has 3 waveforms: 2 spike events for unit 1 and 3 for unit 2, 15 waveforms in total.

Before — no equivalent. The 15 waveforms have to be interleaved by hand in the order the index describes (the 3 electrodes of spike event 1, then the 3 of spike event 2, and so on), and both index levels have to be computed and wired as in the previous example.

After — one [num_samples x num_electrodes x num_spike_events] array per unit. This is pynwb's (num_spikes, num_electrodes, num_samples) input with the dimensions reversed, the same rule that maps any pynwb array to MatNWB:

a1 = rand(4, 3, 2);   % 2 spike events on 3 electrodes
a2 = rand(4, 3, 3);   % 3 spike events
units = types.core.Units('colnames', {}, 'description', 'units');
units.addRaggedArray('waveforms', {a1, a2}, 'Depth', 2);
fprintf('waveforms.data size: %s\n', strjoin(string(size(units.waveforms.data)), 'x'));
fprintf('waveforms_index: %s\n', mat2str(units.waveforms_index.data.'));
fprintf('waveforms_index_index: %s\n', mat2str(units.waveforms_index_index.data.'));
waveforms.data size: 4x15
waveforms_index: [3 6 9 12 15]
waveforms_index_index: [2 5]

Reading the output: the data is 4 samples by 15 waveforms, 5 spike events times 3 electrodes. waveforms_index climbs by 3 because each spike event owns one waveform per electrode. waveforms_index_index is 2 and then 5: unit 1 owns spike events 1 and 2, unit 2 owns 3 to 5.

Units with different electrode counts

Three units: 2 spike events on 3 electrodes, 4 spike events on 1 electrode, and 1 spike event on 3 electrodes. Each unit is one [num_samples x num_waveforms] matrix, with the waveforms of the first spike event first.

unit1 = rand(4, 6);   % 2 spike events x 3 electrodes
unit2 = rand(4, 4);   % 4 spike events x 1 electrode
unit3 = rand(4, 3);   % 1 spike event x 3 electrodes

Read from the dimensions — without ElementsPerSubGroup, the number of waveforms per spike event comes from the dimensions of the rows. Every row here is a matrix, so each is read in the single-electrode form, with one waveform per spike event:

units = types.core.Units('colnames', {}, 'description', 'units');
units.addRaggedArray('waveforms', {unit1, unit2, unit3}, 'Depth', 2);
fprintf('waveforms_index: %s\n', mat2str(units.waveforms_index.data.'));
fprintf('waveforms_index_index: %s\n', mat2str(units.waveforms_index_index.data.'));
waveforms_index: [1 2 3 4 5 6 7 8 9 10 11 12 13]
waveforms_index_index: [6 10 13]

To get the intended column this way, unit 1 has to be reshaped to [4 x 3 x 2] and unit 2 to [4 x 1 x 4].

With ElementsPerSubGroup — the number of electrodes of each unit is stated, and the matrices are passed as they are:

units = types.core.Units('colnames', {}, 'description', 'units');
units.addRaggedArray('waveforms', {unit1, unit2, unit3}, 'Depth', 2, 'ElementsPerSubGroup', [3 1 3]);
fprintf('waveforms.data size: %s\n', strjoin(string(size(units.waveforms.data)), 'x'));
fprintf('waveforms_index: %s\n', mat2str(units.waveforms_index.data.'));
fprintf('waveforms_index_index: %s\n', mat2str(units.waveforms_index_index.data.'));
waveforms.data size: 4x13
waveforms_index: [3 6 7 8 9 10 13]
waveforms_index_index: [2 6 7]

Reading the output: waveforms_index climbs by 3 for the two spike events of unit 1, by 1 for the four spike events of unit 2, and by 3 for the spike event of unit 3. waveforms_index_index is 2, 6 and 7: unit 1 owns spike events 1 and 2, unit 2 owns 3 to 6, unit 3 owns 7.

A ragged column

Spike times for two units, 3 and 2 values.

Before — two steps, with the index column name spelled by hand:

[vector, index] = util.create_indexed_column({[0.1 0.2 0.3], [0.5 0.6]});
units.addColumn('spike_times', vector, 'spike_times_index', index);

After — one call; the index column is named and added for you:

units.addRaggedArray('spike_times', {[0.1 0.2 0.3], [0.5 0.6]});
fprintf('spike_times_index: %s\n', mat2str(units.spike_times_index.data.'));
spike_times_index: [3 5]

The index marks that unit 1 owns values 1 to 3 and unit 2 owns values 4 and 5. The stored column is the same in both cases.

A text column

A table whose rows hold 3 and 1 text tags.

t = types.hdmf_common.DynamicTable('description', 'table');

Before — the helper does not take rows given as cell arrays of character vectors, so a text column like this was built by hand, with the row ends worked out by the user:

col = types.hdmf_common.VectorData('description', 'tags', 'data', {'1a'; '1b'; '1c'; '2a'});
colIndex = types.hdmf_common.VectorIndex('description', 'indexes data', ...
    'target', types.untyped.ObjectView(col), 'data', uint64([3; 4]));
t.addColumn('tags', col, 'tags_index', colIndex);
fprintf('tags: %s\n', strjoin(t.vectordata.get('tags').data, ', '));
fprintf('tags_index: %s\n', mat2str(double(t.vectordata.get('tags_index').data.')));
tags: 1a, 1b, 1c, 2a
tags_index: [3 4]

After — one cell per row, each holding that row's tags. The same two datasets are built:

t.addRaggedArray('tags', {{'1a'; '1b'; '1c'}, {'2a'}}, 'description', 'tags');
fprintf('tags: %s\n', strjoin(t.vectordata.get('tags').data, ', '));
fprintf('tags_index: %s\n', mat2str(double(t.vectordata.get('tags_index').data.')));
tags: 1a, 1b, 1c, 2a
tags_index: [3 4]

Reading the output: the data holds all four tags in row order, and the index says that row 1 ends after tag 3 and row 2 after tag 4.

Pixel masks from flat data

Two ROIs with 3 and 2 pixels. As in the ophys tutorial, the pixels of all ROIs are one struct of columns, and the pixel count of each ROI is known.

pixels = struct('x', uint32([1;2;3;7;8]), 'y', uint32([4;4;4;9;9]), 'weight', single(ones(5,1)));
numPixelsPerRoi = [3; 2];

Before — the user converts the pixels to a table, turns the counts into cumulative offsets with cumsum, creates the VectorIndex with an ObjectView target, and passes both to the constructor:

mask = types.hdmf_common.VectorData('description', 'pixel masks', 'data', struct2table(pixels));
maskIndex = types.hdmf_common.VectorIndex('description', 'Index into pixel_mask VectorData', ...
    'target', types.untyped.ObjectView(mask), 'data', uint64(cumsum(numPixelsPerRoi)));
ps = types.core.PlaneSegmentation('colnames', {'pixel_mask'}, 'description', 'rois', ...
    'pixel_mask', mask, 'pixel_mask_index', maskIndex);
fprintf('pixel_mask rows: %d\n', height(ps.pixel_mask.data));
fprintf('pixel_mask_index: %s\n', mat2str(double(ps.pixel_mask_index.data.')));
pixel_mask rows: 5
pixel_mask_index: [3 5]

After — the flat pixels and the counts go straight into one call. ElementsPerRow gives the number of pixels in each ROI, so no per-ROI table and no offsets are needed:

ps = types.core.PlaneSegmentation('description', 'rois');
ps.addRaggedArray('pixel_mask', pixels, 'ElementsPerRow', numPixelsPerRoi, 'description', 'pixel masks');
fprintf('colnames: %s\n', strjoin(ps.colnames, ', '));
fprintf('pixel_mask rows: %d\n', height(ps.pixel_mask.data));
fprintf('pixel_mask_index: %s\n', mat2str(double(ps.pixel_mask_index.data.')));
colnames: pixel_mask
pixel_mask rows: 5
pixel_mask_index: [3 5]

Reading the output: pixel_mask holds all 5 pixels as one compound table, stored on the PlaneSegmentation property, and the index says that ROI 1 ends after pixel 3 and ROI 2 after pixel 5.

A table whose ids come first

The icephys tables are constructed with their ids and get their ragged reference column afterwards. Here a table has ids 19 and 21 and no columns yet.

t = types.hdmf_common.DynamicTable('description', 'ids only', ...
    'id', types.hdmf_common.ElementIdentifiers('data', int64([19; 21])));

Before — addColumn set the table height only when the table already had columns, or had neither columns nor ids. With ids but no columns, the height check on the index column read an undefined variable:

[v, i] = util.create_indexed_column({0, [0 1]});
t.addColumn('refs', v, 'refs_index', i);
Error: Unrecognized function or variable 'tableHeight'.

After — the ids set the table height, and the column is checked against it and added:

t.addRaggedArray('refs', {0, [0 1]});
fprintf('refs_index: %s\n', mat2str(double(t.vectordata.get('refs_index').data.')));
refs_index: [1 3]

Reading the output: row 1 references one row and row 2 references two, so the index ends at 1 and 3. A plain column whose height does not match the ids is now rejected as well.

How to test

unit1 = rand(4, 3, 2);
unit2 = rand(4, 3, 3);
units = types.core.Units('colnames', {}, 'description', 'units');
units.addRaggedArray('waveforms', {unit1, unit2}, 'Depth', 2);
assert(isequal(units.waveforms.data(:, 4:6), unit1(:, :, 2)))
assert(isequal(units.waveforms_index.data, uint64([3; 6; 9; 12; 15])))
assert(isequal(units.waveforms_index_index.data, uint64([2; 5])))

pixels = struct('x', uint32([1;2;3;7;8]), 'y', uint32([4;4;4;9;9]), 'weight', single(ones(5,1)));
ps = types.core.PlaneSegmentation('description', 'rois');
ps.addRaggedArray('pixel_mask', pixels, 'ElementsPerRow', [3 2]);
assert(isequal(ps.pixel_mask_index.data, uint64([3; 5])))

units = types.core.Units('colnames', {}, 'description', 'units');
units.addRaggedArray('waveforms', {rand(4, 6), rand(4, 4)}, 'Depth', 2, 'ElementsPerSubGroup', [3 1]);
assert(isequal(units.waveforms_index.data, uint64([3; 6; 7; 8; 9; 10])))
assert(isequal(units.waveforms_index_index.data, uint64([2; 6])))

Or run tests.unit.dynamicTableRaggedArrayTest, tests.unit.createIndexedColumnTest, tests.unit.dynamicTableTest, tests.unit.howToRaggedArrayExamplesTest, and with pynwb installed tests.system.UnitsTableIOTest.

Checklist

  • Have you ensured the PR description clearly describes the problem and solutions?
  • Have you checked to ensure that there aren't other open or previously closed Pull Requests for the same change?
  • If this PR fixes an issue, is the first line of the PR description fix #XX where XX is the issue number?

🤖 Generated with Claude Code

@codecov

codecov Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.53%. Comparing base (9961193) to head (c0c4fe2).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #855      +/-   ##
==========================================
+ Coverage   95.45%   95.53%   +0.08%     
==========================================
  Files         240      241       +1     
  Lines        8902     9045     +143     
==========================================
+ Hits         8497     8641     +144     
+ Misses        405      404       -1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ehennestad
ehennestad requested review from bendichter and removed request for bendichter July 9, 2026 10:37
@ehennestad
ehennestad marked this pull request as draft July 9, 2026 21:05
@ehennestad
ehennestad force-pushed the add-ragged-array-methods branch from b369001 to a2b4bdb Compare September 28, 2026 10:56
@ehennestad
ehennestad force-pushed the add-ragged-array-methods branch from a2b4bdb to 04f3b04 Compare September 28, 2026 18:38
@ehennestad
ehennestad changed the base branch from main to fix-create-indexed-column-shapes September 28, 2026 18:38
@ehennestad
ehennestad added this pull request to stack #893 September 28, 2026 18:38
@ehennestad ehennestad changed the title feat(dynamictable): add ragged and doubly-ragged array column helpers feat(dynamictable): add addRaggedArray for ragged and doubly ragged columns Sep 28, 2026
@ehennestad
ehennestad marked this pull request as ready for review September 29, 2026 07:55
@ehennestad ehennestad added the category: enhancement improvements of code or code behavior label Sep 29, 2026
@ehennestad
ehennestad force-pushed the add-ragged-array-methods branch from be92e1d to 20e192e Compare September 29, 2026 19:13
@ehennestad
ehennestad force-pushed the add-ragged-array-methods branch 2 times, most recently from 7003a4a to 6da7216 Compare October 6, 2026 05:37
Base automatically changed from fix-create-indexed-column-shapes to main October 6, 2026 15:33
@ehennestad
ehennestad force-pushed the add-ragged-array-methods branch from 6da7216 to 2f076bc Compare October 6, 2026 15:33
@ehennestad ehennestad added the priority: high impacts proper operation or use of feature important to most users label Oct 6, 2026
@ehennestad ehennestad added this to the v2.12.0 milestone Oct 7, 2026
@ehennestad ehennestad mentioned this pull request Nov 12, 2026
2 of 3 tasks
ehennestad and others added 7 commits November 13, 2026 09:17
Add util.create_doubly_indexed_column plus the DynamicTable methods
addRaggedArray and addDoublyRaggedArray for building ragged and
doubly-ragged array columns (such as the Units waveforms column)
without manually wiring the VectorData and VectorIndex objects.

The methods live in matnwb.neurodata.DynamicTableBase so they are
inherited by all table types and survive generateCore. Covered by
new unit tests for both the helper and the methods.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Add a how-to guide for storing ragged and doubly-ragged array columns
with addRaggedArray / addDoublyRaggedArray, covering single-electrode and
multi-channel waveforms and the underlying util helpers.

Code snippets live in a runnable example file, embedded via literalinclude
and executed by a unit test so the documented code stays correct.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Update UnitTimesIOTest to build a Units table with multi-electrode,
doubly-ragged waveforms and compare MatNWB and PyNWB containers after a
round trip. MatNWB uses addRaggedArray / addDoublyRaggedArray; PyNWB uses
Units.add_unit. Both sides document the per-unit waveforms input order as
(num_spikes, num_electrodes, num_samples).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
UnitTimes is a legacy neurodata type name that no longer exists; the
table is the Units table. Rename the round-trip test class and file
(and the matching PyNWBIOTest.py class) accordingly.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
ehennestad and others added 19 commits November 13, 2026 09:17
Add an "array shortcut" subsection to the ragged-arrays how-to with a
tested snippet, and note that MATLAB drops a trailing singleton
dimension so one-sample waveforms need the nested form.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…lper

util.create_indexed_column takes a Depth name-value and returns the data
vector followed by one VectorIndex per level, innermost first, so a
doubly ragged column is Depth 2. create_doubly_indexed_column is
removed; it was never released.

Every input form uses the orientation of VectorData.data, with the
ragged axes last, as addRow and every other MatNWB dataset do. For
Units.waveforms a unit is [num_samples x num_electrodes x
num_spike_events], which is PyNWB's (spikes, electrodes, samples)
array with its dimensions reversed. The single-electrode form is
[num_samples x num_waveforms], and the nested form holds one
[num_samples x num_electrodes] matrix per spike event. Any of these
is the slice of waveforms.data that will hold it, so no permutation
happens inside the helper.

addColumn's height check now follows a chain of VectorIndex columns to
the outermost one, so addRaggedArray is the helper plus addColumn for
any depth. addDoublyRaggedArray remains as a shorthand for Depth 2;
the duplicated id, height, existing-column and storage logic it
carried is gone, and its errors are addColumn's.

Tests, the ragged-arrays how-to and UnitsTableIOTest use the new
orientation. In UnitsTableIOTest the array form is now a plain
reshape of the values PyNWB uses, with no permute.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
… create_indexed_column

An empty numeric row such as [k x 0 x n] declares n sub-groups with no
elements; it was read as a row with no sub-groups. The description is
stored as char whatever its input type. Errors raised while finding the
element shape name the offending row, as the other errors do.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…lumn

MATLAB drops trailing dimensions of 1 from an array's size, so a row of
the [elementDims x nElements x nSubGroups] form with one sub-group, such
as a unit with a single spike event, arrives as [k x m]. That shape was
always read as the [k x nSubGroups] shortcut: m sub-groups of one
element, with no error, and the file round-tripped with a wrong index.
The element shape was also taken from the first array row, so a
single-element row given first made the following rows fail.

One scan of the column now sets the number of element dimensions to the
largest any item shows and pads shorter items with ones before splitting
their size. The shortcut is used only while no numeric item at level 2
or above has more dimensions than its level; once a row shows the full
form, a 2-D row is that form with its trailing 1 omitted. A cell row
does not switch the mode. Rows with fewer dimensions than their depth
are no longer an error.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…escription

The ragged-arrays how-to links to a section of the schema's format
description page through the new role instead of a hard-coded URL,
like the nwb-core-type-schema role does for the type pages.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The link to the schema's format description targets its first section,
#overview, which opens the page at the top as the previous link did.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
A [k x m] row fits both the [k x nSubGroups] shortcut and the full
[elementDims x nElements x nSubGroups] form with its trailing 1
dropped. The column is read one way: if any numeric row has more
dimensions than its depth, every row is read in the full form, so a
single-electrode unit is given as [k x 1 x nSpikes]. The docstring and
the how-to now state this, and the how-to has a tested example with
units of different electrode counts. Tests pin the per-column rule,
including that an empty 3-D row counts as a 3-D row.

An empty row with more than two dimensions declares sub-groups, so its
element shape is now checked like any other row's; only an empty
matrix is read as a row with no entries.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
addColumn took the table height from the id column only when the table
already had columns, and checked a new column's height only in that
case. On a table built with ids but no columns, adding a ragged column
failed with "Unrecognized function or variable 'tableHeight'", and a
plain column of any height was accepted. The height now comes from the
ids whenever the table has them, and every new column is checked
against it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
At the innermost level a cell array of character vectors or a string
array is a list of text elements, and a character vector is one text
element. The data is stored as a column cell array of character
vectors, which is how a text ragged column is built by hand. Text works
in the cell form at any depth. A column that mixes text and numeric
rows raises NWB:CreateIndexedColumn:InconsistentElementType.

Tests cover the text forms, an empty row in a text column, text at
depth 2, the mixed-column error, a text column written and read back,
and addRaggedArray on a table that has ids but no columns.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
At the innermost level a table is a list of compound elements, one per
table row, and so is a struct array (one element per struct) or a
scalar struct whose fields are equal-length columns. The rows are
joined field by field and stored as one table, which is written as a
compound dataset such as PlaneSegmentation.pixel_mask. A column holds
elements of one kind: numeric, text or compound.

ElementsPerRow builds a column of depth 1 from data that is already
flat: the elements of all rows in row order, numeric, text or
compound, plus the number of elements in each row. Pixel masks can
then be added as one table of all pixels and the pixel count of each
ROI, without one table per ROI. addRaggedArray forwards the option.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
A text column is a string column when every text row is a string
array, and a cellstr column otherwise. A compound column is a struct
column when every compound row is a struct array with one value per
field, and a table otherwise. Flat data given with ElementsPerRow keeps
its class the same way. String arrays and struct arrays therefore give
the same column as util.create_indexed_column on main.

A character vector row is one text element. On main a character vector
row was a list of characters, one element per character, which is
rarely what a text column needs; this is the one change for inputs that
main accepted.

Text rows and struct-array rows must be vectors, as in the base branch.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Add how-to sections for text and compound ragged columns and for flat
data with ElementsPerRow, each with a tested snippet. Correct the addRow
note: addRow cannot start a ragged column but can append to one, with
scalar rows as column vectors and doubly ragged rows in the cell form.

State in the create_indexed_column help that TABLE is the DynamicTable
object itself, which the function wraps in an ObjectView.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
addRow builds a ragged or doubly ragged column row by row when the
column is listed in colnames. An extra cell around a doubly ragged row
adds an index level, so the note now says to leave it out.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Object references are a fourth element kind beside numeric, text and
compound: a row is a vector of objects such as types.untyped.ObjectView,
with [] for a row that references nothing, and the column keeps the
class. Flat data with ElementsPerRow takes the same vectors. This is how
a trials table links each trial to the TimeSeries recorded during it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…olumn

The column is built in memory, so a DataPipe or DataStub given as a row
or as flat data was silently loaded and lost its chunking or lazy read.
A SoftLink was accepted as an object element although a dataset cannot
hold links. Each now raises an error that names the row and says what
to use instead.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…_column

Rows of different numeric classes were concatenated, and the values of
one class were converted to the other: {int32([1 2]), 3.5} gave
int32([1; 2; 4]). The layout scan now records the class of the numeric
rows at every level, so mixed classes raise InconsistentElementType, as
they do on fix-create-indexed-column-shapes, and rows of one integer
class keep that class.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
addColumn follows the chain of VectorIndex columns above a new column
to find the outermost index, whose length is the table height. The
walk had no end for a chain that returns to a column it already
visited, such as a VectorIndex whose target is itself, so addColumn
did not return.

getIndexInSet now resolves the outermost index with
types.util.dynamictable.internal.getOutermostIndexColumnName, which
raises NWB:DynamicTable:CheckConfig:InfiniteReferenceLoop for such a
chain.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The test builds the waveforms column with addRaggedArray and Depth 2,
not with addDoublyRaggedArray.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@ehennestad
ehennestad force-pushed the add-ragged-array-methods branch from abb177b to 0ae6b7f Compare November 13, 2026 08:17
ehennestad and others added 10 commits November 13, 2026 14:38
create_indexed_column joined each field of compound rows with vertcat,
which converts values when rows give the field in different numeric
classes: a uint8 field given 300.7 stored 255. A numeric field must now
have one class across the rows of a column that is stored as a table,
as numeric rows already must.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
An empty ElementsPerRow was read as "not given", so flat data for a
table with no rows raised an error asking for ElementsPerRow.
create_indexed_column and addRaggedArray now decide the form of the
data by whether the argument was given.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The element shape was taken from the first non-empty row only. In a
column where no row holds an element, a [k x 0 x n] row was therefore
counted as zero sub-groups instead of n empty ones. Such a row now
supplies the element shape when no row holds an element.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
At Depth 2 the number of elements per sub-group of a numeric row is
read from its dimensions, and a [k x m] matrix is read as m sub-groups
of one element or as one sub-group of m elements depending on whether
another row is 3-D.

ElementsPerSubGroup states that number, as one value or one value per
row, on create_indexed_column, addRaggedArray and addDoublyRaggedArray.
A numeric row is then [elementDims x nElements] with nElements a
multiple of the row's value, or [elementDims x value x nSubGroups].
Without the argument the rows are read as before.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Inside a nested cell at Depth 2 a column vector is one element and a
row vector is a list of scalars, unlike at Depth 1; the how-to page now
says to give a sub-group of scalars as a row vector. The docstring of
create_indexed_column states that '' is a row with no elements, and a
test pins that reading next to "" and {''}, which are one empty text
element.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Both walks over the rows built the text that names an item, such as
DATA{3}{2}, with sprintf for every item, although only error messages
read it. For a nested cell of 200000 spike events that was about half
of the run time. The walks now pass the position as numbers, and
formatLabel turns it into text where an error is raised. The messages
are unchanged. The nested form of that input takes about 0.8 s instead
of 1.8 s in R2025b.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The "Data orientation" section now states the rule for ragged columns
and the waveforms shape, and links to the concept page that explains
why MatNWB reverses the schema's dimensions.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Several snippets used variables that the example file defined outside
the snippet markers, such as electrodesTable and the waveform arrays, so
the code shown on the page did not run. Each snippet now defines its own
data, the electrodes table is created in a snippet of its own, and the
snippets follow the order of the page.

A second test writes only the code between the markers to a function
file and runs it, so a snippet that relies on code outside the snippets
fails with an undefined variable.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
At Depth 1 an empty array with more than two dimensions, such as
zeros(4, 3, 0), raised the number of element dimensions of the whole
column, so {rand(4, 2), rand(4, 3), zeros(4, 3, 0)} failed with
InconsistentElementShape and the message named the second row. main
accepts this input. An innermost item without elements now declares no
element shape and is not compared with it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The data of a column with one element is [elementDims x 1]. An array in
memory is written without that last dimension, so one 40-sample
waveform in a whole column becomes a dataset of shape (40,), and the
row reads back as one sample in MatNWB and in pynwb.

create_indexed_column now raises
NWB:CreateIndexedColumn:SingleElementColumn for a numeric column whose
only element has more than one value. The message names the way to
store such a column: a VectorData whose data is a DataPipe that states
every dimension, which writes a (1, 40) dataset.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

category: enhancement improvements of code or code behavior priority: high impacts proper operation or use of feature important to most users

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant