Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
211 changes: 211 additions & 0 deletions +tests/+unit/createIndexedColumnTest.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
classdef createIndexedColumnTest < tests.abstract.NwbTestCase
% createIndexedColumnTest - Unit tests for util.create_indexed_column

methods (TestClassSetup)
function setupClass(testCase)
testCase.applyFixture(matlab.unittest.fixtures.WorkingFolderFixture);
end
end

methods (Test)
function testRowVectors(testCase)
[vector, index] = util.create_indexed_column({[1 2 3], [4 5]}, 'spike times');

testCase.verifyEqual(vector.data, [1; 2; 3; 4; 5]);
testCase.verifyEqual(index.data, uint64([3; 5]));
testCase.verifyEqual(vector.description, 'spike times');
testCase.verifySameHandle(index.target.target, vector);
end

function testColumnVectorsMatchRowVectors(testCase)
% Orientation of a vector row does not matter: both are lists of scalars.
[fromRows, indexFromRows] = util.create_indexed_column({[1 2 3], [4 5]});
[fromColumns, indexFromColumns] = util.create_indexed_column({[1; 2; 3], [4; 5]});

testCase.verifyEqual(fromColumns.data, fromRows.data);
testCase.verifyEqual(indexFromColumns.data, indexFromRows.data);
end

function testEmptyRow(testCase)
[vector, index] = util.create_indexed_column({[1 2], [], 3});

testCase.verifyEqual(vector.data, [1; 2; 3]);
% The empty row repeats the previous cumulative count.
testCase.verifyEqual(index.data, uint64([2; 2; 3]));
end

function testMatrixRows(testCase)
% Elements are 4-sample vectors, one per column, as in VectorData.data.
row1 = reshape(1:8, 4, 2); % 2 elements
row2 = 100 + reshape(1:12, 4, 3); % 3 elements

[vector, index] = util.create_indexed_column({row1, row2});

testCase.verifyEqual(size(vector.data), [4, 5]);
testCase.verifyEqual(vector.data(:, 1:2), row1);
testCase.verifyEqual(vector.data(:, 3:5), row2);
testCase.verifyEqual(index.data, uint64([2; 5]));
end

function testNDRows(testCase)
% HDMF's DynamicTable.add_row stores the rows (2,3,4) and (1,3,4) of
% an indexed column as data (3,3,4) with index [2 3] (hdmf 6.2.0).
% With the ragged axis last, the MatNWB rows are [4x3x2] and [4x3x1],
% and the data is [4x3x3], which is (3,3,4) on disk.
row1 = reshape(1:24, 4, 3, 2);
row2 = 100 + reshape(1:12, 4, 3); % one element; MATLAB drops the trailing 1

[vector, index] = util.create_indexed_column({row1, row2});

testCase.verifyEqual(size(vector.data), [4, 3, 3]);
testCase.verifyEqual(vector.data(:, :, 1:2), row1);
testCase.verifyEqual(vector.data(:, :, 3), row2);
testCase.verifyEqual(index.data, uint64([2; 3]));
end

function testSingleElementColumnVectorAmongMatrixRows(testCase)
row1 = reshape(1:8, 4, 2);
row2 = (101:104)'; % one 4-sample element

[vector, index] = util.create_indexed_column({row1, row2});

testCase.verifyEqual(vector.data(:, 3), row2);
testCase.verifyEqual(index.data, uint64([2; 3]));
end

function testInconsistentElementShapeErrors(testCase)
testCase.verifyError( ...
@() util.create_indexed_column({ones(4, 2), ones(5, 2)}), ...
'NWB:CreateIndexedColumn:InconsistentElementShape');
% A row vector is not one 4-sample element; that is [4 x 1].
testCase.verifyError( ...
@() util.create_indexed_column({ones(4, 2), ones(1, 4)}), ...
'NWB:CreateIndexedColumn:InconsistentElementShape');
end

function testInvalidRowTypeErrors(testCase)
testCase.verifyError( ...
@() util.create_indexed_column({[1 2], @sin}), ...
'NWB:CreateIndexedColumn:InvalidRow');
% Strings, characters and structs are accepted as vectors only.
testCase.verifyError( ...
@() util.create_indexed_column({["a" "b"; "c" "d"]}), ...
'NWB:CreateIndexedColumn:InvalidRow');
end

