Repository navigation
Expand file tree
/
Copy pathinspectNwbFile.m
More file actions
247 lines (226 loc) · 9.48 KB
/
Copy pathinspectNwbFile.m
File metadata and controls
247 lines (226 loc) · 9.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
function result = inspectNwbFile(nwbFilepath, options)
% INSPECTNWBFILE - Run nwbinspector on the specified NWB file
%
% Syntax:
% report = INSPECTNWBFILE(nwbFilepath) runs nwbinspector on the NWB file at
% nwbFilepath and returns a tabular report listing potential issues.
%
% report = INSPECTNWBFILE(nwbFilepath, Name, Value) runs nwbinspector using
% optional name-value pairs for customizing the report.
%
% Input Arguments:
% - nwbFilepath (string) -
% Filepath pointing to an NWB file.
%
% - options (name-value pairs) -
% Optional name-value pairs. Available options:
%
% - VariableOrder (string) -
% Which order to arrange the variables in the tabular report.
%
% Output Arguments:
% - report (table) - A tabular report listing nwbinspector issues. If PyNWB
% fails to read the file, no checks are run and an error is raised instead
% of returning a report.
%
% Usage:
% Example 1 - Inspect an NWB file::
%
% report = inspectNwbFile('my_nwb_file.nwb');
%
% Example 2 - Inspect an NWB file and specify the order to display report variables::
%
% variableOrder = ["importance", "message", "check_function_name", "object_name"];
% nwb = inspectNwbFile('my_nwb_file.nwb', ...
% 'VariableOrder', variableOrder);
%
% .. note::
% This function requires the python nwbinspector module to be
% installed and available from MATLAB. From MATLAB R2019, it is possible to
% run python modules directly from MATLAB. Ensure nwbinspector is installed
% in the python environment returned by running `pyenv` in MATLAB.
% It is also possible to run the command line (CLI) version of nwbinspector.
% If the nwbinspector executable is not on your system's path, you can add the
% executable to your MATLAB environment variables using the variable name
% "NWBINSPECTOR_EXECUTABLE", for example
% `setenv("NWBINSPECTOR_EXECUTABLE", 'path/to/python/ver/bin/nwbinspector')`
%
% .. note::
% This function is meant as a convenience method for running the nwbinspector
% as part of an MatNWB workflow, and it does not expose more advanced
% functionality of the nwbinspector.
%
% See also:
% pyenv
arguments
nwbFilepath (1,1) string {matnwb.common.mustBeNwbFile}
options.VariableOrder = [...
"importance", ...
"check_function_name", ...
"object_name", ...
"object_type", ...
"message", ...
"location", ...
"file_path", ...
"severity"];
options.UseCLI (1,1) logical = false % Flag for forcing usage of the command line interface. Useful for testing
end
hasPyNwbInspector = isPyNwbInspectorAvailable();
[hasCliNwbInspector, nwbInspectorExecutable] = isCliNwbInspectorAvailable();
if hasPyNwbInspector && ~options.UseCLI
pyResult = py.list(py.nwbinspector.inspect_nwbfile(nwbFilepath));
result = convertNwbInspectorResultsToTable(pyResult);
elseif hasCliNwbInspector
reportFilePath = [tempname, '.json'];
if isunix
systemCommand = sprintf('%s %s --levels importance --json-file-path %s', ...
nwbInspectorExecutable, nwbFilepath, reportFilePath);
elseif ispc
% Use double quotes in case there are spaces in the filepaths
systemCommand = sprintf('"%s" "%s" --levels importance --json-file-path "%s"', ...
nwbInspectorExecutable, nwbFilepath, reportFilePath);
end
[status, m] = system(systemCommand);
assert(status == 0, ...
'NWB:InspectNwbFile:UnknownError', ...
['Failed to run nwbinspector using system command. ', ...
'The following message was returned:\n%s'], m)
cleanupObj = onCleanup( @() delete(reportFilePath));
result = convertJsonReportToTable(reportFilePath);
else
error('NWB:InspectNwbFile:NwbInspectorNotFound', ...
'Did not find nwbinspector. See `help inspectNwbFile` for more details')
end
throwErrorIfFileCouldNotBeRead(result, nwbFilepath)
result = result(:, options.VariableOrder);
end
function throwErrorIfFileCouldNotBeRead(resultTable, nwbFilepath)
% throwErrorIfFileCouldNotBeRead - Raise an error if PyNWB could not read the file.
%
% nwbinspector does not raise when PyNWB fails to read a file. It returns a
% single message with importance ERROR whose check_function_name is a
% sentence starting with "During io.read()" and whose message is the Python
% traceback (see nwbinspector._nwb_inspection.inspect_nwbfile). Such a
% result means no checks ran at all, so returning it as a report would
% silently let an unreadable file "pass". nwbinspector provides no
% structured marker for this case, so the prefix is matched as text. See
% https://github.com/NeurodataWithoutBorders/nwbinspector/issues/723
READ_ERROR_PREFIX = "During io.read(), an error occurred";
isReadError = startsWith(string(resultTable.check_function_name), READ_ERROR_PREFIX);
if any(isReadError)
pythonTraceback = strjoin(string(resultTable.message(isReadError)), newline);
error('NWB:InspectNwbFile:FileReadError', ...
['nwbinspector could not inspect "%s" because PyNWB failed to read ', ...
'the file, so no checks were run. The Python traceback was:\n%s'], ...
nwbFilepath, pythonTraceback)
end
end
function resultTable = convertNwbInspectorResultsToTable(resultsIn)
resultTable = getEmptyNwbInspectorResultStruct();
C = cell(resultsIn);
for i = 1:numel(C)
resultTable(i).importance = string( py.getattr(C{i}.importance, 'name') );
resultTable(i).severity = string( py.getattr(C{i}.severity, 'name') );
try
resultTable(i).location = string(C{i}.location);
catch
resultTable(i).location = "N/A";
end
resultTable(i).message = pyValueToString(C{i}.message);
resultTable(i).object_name = pyValueToString(C{i}.object_name);
resultTable(i).object_type = pyValueToString(C{i}.object_type);
resultTable(i).file_path = pyValueToString(C{i}.file_path);
resultTable(i).check_function_name = pyValueToString(C{i}.check_function_name);
end
resultTable = struct2table(resultTable, 'AsArray', true);
end
function resultTable = convertJsonReportToTable(reportFilePath)
S = jsondecode(fileread(reportFilePath));
varNames = fieldnames(S.messages);
T = struct2table(S.messages, 'AsArray', true);
for i = 1:numel(varNames)
try
T.(varNames{i}) = string(T.(varNames{i}));
catch MECause
switch MECause.identifier
case 'MATLAB:string:MustBeConvertibleCellArray'
data = T.(varNames{i});
isNumericEmpty = cellfun(@(c) isnumeric(c) && isempty(c), data);
if any(isNumericEmpty)
data(isNumericEmpty) = {""};
T.(varNames{i}) = string(data);
end
otherwise
ME = MException(...
'NWB:InspectNwbFile:ResultConversionFailed', ...
'Something went wrong when converting nwbinspector results to a MATLAB table.');
ME.addCause(MECause)
throw(ME)
end
end
end
resultTable = T;
end
function emptyResults = getEmptyNwbInspectorResultStruct()
emptyResults = struct(...
'importance', {}, ...
'check_function_name', {}, ...
'object_name', {}, ...
'object_type', {}, ...
'message', {}, ...
'location', {}, ...
'file_path', {}, ...
'severity', {} );
end
function isNwbInspectorInstalled = isPyNwbInspectorAvailable()
isNwbInspectorInstalled = false;
if exist("pyenv", "builtin") == 5
pythonEnv = pyenv();
if pythonEnv.Executable == ""
return
else
try
py.importlib.metadata.version("nwbinspector");
isNwbInspectorInstalled = true;
catch ME
if contains(ME.message, "PackageNotFoundError")
warning([...
'nwbinspector is not installed for MATLAB''s default ', ...
'python environment:\n%s'], pyenv().Home)
else
throwAsCaller(ME)
end
end
end
end
end
function [isNwbInspectorInstalled, nwbInspectorExecutable] = isCliNwbInspectorAvailable()
nwbInspectorExecutable = getenv("NWBINSPECTOR_EXECUTABLE");
if isempty(nwbInspectorExecutable)
% Trying with default nwbinspector binary
nwbInspectorExecutable = "nwbinspector";
end
if isunix
systemCommand = sprintf('which %s', nwbInspectorExecutable);
elseif ispc
if isfile([nwbInspectorExecutable, '.exe'])
% If the nwbexecutable exists as a file, we have the absolute
% path and don't need to check with the where command
isNwbInspectorInstalled = true;
return
else
systemCommand = sprintf('where "%s"', nwbInspectorExecutable);
end
end
assert(logical(exist('systemCommand', 'var')), ...
'Unknown platform, could not generate system command. Please report!')
[status, ~] = system(systemCommand);
isNwbInspectorInstalled = status == 0;
end
function strValue = pyValueToString(pyValue)
if isa(pyValue, 'py.NoneType')
strValue = string(missing);
else
strValue = string(pyValue);
end
end