function testStringRowsKeepTheirClass(testCase)
[vector, index] = util.create_indexed_column({["a" "b"], "c"});

testCase.verifyEqual(vector.data, ["a"; "b"; "c"]);
testCase.verifyEqual(index.data, uint64([2; 3]));
end

function testCharRowsAreListsOfCharacters(testCase)
[vector, index] = util.create_indexed_column({'abc', 'de'});

testCase.verifyEqual(vector.data, ('abcde')');
testCase.verifyEqual(index.data, uint64([3; 5]));
end

function testStructArrayRowsKeepTheirClass(testCase)
s1 = struct('x', {uint32(1), uint32(2)}, 'weight', {single(1), single(1)});
s2 = struct('weight', single(0.5), 'x', uint32(7)); % fields in another order

[vector, index] = util.create_indexed_column({s1, s2});

testCase.verifyEqual(vector.data, [s1(:); orderfields(s2, s1)]);
testCase.verifyEqual(index.data, uint64([2; 3]));
end

function testObjectViewRowsKeepTheirClass(testCase)
% Rows of object references, with [] for a row that references
% nothing, as when linking each trial to its raw data.
seriesView = types.untyped.ObjectView(types.core.TimeSeries('description', 'raw'));
deviceView = types.untyped.ObjectView(types.core.Device());

[vector, index] = util.create_indexed_column( ...
{seriesView, [], [seriesView; deviceView]});

testCase.verifyEqual(vector.data, [seriesView; seriesView; deviceView]);
testCase.verifyEqual(index.data, uint64([1; 1; 3]));
end

function testIntegerRowsKeepTheirClass(testCase)
[vector, index] = util.create_indexed_column({int32([1 2]), int32(3)});

testCase.verifyEqual(vector.data, int32([1; 2; 3]));
testCase.verifyEqual(index.data, uint64([2; 3]));
end

function testMixedRowTypesErrors(testCase)
testCase.verifyError(@() util.create_indexed_column({[1 2], "a"}), ...
'NWB:CreateIndexedColumn:InconsistentElementType');
% Rows of different numeric classes would convert values silently
% (3.5 would become int32(4)), so they are rejected.
testCase.verifyError(@() util.create_indexed_column({int32([1 2]), 3.5}), ...
'NWB:CreateIndexedColumn:InconsistentElementType');
testCase.verifyError( ...
@() util.create_indexed_column({struct('x', 1), struct('y', 2)}), ...
'NWB:CreateIndexedColumn:InconsistentElementShape');
end

function testTableRegion(testCase)
target = types.hdmf_common.DynamicTable( ...
'description', 'target', ...
'colnames', {'x'}, ...
'x', types.hdmf_common.VectorData('description', 'x', 'data', (1:5)'), ...
'id', types.hdmf_common.ElementIdentifiers('data', (0:4)'));

[region, index] = util.create_indexed_column({[0 1], [2 3 4]}, 'regions', target);

testCase.verifyClass(region, 'types.hdmf_common.DynamicTableRegion');
% The region validator casts the row indices to an integer class.
testCase.verifyEqual(double(region.data), [0; 1; 2; 3; 4]);
testCase.verifyEqual(index.data, uint64([2; 5]));
end

function testMatrixRowsRoundTrip(testCase)
% The ragged axis is last in MATLAB, so it is first on disk as the
% schema requires, and the column survives export and read.
row1 = reshape(1:8, 4, 2);
row2 = 100 + reshape(1:12, 4, 3);
[vector, index] = util.create_indexed_column({row1, row2}, 'waveform-like');

dynamicTable = types.hdmf_common.DynamicTable('description', 'test');
dynamicTable.addColumn('wf', vector, 'wf_index', index);
testCase.verifyEqual(numel(dynamicTable.id.data), 2);

nwb = NwbFile( ...
'identifier', 'indexed_column_test', ...
'session_description', 'test', ...
'session_start_time', datetime(2024, 1, 1, 'TimeZone', 'local'));
nwb.acquisition.set('DynamicTable', dynamicTable);

fileName = testCase.getRandomFilename();
nwbExport(nwb, fileName);

testCase.verifyEqual(readOnDiskShape(fileName, '/acquisition/DynamicTable/wf'), [5, 4]);

back = nwbRead(fileName, 'ignorecache');
column = back.acquisition.get('DynamicTable').vectordata.get('wf');
columnIndex = back.acquisition.get('DynamicTable').vectordata.get('wf_index');
testCase.verifyEqual(column.data.load(), vector.data);
testCase.verifyEqual(columnIndex.data.load(), uint64([2; 5]));
end
end
end

function shape = readOnDiskShape(fileName, datasetPath)
% C-order shape of a dataset, i.e. the schema's dimension order. h5info
% reports sizes in MATLAB order, so use the low-level API.
fileId = H5F.open(fileName, 'H5F_ACC_RDONLY', 'H5P_DEFAULT');
fileCleanup = onCleanup(@() H5F.close(fileId));
datasetId = H5D.open(fileId, datasetPath);
datasetCleanup = onCleanup(@() H5D.close(datasetId));
spaceId = H5D.get_space(datasetId);
spaceCleanup = onCleanup(@() H5S.close(spaceId));
[~, shape] = H5S.get_simple_extent_dims(spaceId);
delete(spaceCleanup)
delete(datasetCleanup)
delete(fileCleanup)
end
151 changes: 138 additions & 13 deletions +util/create_indexed_column.m
Original file line number Diff line number Diff line change
@@ -1,15 +1,39 @@
function [data_vector, data_index] = create_indexed_column(data, description, table)
%CREATE_INDEXED_COLUMN creates the index and vector NWB objects for storing
%a vector column in an NWB DynamicTable
%a ragged column in an NWB DynamicTable
%
% [DATA_VECTOR, DATA_INDEX] = CREATE_INDEXED_COLUMN(DATA)
% expects DATA as a cell array where each cell is all of the data
% for a row and PATH is the path to the indexed data in the NWB file
% EXAMPLE: [data_vector, data_index] = util.create_indexed_colum({[1,2,3], [1,2,3,4]})
%
% expects DATA as a cell array with one cell per table row, holding that
% row's elements. Each cell is one of:
% - a numeric or logical vector (row or column): a list of scalar
% elements. When every row is a vector, DATA_VECTOR.data is a column
% vector holding all elements.
% - a numeric or logical array [elementDims x nElements]: nElements
% elements that each have the shape elementDims, with the ragged axis
% last, in the same orientation as the data property of any MatNWB
% VectorData. Rows are concatenated along that last dimension, so
% DATA_VECTOR.data is [elementDims x totalElements]. On disk the ragged
% axis then comes first, as the schema requires.
% - a string array, character vector, struct array or array of objects
% (such as types.untyped.ObjectView references) that is a vector: a
% list of elements of that class, one per string, character, struct or
% object. DATA_VECTOR.data keeps the class: a string column, a character
% column, a struct column or an object column.
% - [] for a row with no elements.
% All rows must hold elements of the same class (for example all int32,
% not int32 and double), and struct rows the same fields. All array rows
% must share elementDims, which is taken from the first row that is not a
% vector. A row holding a single element may be given with its trailing
% dimension of 1 omitted (a column vector [k x 1] when elements are
% k-sample vectors, a [k x m] matrix when elements are [k x m]).
% EXAMPLE: [data_vector, data_index] = util.create_indexed_column({[1,2,3], [1,2,3,4]})
% data_vector.data is [1;2;3;1;2;3;4] and data_index.data is [3;7].
% EXAMPLE: [data_vector, data_index] = util.create_indexed_column({rand(4,2), rand(4,3)})
% data_vector.data is [4 x 5] (five 4-sample elements) and data_index.data is [2;5].
%
% [DATA_VECTOR, DATA_INDEX] = CREATE_INDEXED_COLUMN(DATA, DESCRIPTION)
% adds the string DESCRIPTION in the description field of the data vector
%
%
% [DYNAMICTABLEREGION, DATA_INDEX] = CREATE_INDEXED_COLUMN(DATA, DESCRIPTION, TABLE)
% If TABLE is supplied as on ObjectView of an NWB DynamicTable, a
% DynamicTableRegion is instead output which references this table.
Expand All @@ -19,13 +43,7 @@
description = 'no description';
end

bounds = NaN(length(data), 1);
for i = 1:length(data)
bounds(i) = length(data{i});
end
bounds = uint64(cumsum(bounds));

data = cell2mat(data)';
[data, bounds] = flattenRows(data);

if exist('table', 'var')
data_vector = types.hdmf_common.DynamicTableRegion( ...
Expand All @@ -46,5 +64,112 @@
'target', ov, ...
'description', 'indexes data' ...
);
end

function [flatData, bounds] = flattenRows(rows)
% Concatenate the rows along the ragged (last) axis and count the elements
% of each row. BOUNDS is the cumulative element count, one entry per row.
numRows = numel(rows);
elementType = "";
structFields = {};
for iRow = 1:numRows
row = rows{iRow};
if isnumeric(row) || islogical(row)
% Rows of different numeric classes are not combined, as the
% values of one class would be converted to the other.
rowType = string(class(row));
elseif (isstring(row) || ischar(row) || isstruct(row) || isObjectArray(row)) ...
&& (isvector(row) || isempty(row))
rowType = string(class(row));
else
error("NWB:CreateIndexedColumn:InvalidRow", ...
"Each cell of DATA must be a numeric or logical array, or a vector of " + ...
"strings, characters, structs or objects. Cell %d is a %s of size [%s].", ...
iRow, class(row), join(string(size(row)), " "));
end
if isempty(row)
continue
end
if elementType == ""
elementType = rowType;
elseif rowType ~= elementType
error("NWB:CreateIndexedColumn:InconsistentElementType", ...
"All rows must hold elements of the same type. Cell %d holds %s " + ...
"elements, but an earlier row holds %s elements.", iRow, rowType, elementType);
end
if isstruct(row)
if isempty(structFields)
structFields = fieldnames(row);
elseif ~isequal(sort(fieldnames(row)), sort(structFields))
error("NWB:CreateIndexedColumn:InconsistentElementShape", ...
"All struct rows must have the same fields. Cell %d has fields " + ...
"{%s}, but an earlier row has {%s}.", iRow, ...
strjoin(fieldnames(row), ", "), strjoin(structFields, ", "));
end
end
end

elementDims = findElementDims(rows);
counts = zeros(numRows, 1);
chunks = cell(1, numRows);
for iRow = 1:numRows
row = rows{iRow};
if isempty(row)
counts(iRow) = 0;
chunks{iRow} = [];
elseif isempty(elementDims)
% Every row is a vector: a list of scalars, stacked into a column.
counts(iRow) = numel(row);
chunks{iRow} = row(:);
if isstruct(row)
% Concatenating structs needs the fields in the same order.
chunks{iRow} = orderfields(chunks{iRow}, structFields);
end
else
rowDims = size(row);
if isequal(rowDims, elementDims)
% A single element; MATLAB dropped the trailing dimension of 1.
counts(iRow) = 1;
elseif isequal(rowDims(1:end-1), elementDims)
counts(iRow) = rowDims(end);
else
error("NWB:CreateIndexedColumn:InconsistentElementShape", ...
"All elements must have the same shape. Expected elements of " + ...
"shape [%s], but row %d has size [%s]. Give the elements of a row " + ...
"as [elementShape x nElements], with the ragged axis last.", ...
join(string(elementDims), " "), iRow, join(string(rowDims), " "));
end
chunks{iRow} = row;
end
end
bounds = uint64(cumsum(counts));

nonEmptyChunks = chunks(counts > 0);
if isempty(nonEmptyChunks)
flatData = [];
elseif isempty(elementDims)
flatData = vertcat(nonEmptyChunks{:});
else
flatData = cat(numel(elementDims) + 1, nonEmptyChunks{:});
end
end

function elementDims = findElementDims(rows)
% The element shape, taken from the first row that is not a vector. Empty
% when every row is a vector, i.e. the elements are scalars.
elementDims = [];
for iRow = 1:numel(rows)
row = rows{iRow};
if ~isempty(row) && ~isvector(row)
rowDims = size(row);
elementDims = rowDims(1:end-1);
return
end
end
end

function tf = isObjectArray(row)
% An array of objects such as types.untyped.ObjectView references. A
% table is an object too, but its rows are not elements of one class.
tf = isobject(row) && ~istable(row);
end
Loading