Scheduled service maintenance on November 22


On Friday, November 22, 2024, between 06:00 CET and 18:00 CET, GIN services will undergo planned maintenance. Extended service interruptions should be expected. We will try to keep downtimes to a minimum, but recommend that users avoid critical tasks, large data uploads, or DOI requests during this time.

We apologize for any inconvenience.

openNEV.m 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. function varargout = openNEV(varargin)
  2. % openNEV
  3. %
  4. % Opens an .nev file for reading, returns all file information in a NEV
  5. % structure. Works with File Spec 2.1 & 2.2 & 2.3 & 3.0.
  6. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7. % Use OUTPUT = openNEV(fname, 'noread', 'report', 'noparse', 'nowarning',
  8. % 'nosave', 'nomat', 'uV', 'overwrite', 'direct').
  9. %
  10. % NOTE: All input arguments are optional. Input arguments may be in any order.
  11. %
  12. % fname: Name of the file to be opened. If the fname is omitted
  13. % the user will be prompted to select a file using an open
  14. % file user interface.
  15. % DEFAULT: Will open Open File UI.
  16. %
  17. % 'noread': Will not read the spike waveforms if user passes this argument.
  18. % DEFAULT: will read spike waveform.
  19. %
  20. % 'report': Will show a summary report if user passes this argument.
  21. % DEFAULT: will not show report.
  22. %
  23. % 'parse': The code will not parse the experimental parameters in digital I/O.
  24. % See below for guidelines on how to format your parameters.
  25. % DEFAULT: will not parse the parameters.
  26. %
  27. % 'nowarning': The code will not give a warning if there is an error in
  28. % parsing.
  29. % DEFAULT: will give warning message.
  30. %
  31. % 'nosave': The code will not save a copy of the NEV structure as a
  32. % MAT file. By default the code will save a copy in the same
  33. % folder as the NEV file for easy future access.
  34. % DEFAULT: will save the MAT file.
  35. %
  36. % 'nomat': Will not look for a MAT file. This option will force
  37. % openNEV to open a NEV file instead of any available MAT
  38. % files.
  39. % DEFAULT: will load the MAT file if available.
  40. %
  41. % 'uV': Will read the spike waveforms in unit of uV instead of
  42. % raw values. Note that this conversion may lead to loss of
  43. % information (e.g. 15/4 = 4) since the waveforms type will
  44. % stay in int16. It's recommended to read raw spike
  45. % waveforms and then perform the conversion at a later
  46. % time.
  47. % DEFAULT: will read waveform information in raw.
  48. %
  49. % '8bits': Indicates that 8 bits on the digital IO port was used
  50. % instead of 16 bits.
  51. % DEFAULT: will assumes that 16 bits of digital IO were used.
  52. %
  53. % 't:': Indicats the time window of the NEV file to be read. For
  54. % example, if t: is set to 2 (i.e. 't:0.6')
  55. % then only the first 2 seconds of the file is to be read. If set
  56. % to 2-50 (i.e. 't:2:50) then the time between 2 seconds
  57. % and 50 seconds will be read.
  58. % DEFAULT: the entire file will be read if 't:xx:xx' is not
  59. % passed to the function.
  60. %
  61. % 'overwrite': If MATLAB loads a NEV file using 'nomat' and a MAT file
  62. % already exists, by default it will prompt the user to
  63. % allow for overwriting the old MAT. Passing the
  64. % 'overwrite' flag will automatically overwrite the newly
  65. % opened NEV file ont the old MAT file.
  66. % DEFAULT: will ask the user whether to overwrite the old
  67. % MAT.
  68. %
  69. % 'direct': Use this if you are using a CerePlex Direct system
  70. % without the typical strobe mode. This will treat the 16th
  71. % bit of the digital input as a strobe signal and report
  72. % the remaining 15 bits as the digital input value.
  73. %
  74. % OUTPUT: Contains the NEV structure.
  75. %
  76. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  77. % USAGE EXAMPLE:
  78. %
  79. % openNEV('report','read');
  80. %
  81. % In the example above, the file dialogue will prompt for a file. A
  82. % report of the file contents will be shown. The digital data will not be
  83. % parsed. The data needs to be in the proper format (refer below). The
  84. % spike waveforms are in raw units and not in uV.
  85. %
  86. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  87. % DIGITAL PARAMETERS/MARKERS FORMAT:
  88. %
  89. % In order for this function to parse your experimental parameters they
  90. % need to be in the following format:
  91. %
  92. % *ParamLabel:Parameter1=value1;Parameter2=value2;Parameter3=value3;#
  93. %
  94. % TWO EXAMPLES:
  95. % *ExpParameter:Intensity=1.02;Duration=400;Trials=1;PageSegment=14;#
  96. %
  97. % *Stimulation:StimCount=5;Duration=10;#
  98. %
  99. % In the first example, the parameter is of type "ExpParameter". The
  100. % parameters are, "Intensity, Duration, Trials, and PageSement." The
  101. % values of those parameters are, "1.02, 400, 1, and 14," respectively.
  102. % The second example is of type "Stimulation". The name of the parameters
  103. % are "StimCount" and "Duration" and the values are "5" and "10"
  104. % respectively.
  105. % -----------------------------------------------------------------------
  106. % It can also read single value markers that follow the following format.
  107. %
  108. % *MarkerName=Value;#
  109. %
  110. % EXAMPLES: *WaitSeconds=10;# OR *JuiceStatus=ON;#
  111. %
  112. % The above line is a "Marker". The marker value is 10 in the first
  113. % and it's ON in the second example.
  114. % -----------------------------------------------------------------------
  115. % Moreover, the marker could be a single value:
  116. %
  117. % *MarkerValue#
  118. %
  119. % EXAMPLES: *JuiceOff# OR *HandsOnSwitches#
  120. % -----------------------------------------------------------------------
  121. % The label, parameter name, and values are flexible and can be anything.
  122. % The only required formatting is that the user needs to have a label
  123. % followed by a colon ':', followed by a field name 'MarkerVal', followed
  124. % by an equal sign '=', followed by the parameter value '10', and end
  125. % with a semi-colon ';'.
  126. %
  127. % NOTE:
  128. % Every line requires a pound-sign '#' at the very end.
  129. % Every line requires a star sign '*' at the very beginning. If you
  130. % use LabVIEW SendtoCerebus.vi by Kian Torab then there is no need for
  131. % a '*' in the beginning.
  132. %
  133. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  134. % Kian Torab
  135. % support@blackrockmicro.com
  136. % Blackrock Microsystems
  137. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  138. % Version History
  139. %
  140. % 4.4.0.0:
  141. % - Major performance boost in reading NEV files when tracking data is
  142. % stored in the file.
  143. %
  144. % 4.4.0.2:
  145. % - Updated documentation.
  146. %
  147. % 4.4.0.3: 5 January 2014
  148. % - Fixed the way DayOfWeek is read in MetaTags.
  149. % - Fixed 'noread' argument, so when passed, openNEV will not read the
  150. % spike waveforms.
  151. %
  152. % 4.4.1.0: 25 January 2014
  153. % - Fixed a bug that resulted from passing 'read' to openNEV.
  154. %
  155. % 4.4.2.0: 28 February 2014
  156. % - Fixed bug related to loading data with t:XX:XX argument.
  157. %
  158. % 4.4.3.0: 12 June 2014
  159. % - Fixed a typo in the help.
  160. %
  161. % 4.4.3.1: 13 June 2014
  162. % - Updated the version numbers in the help and in the function itself.
  163. %
  164. % 5.0.0.0: 02 December 2014
  165. % - Fixed a bug where Application name wasn't being read properly.
  166. % - Warnings now don't show up in more places when "nowarning" is used.
  167. % - Added field FileExt to MetaTags.
  168. % - Added 512 synchronized reading capability.
  169. % - Fixed the date in NSx.MetaTags.DateTime.
  170. %
  171. % 5.1.0.0: 28 March 2015
  172. % - Added the ability to read from networked drives in Windows.
  173. % - Fixed the DateTime variable in MetaTags.
  174. % - Fixed the date in NSx.MetaTags.DateTime (again).
  175. % - Fixed a bug related to >512-ch data loading.
  176. %
  177. % 5.1.1.0: 1 April 2015
  178. % - Fixed a bug with NeuroMotive when spike window is changed from the
  179. % original length.
  180. %
  181. % 5.1.2.0: June 30 2015
  182. % - Fixed a bug regarding the number of packages when 'no read' is used.
  183. %
  184. % 5.1.3.0: July 10 2015
  185. % - Fixed a bug with NeuroMotive data reading when both objects and
  186. % markers were being recorded.
  187. %
  188. % 5.2.0.0: June 11 2016
  189. % - Added support for CerePlex Direct strobe mode on digital input.
  190. % - Fixed a bug with reading NeuroMotive data that resulted in a crash.
  191. %
  192. % 5.3.0.0: June 13 2016
  193. % - Fixed a bug with reading NeuroMotive data that resulted in a crash.
  194. % - Improved and more detailed parsing of NeuroMotive events.
  195. % - Added parsing of comment start time and comment committ time (time
  196. % that a comment is entered.
  197. %
  198. % 5.3.1.0: September 1, 2017
  199. % - Fixed a bug with file path and whent this was passed to the function.
  200. %
  201. % 5.4.0.0: September 13, 2017
  202. % - Checks to see if there's a newer version of NPMK is available.
  203. % - Properly reads the comment colors.
  204. %
  205. % 5.4.0.1: January 10, 2018
  206. % - Fixed a NeuroMotive bug when AllMarkers was being recorded.
  207. %
  208. % 5.4.1.0: April 25, 2018
  209. % - Now all comments open in order.
  210. % - Fixed a bug with path of file if both NEV and MAT were moved to a new
  211. % location.
  212. %
  213. % 6.0.0.0: January 27, 2020
  214. % - Added support for 64-bit timestamps in NEV and NSx.
  215. % - Removed dependency on MATLAB R2016b by removing function 'contains'.
  216. %
  217. % 6.1.0.0: April 16, 2020
  218. % - Some bug fixes. (David Kluger)
  219. %
  220. % 6.2.0.0: April 29, 2020
  221. % - Added ability to read all types of recording event types.
  222. %
  223. %
  224. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  225. %% Check for the latest version fo NPMK
  226. NPMKverChecker
  227. %% Defining structures
  228. NEV = struct('MetaTags',[], 'ElectrodesInfo', [], 'Data', []);
  229. NEV.MetaTags.openNEVver = '6.2.0.0';
  230. NEV.MetaTags = struct('Subject', [], 'Experimenter', [], 'DateTime', [],...
  231. 'SampleRes',[],'Comment',[],'FileTypeID',[],'Flags',[], 'openNEVver', [], ...
  232. 'DateTimeRaw', [], 'FileSpec', [], 'PacketBytes', [], 'HeaderOffset', [], ...
  233. 'DataDuration', [], 'DataDurationSec', [], 'PacketCount', [], ...
  234. 'TimeRes', [], 'Application', [], 'Filename', [], 'FilePath', []);
  235. NEV.Data = struct('SerialDigitalIO', [], 'Spikes', [], 'Comments', [], 'VideoSync', [], ...
  236. 'Tracking', [], 'TrackingEvents', [], 'PatientTrigger', [], 'Reconfig', []);
  237. NEV.Data.Spikes = struct('TimeStamp', [],'Electrode', [],...
  238. 'Unit', [],'Waveform', [], 'WaveformUnit', []);
  239. NEV.Data.SerialDigitalIO = struct('InputType', [], 'TimeStamp', [],...
  240. 'TimeStampSec', [], 'Type', [], 'Value', [], 'InsertionReason', [], 'UnparsedData', []);
  241. NEV.Data.VideoSync = struct('TimeStamp', [], 'FileNumber', [], 'FrameNumber', [], 'ElapsedTime', [], 'SourceID', []);
  242. NEV.Data.Comments = struct('TimeStampStarted', [], 'TimeStampStartedSec', [], 'TimeStamp', [], 'TimeStampSec', [], 'CharSet', [], 'Text', []);
  243. NEV.Data.Tracking = [];
  244. NEV.Data.TrackingEvents = struct('TimeStamp', [], 'TimeStampSec', [], 'ROIName', [], 'ROINum', [], 'Event', [], 'Frame', []);
  245. NEV.Data.PatientTrigger = struct('TimeStamp', [], 'TriggerType', []);
  246. NEV.Data.Reconfig = struct('TimeStamp', [], 'ChangeType', [], 'CompName', [], 'ConfigChanged', []);
  247. Flags = struct;
  248. %% Check for multiple versions of openNEV in path
  249. if size(which('openNEV', '-ALL'),1) > 1
  250. disp('WARNING: There are multiple openNEV functions in the path. Use which openNEV -ALL for more information.');
  251. end
  252. %% Validating input arguments
  253. for i=1:length(varargin)
  254. switch lower(varargin{i})
  255. case 'report'
  256. Flags.Report = varargin{i};
  257. case 'noread'
  258. Flags.ReadData = varargin{i};
  259. case 'nomultinsp'
  260. Flags.MultiNSP = varargin{i};
  261. case 'read'
  262. Flags.ReadData = varargin{i};
  263. case 'nosave'
  264. Flags.SaveFile = varargin{i};
  265. case 'nomat'
  266. Flags.NoMAT = varargin{i};
  267. case 'direct'
  268. Flags.Direct = varargin{i};
  269. case 'nowarning'
  270. Flags.WarningStat = varargin{i};
  271. case 'parse'
  272. Flags.ParseData = 'parse';
  273. case 'uv'
  274. Flags.waveformUnits = 'uV';
  275. case '8bits'
  276. Flags.digIOBits = '8bits';
  277. case 'overwrite'
  278. Flags.Overwrite = 'overwrite';
  279. case 'nooverwrite'
  280. Flags.Overwrite = 'nooverwrite';
  281. otherwise
  282. temp = varargin{i};
  283. if length(temp)>3 && ...
  284. (strcmpi(temp(3),'\') || ...
  285. strcmpi(temp(1),'/') || ...
  286. strcmpi(temp(2),'/') || ...
  287. strcmpi(temp(1:2), '\\') || ...
  288. strcmpi(temp(end-3), '.'))
  289. fileFullPath = varargin{i};
  290. if exist(fileFullPath, 'file') ~= 2
  291. disp('The file does not exist.');
  292. varargout{1} = [];
  293. return;
  294. end
  295. elseif length(temp)>3 && strcmpi(temp(1:2),'t:') && ~strcmpi(temp(3), '\') && ~strcmpi(temp(3), '/')
  296. temp(1:2) = [];
  297. temp = str2num(temp);
  298. if length(temp) == 1
  299. fprintf('Only one timepoint (%0.0f) was passed to the function.\n', temp);
  300. fprintf('The initial timepoint is set to 0, so data between 0 and %0.0f will be read.\n', temp);
  301. temp(2) = temp;
  302. temp(1) = 0;
  303. end
  304. readTime = [temp(1), temp(end)];
  305. Flags.SaveFile = 'nosave';
  306. Flags.NoMAT = 'nomat';
  307. elseif (strncmp(temp, 'c:', 2) && temp(3) ~= '\' && temp(3) ~= '/')
  308. Flags.selChannels = str2num(temp(3:end)); %#ok<ST2NM>
  309. else
  310. if ~isnumeric(varargin{i})
  311. disp(['Invalid argument ''' varargin{i} ''' .']);
  312. else
  313. disp(['Invalid argument ''' num2str(varargin{i}) ''' .']);
  314. end
  315. clear variables;
  316. if nargout
  317. varargout{1} = [];
  318. end
  319. return;
  320. end
  321. clear temp;
  322. end
  323. end; clear i;
  324. %% Defining and validating variables
  325. if ~exist('fileFullPath', 'var')
  326. if exist('getFile.m', 'file') == 2
  327. [fileName pathName] = getFile('*.nev;*.nevm', 'Choose a NEV file...');
  328. else
  329. [fileName pathName] = uigetfile;
  330. end
  331. fileFullPath = [pathName fileName];
  332. if fileFullPath==0;
  333. clear variables;
  334. if nargout
  335. varargout{1} = [];
  336. end
  337. disp('No file was selected.');
  338. return
  339. end
  340. end
  341. [~, ~, fileExt] = fileparts(fileFullPath);
  342. %% Loading .x files for multiNSP configuration
  343. if strcmpi(fileExt(2:4), 'nev') && length(fileExt) == 5
  344. fileFullPath(1) = fileFullPath(end);
  345. fileFullPath(end) = [];
  346. end
  347. if ~isfield(Flags, 'Report'); Flags.Report = 'noreport'; end
  348. if ~isfield(Flags, 'WarningStat'); Flags.WarningStat = 'warning'; end;
  349. if ~isfield(Flags, 'ReadData'); Flags.ReadData = 'read'; end
  350. if ~isfield(Flags, 'ParseData'); Flags.ParseData = 'noparse'; end
  351. if ~isfield(Flags, 'SaveFile'); Flags.SaveFile = 'save'; end;
  352. if ~isfield(Flags, 'NoMAT'); Flags.NoMAT = 'yesmat'; end;
  353. if ~isfield(Flags, 'waveformUnits'); Flags.waveformUnits = 'raw'; end;
  354. if ~isfield(Flags, 'digIOBits'); Flags.digIOBits = '16bits'; end;
  355. if ~isfield(Flags, 'Overwrite'); Flags.Overwrite = 'nooverwrite'; end;
  356. if ~isfield(Flags, 'MultiNSP'); Flags.MultiNSP = 'multinsp'; end;
  357. if ~isfield(Flags, 'selChannels'); Flags.selChannels = 'all'; end;
  358. if ~isfield(Flags, 'Direct'); Flags.Direct = 'nodirect'; end;
  359. if strcmpi(Flags.Report, 'report')
  360. disp(['openNEV ' NEV.MetaTags.openNEVver]);
  361. end
  362. syncShift = 0;
  363. % Check to see if 512 setup and calculate offset
  364. if strcmpi(Flags.MultiNSP, 'multinsp')
  365. fiveTwelveFlag = regexp(fileFullPath, '-i[0123]-');
  366. if ~isempty(fiveTwelveFlag)
  367. syncShift = multiNSPSync(fileFullPath);
  368. else
  369. Flags.MultiNSP = 'no';
  370. end
  371. end
  372. %% Validating existance of parseCommand
  373. if strcmpi(Flags.ParseData, 'parse')
  374. if exist('parseCommand.m', 'file') ~= 2
  375. disp('This version of openNEV requires function parseCommand.m to be placed in path.');
  376. clear variables;
  377. if nargout
  378. varargout{1} = [];
  379. end
  380. return;
  381. end
  382. end
  383. tic;
  384. matPath = [fileFullPath(1:end-4) '.mat'];
  385. %% Check for a MAT file and load that instead of NEV
  386. if exist(matPath, 'file') == 2 && strcmpi(Flags.NoMAT, 'yesmat') && strcmpi(Flags.WarningStat, 'warning')
  387. disp('MAT file corresponding to selected NEV file already exists. Loading MAT instead...');
  388. load(matPath);
  389. NEV.MetaTags.FilePath = fileFullPath;
  390. if isempty(NEV.Data.Spikes.Waveform) && strcmpi(Flags.ReadData, 'read') && strcmpi(Flags.WarningStat, 'warning')
  391. disp('The MAT file does not waveforms. Loading NEV instead...');
  392. else
  393. NEV = killUnwantedChannels(NEV, Flags.selChannels);
  394. if ~nargout
  395. assignin('base', 'NEV', NEV);
  396. clear variables;
  397. else
  398. varargout{1} = NEV;
  399. end
  400. return;
  401. end
  402. end
  403. %% Reading BasicHeader information from file
  404. FID = fopen(fileFullPath, 'r', 'ieee-le');
  405. BasicHeader = fread(FID, 336, '*uint8');
  406. NEV.MetaTags.FileTypeID = char(BasicHeader(1:8)');
  407. NEV.MetaTags.FileSpec = [num2str(double(BasicHeader(9))) '.' num2str(double(BasicHeader(10)))];
  408. NEV.MetaTags.Flags = dec2bin(double(typecast(BasicHeader(11:12), 'uint16')),16);
  409. Trackers.fExtendedHeader = double(typecast(BasicHeader(13:16), 'uint32'));
  410. NEV.MetaTags.HeaderOffset = Trackers.fExtendedHeader;
  411. Trackers.countPacketBytes = double(typecast(BasicHeader(17:20), 'uint32'));
  412. NEV.MetaTags.PacketBytes = Trackers.countPacketBytes;
  413. NEV.MetaTags.TimeRes = double(typecast(BasicHeader(21:24), 'uint32'));
  414. NEV.MetaTags.SampleRes = typecast(BasicHeader(25:28), 'uint32');
  415. t = double(typecast(BasicHeader(29:44), 'uint16'));
  416. tempApp = BasicHeader(45:76)';
  417. tempApp(find(tempApp == 0):end) = [];
  418. NEV.MetaTags.Application = char(tempApp); clear tempApp;
  419. NEV.MetaTags.Comment = char(BasicHeader(77:332)');
  420. [NEV.MetaTags.FilePath, NEV.MetaTags.Filename, NEV.MetaTags.FileExt] = fileparts(fileFullPath);
  421. Trackers.countExtHeader = typecast(BasicHeader(333:336), 'uint32');
  422. clear BasicHeader;
  423. if or(strcmpi(NEV.MetaTags.FileTypeID, 'NEURALEV'), strcmpi(NEV.MetaTags.FileTypeID, 'BREVENTS'))
  424. if exist([fileFullPath(1:end-8) '.sif'], 'file') == 2
  425. METATAGS = textread([fileFullPath(1:end-8) '.sif'], '%s');
  426. NEV.MetaTags.Subject = METATAGS{3}(5:end-5);
  427. NEV.MetaTags.Experimenter = [METATAGS{5}(8:end-8) ' ' METATAGS{6}(7:end-7)];
  428. end
  429. end
  430. if ~any(strcmpi(NEV.MetaTags.FileSpec, {'2.1', '2.2', '2.3', '3.0'}))
  431. disp('Unknown filespec. Cannot open file.');
  432. fclose FID;
  433. clear variables;
  434. if nargout
  435. varargout{1} = [];
  436. end
  437. return;
  438. end
  439. clear fileFullPath;
  440. %% Parsing and validating FileSpec and DateTime variables
  441. NEV.MetaTags.DateTimeRaw = t.';
  442. NEV.MetaTags.DateTime = datestr(datenum(t(1), t(2), t(4), t(5), t(6), t(7)));
  443. clear t;
  444. %% Removing extra garbage characters from the Comment field.
  445. NEV.MetaTags.Comment(find(NEV.MetaTags.Comment==0,1):end) = 0;
  446. %% Recording after BasicHeader file position
  447. Trackers.fBasicHeader = ftell(FID); %#ok<NASGU>
  448. % Calculating the length of the data
  449. currentLocation = ftell(FID);
  450. fseek(FID, -Trackers.countPacketBytes, 'eof');
  451. NEV.MetaTags.DataDuration = fread(FID, 1, 'uint32=>double');
  452. NEV.MetaTags.DataDurationSec = double(NEV.MetaTags.DataDuration) / double(NEV.MetaTags.SampleRes);
  453. fseek(FID, currentLocation, 'bof');
  454. %% Reading ExtendedHeader information
  455. for ii=1:Trackers.countExtHeader
  456. ExtendedHeader = fread(FID, 32, '*uint8');
  457. PacketID = char(ExtendedHeader(1:8)');
  458. switch PacketID
  459. case 'ARRAYNME'
  460. NEV.ArrayInfo.ElectrodeName = char(ExtendedHeader(9:end));
  461. case 'ECOMMENT'
  462. NEV.ArrayInfo.ArrayComment = char(ExtendedHeader(9:end));
  463. case 'CCOMMENT'
  464. NEV.ArrayInfo.ArrayCommentCont = char(ExtendedHeader(9:end));
  465. case 'MAPFILE'
  466. NEV.ArrayInfo.MapFile = char(ExtendedHeader(9:end));
  467. case 'NEUEVWAV'
  468. ElectrodeID = typecast(ExtendedHeader(9:10), 'uint16');
  469. NEV.ElectrodesInfo(ElectrodeID).ElectrodeID = ElectrodeID;
  470. NEV.ElectrodesInfo(ElectrodeID).ConnectorBank = char(ExtendedHeader(11)+64);
  471. NEV.ElectrodesInfo(ElectrodeID).ConnectorPin = ExtendedHeader(12);
  472. df = typecast(ExtendedHeader(13:14),'int16');
  473. % This is a workaround for the DigitalFactor overflow in NEV
  474. % files. Remove once Central is updated
  475. if df == 21516
  476. NEV.ElectrodesInfo(ElectrodeID).DigitalFactor = 152592.547;
  477. else
  478. NEV.ElectrodesInfo(ElectrodeID).DigitalFactor = df;
  479. end
  480. % End of workaround
  481. NEV.ElectrodesInfo(ElectrodeID).EnergyThreshold = typecast(ExtendedHeader(15:16),'uint16');
  482. NEV.ElectrodesInfo(ElectrodeID).HighThreshold = typecast(ExtendedHeader(17:18),'int16');
  483. NEV.ElectrodesInfo(ElectrodeID).LowThreshold = typecast(ExtendedHeader(19:20),'int16');
  484. NEV.ElectrodesInfo(ElectrodeID).Units = ExtendedHeader(21);
  485. NEV.ElectrodesInfo(ElectrodeID).WaveformBytes = ExtendedHeader(22);
  486. clear ElectrodeID;
  487. case 'NEUEVLBL'
  488. ElectrodeID = typecast(ExtendedHeader(9:10), 'uint16');
  489. NEV.ElectrodesInfo(ElectrodeID).ElectrodeLabel = char(ExtendedHeader(11:26));
  490. clear ElectrodeID;
  491. case 'NEUEVFLT'
  492. ElectrodeID = typecast(ExtendedHeader(9:10), 'uint16');
  493. NEV.ElectrodesInfo(ElectrodeID).HighFreqCorner = typecast(ExtendedHeader(11:14),'uint32');
  494. NEV.ElectrodesInfo(ElectrodeID).HighFreqOrder = typecast(ExtendedHeader(15:18),'uint32');
  495. NEV.ElectrodesInfo(ElectrodeID).HighFilterType = typecast(ExtendedHeader(19:20),'uint16');
  496. NEV.ElectrodesInfo(ElectrodeID).LowFreqCorner = typecast(ExtendedHeader(21:24),'uint32');
  497. NEV.ElectrodesInfo(ElectrodeID).LowFreqOrder = typecast(ExtendedHeader(25:28),'uint32');
  498. NEV.ElectrodesInfo(ElectrodeID).LowFilterType = typecast(ExtendedHeader(29:30),'uint16');
  499. clear ElectrodeID;
  500. case 'DIGLABEL'
  501. Mode = ExtendedHeader(25);
  502. NEV.IOLabels{Mode+1} = char(ExtendedHeader(9:24).');
  503. clear Mode;
  504. case 'NSASEXEV' %% Not implemented in the Cerebus firmware.
  505. %% Needs to be updated once implemented into the
  506. %% firmware by Blackrock Microsystems.
  507. NEV.NSAS.Freq = typecast(ExtendedHeader(9:10),'uint16');
  508. NEV.NSAS.DigInputConf = char(ExtendedHeader(11));
  509. NEV.NSAS.AnalCh1Conf = char(ExtendedHeader(12));
  510. NEV.NSAS.AnalCh1Detect = typecast(ExtendedHeader(13:14),'uint16');
  511. NEV.NSAS.AnalCh2Conf = char(ExtendedHeader(15));
  512. NEV.NSAS.AnalCh2Detect = typecast(ExtendedHeader(16:17),'uint16');
  513. NEV.NSAS.AnalCh3Conf = char(ExtendedHeader(18));
  514. NEV.NSAS.AnalCh3Detect = typecast(ExtendedHeader(19:20),'uint16');
  515. NEV.NSAS.AnalCh4Conf = char(ExtendedHeader(21));
  516. NEV.NSAS.AnalCh4Detect = typecast(ExtendedHeader(22:23),'uint16');
  517. NEV.NSAS.AnalCh5Conf = char(ExtendedHeader(24));
  518. NEV.NSAS.AnalCh5Detect = typecast(ExtendedHeader(25:26),'uint16');
  519. case 'VIDEOSYN'
  520. cnt = 1;
  521. if (isfield(NEV, 'VideoSyncInfo'))
  522. cnt = size(NEV.VideoSyncInfo, 2) + 1;
  523. end
  524. NEV.VideoSyncInfo(cnt).SourceID = typecast(ExtendedHeader(9:10),'uint16');
  525. NEV.VideoSyncInfo(cnt).SourceName = char(ExtendedHeader(11:26))';
  526. NEV.VideoSyncInfo(cnt).FrameRateFPS = typecast(ExtendedHeader(27:30),'single')';
  527. clear cnt;
  528. case 'TRACKOBJ'
  529. cnt = 1;
  530. if (isfield(NEV, 'ObjTrackInfo'))
  531. cnt = size(NEV.ObjTrackInfo, 2) + 1;
  532. end
  533. NEV.ObjTrackInfo(cnt).TrackableType = typecast(ExtendedHeader(9:10),'uint16');
  534. NEV.ObjTrackInfo(cnt).TrackableID = typecast(ExtendedHeader(11:14), 'uint32');
  535. NEV.ObjTrackInfo(cnt).TrackableName = char(ExtendedHeader(15:30))';
  536. clear cnt;
  537. otherwise
  538. disp(['PacketID ' PacketID ' is invalid.']);
  539. disp('Please make sure this version of openNEV is compatible with your current NSP firmware.')
  540. fclose(FID);
  541. clear variables;
  542. if nargout
  543. varargout{1} = [];
  544. end
  545. return;
  546. end
  547. end
  548. NEV.MetaTags.ChannelID = [NEV.ElectrodesInfo.ElectrodeID];
  549. clear ExtendedHeader PacketID ii;
  550. %% Recording after ExtendedHeader file position and calculating Data Length
  551. % and number of data packets
  552. fseek(FID, 0, 'eof');
  553. Trackers.fData = ftell(FID);
  554. Trackers.countDataPacket = (Trackers.fData - Trackers.fExtendedHeader)/Trackers.countPacketBytes;
  555. NEV.MetaTags.PacketCount = Trackers.countDataPacket;
  556. %%
  557. Flags.UnparsedDigitalData = 0;
  558. %% Reading packet headers and digital values
  559. Timestamp = [];
  560. PacketIDs = [];
  561. tempClassOrReason = [];
  562. tempDigiVals = [];
  563. if NEV.MetaTags.PacketCount ~= 0
  564. fseek(FID, Trackers.fExtendedHeader, 'bof');
  565. if strcmpi(NEV.MetaTags.FileTypeID, 'NEURALEV')
  566. tRawData = fread(FID, [10 Trackers.countDataPacket], '10*uint8=>uint8', Trackers.countPacketBytes - 10);
  567. Timestamp = tRawData(1:4,:);
  568. Timestamp = typecast(Timestamp(:), 'uint32').' + syncShift;
  569. timeStampBytes = 4;
  570. elseif strcmpi(NEV.MetaTags.FileTypeID, 'BREVENTS')
  571. tRawData = fread(FID, [14 Trackers.countDataPacket], '14*uint8=>uint8', Trackers.countPacketBytes - 14);
  572. Timestamp = tRawData(1:8,:);
  573. Timestamp = typecast(Timestamp(:), 'uint64').' + syncShift;
  574. timeStampBytes = 8;
  575. end
  576. %% Calculate the number of packets that need to be read based on the time input parameters
  577. if ~exist('readTime', 'var')
  578. Trackers.readPackets = [1, length(Timestamp)];
  579. else
  580. [tmp,tempReadPackets] = find(Timestamp > readTime(1)*NEV.MetaTags.SampleRes,1,'first');
  581. if ~isempty(tempReadPackets)
  582. Trackers.readPackets(1) = tempReadPackets;
  583. else
  584. Trackers.readPackets(1) = NaN;
  585. end
  586. if isnan(Trackers.readPackets(1))
  587. fprintf('The file contains %0.2f seconds of data. The requested begining timestamp of %0.2f seconds is longer than the duration.\n', ...
  588. double(Timestamp(end))/double(NEV.MetaTags.SampleRes), ...
  589. readTime(1));
  590. clear variables;
  591. if nargout
  592. varargout{1} = [];
  593. end
  594. return;
  595. end
  596. [tmp,tempReadPackets] = find(Timestamp < readTime(2)*NEV.MetaTags.SampleRes,1,'last');
  597. if ~isempty(tempReadPackets)
  598. if readTime(2)*NEV.MetaTags.SampleRes > Timestamp(end)
  599. fprintf('The file contains %0.2f seconds of data. The requested end duration of %0.2f seconds will be adjusted to %0.2f seconds.\n', ...
  600. double(Timestamp(end))/double(NEV.MetaTags.SampleRes), ...
  601. readTime(2),...
  602. double(Timestamp(end))/double(NEV.MetaTags.SampleRes));
  603. end
  604. Trackers.readPackets(2) = tempReadPackets;
  605. else
  606. Trackers.readPackets(2) = NaN;
  607. end
  608. clear tmp, tempReadPackets;
  609. end
  610. PacketIDs = tRawData(timeStampBytes+1:timeStampBytes+2,Trackers.readPackets(1):Trackers.readPackets(2));
  611. PacketIDs = typecast(PacketIDs(:), 'uint16').';
  612. tempClassOrReason = uint8(tRawData(timeStampBytes+3,Trackers.readPackets(1):Trackers.readPackets(2)));
  613. if strcmpi(Flags.digIOBits, '16bits')
  614. tempDigiVals = tRawData(timeStampBytes+5:timeStampBytes+6,Trackers.readPackets(1):Trackers.readPackets(2));
  615. tempDigiVals = typecast(tempDigiVals(:), 'uint16');
  616. else
  617. tempDigiVals = uint16(tRawData(timeStampBytes+5,Trackers.readPackets(1):Trackers.readPackets(2)));
  618. end
  619. clear tRawData;
  620. else
  621. Trackers.readPackets = zeros(1,2);
  622. end
  623. %% Defining PacketID constants
  624. digserPacketID = 0;
  625. neuralIndicesPacketIDBounds = [1, 16384];
  626. commentPacketID = 65535;
  627. videoSyncPacketID = 65534;
  628. trackingPacketID = 65533;
  629. patientTrigPacketID = 65532;
  630. logEventPacketID = 65531;
  631. reconfigPacketID = 65530;
  632. recEventPacketID = 65529;
  633. %% Parse read digital data. Please refer to help to learn about the proper
  634. % formatting if the data.
  635. digserIndices = find(PacketIDs == digserPacketID);
  636. neuralIndices = find(neuralIndicesPacketIDBounds(2) >= PacketIDs & PacketIDs >= neuralIndicesPacketIDBounds(1));
  637. commentIndices = find(PacketIDs == commentPacketID);
  638. videoSyncPacketIDIndices = find(PacketIDs == videoSyncPacketID);
  639. trackingPacketIDIndices = find(PacketIDs == trackingPacketID);
  640. patientTrigPacketIDIndices = find(PacketIDs == patientTrigPacketID);
  641. logEventPacketIDIndices = find(PacketIDs == logEventPacketID);
  642. reconfigPacketIDIndices = find(PacketIDs == reconfigPacketID);
  643. recEventPacketIDIndices = find(PacketIDs == recEventPacketID);
  644. clear digserPacketID neuralIndicesPacketIDBounds commentPacketID ...
  645. videoSyncPacketID trackingPacketID patientTrigPacketID reconfigPacketID;
  646. digserTimestamp = Timestamp(digserIndices);
  647. NEV.Data.Spikes.TimeStamp = Timestamp(neuralIndices);
  648. NEV.Data.Spikes.Electrode = PacketIDs(neuralIndices);
  649. clear PacketIDs;
  650. NEV.Data.Spikes.Unit = tempClassOrReason(neuralIndices);
  651. %clear neuralIndices;
  652. NEV.Data.SerialDigitalIO.InsertionReason = tempClassOrReason(digserIndices);
  653. clear tempClassOrReason;
  654. DigiValues = tempDigiVals(digserIndices);
  655. clear tempDigiVals;
  656. %% Reads the waveforms if 'read' is passed to the function
  657. if strcmpi(Flags.ReadData, 'read')
  658. allExtraDataPacketIndices = [commentIndices, ...
  659. videoSyncPacketIDIndices, ...
  660. trackingPacketIDIndices, ...
  661. patientTrigPacketIDIndices, ...
  662. logEventPacketIDIndices,...
  663. reconfigPacketIDIndices,...
  664. recEventPacketIDIndices];
  665. if ~isempty(allExtraDataPacketIndices) % if there is any extra packets
  666. fseek(FID, Trackers.fExtendedHeader, 'bof');
  667. fseek(FID, (Trackers.readPackets(1)-1) * Trackers.countPacketBytes, 'cof');
  668. tRawData = fread(FID, [Trackers.countPacketBytes Trackers.readPackets(2)], ...
  669. [num2str(Trackers.countPacketBytes) '*uint8=>uint8'], 0);
  670. if ~isempty(commentIndices)
  671. [NEV.Data.Comments.TimeStamp, orderOfTS] = sort(Timestamp(commentIndices));
  672. NEV.Data.Comments.TimeStampSec = double(NEV.Data.Comments.TimeStamp)/double(NEV.MetaTags.TimeRes);
  673. tempCharSet = tRawData(timeStampBytes+3, commentIndices);
  674. NEV.Data.Comments.CharSet = tempCharSet(orderOfTS); clear tempCharSet;
  675. colorFlag = tRawData(timeStampBytes+4, commentIndices);
  676. NEV.Data.Comments.TimeStampStarted = tRawData(timeStampBytes+5:timeStampBytes+8, commentIndices);
  677. tempTimeStampStarted = typecast(NEV.Data.Comments.TimeStampStarted(:), 'uint32').';
  678. NEV.Data.Comments.TimeStampStarted = tempTimeStampStarted(orderOfTS); clear tempTimeStampStarted;
  679. tempText = char(tRawData(timeStampBytes+9:Trackers.countPacketBytes, commentIndices).');
  680. NEV.Data.Comments.Text = tempText(orderOfTS,:); clear tempText;
  681. % Transferring NeuroMotive Events to its own structure
  682. neuroMotiveEvents = find(NEV.Data.Comments.CharSet == 255);
  683. NEV.Data.TrackingEvents.TimeStamp = NEV.Data.Comments.TimeStamp(neuroMotiveEvents);
  684. NEV.Data.TrackingEvents.TimeStampSec = double(NEV.Data.TrackingEvents.TimeStamp)/double(NEV.MetaTags.TimeRes);
  685. % Parsing NeuroMotive Events
  686. events = NEV.Data.Comments.Text(neuroMotiveEvents,:);
  687. for idx = 1:size(events,1)
  688. splitEvent = strsplit(events(idx,:), ':');
  689. NEV.Data.TrackingEvents.ROIName{idx} = splitEvent{1};
  690. NEV.Data.TrackingEvents.ROINum(idx) = str2double(splitEvent{2});
  691. NEV.Data.TrackingEvents.Event{idx} = splitEvent{3};
  692. NEV.Data.TrackingEvents.Frame(idx) = str2double(splitEvent{4});
  693. end
  694. NEV.Data.Comments.TimeStamp(neuroMotiveEvents) = [];
  695. NEV.Data.Comments.TimeStampSec(neuroMotiveEvents) = [];
  696. NEV.Data.Comments.CharSet(neuroMotiveEvents) = [];
  697. NEV.Data.Comments.TimeStampStarted(neuroMotiveEvents) = [];
  698. NEV.Data.Comments.TimeStampStartedSec = double(NEV.Data.Comments.TimeStampStarted)/double(NEV.MetaTags.TimeRes);
  699. NEV.Data.Comments.Text(neuroMotiveEvents,:) = [];
  700. colorFlag(neuroMotiveEvents) = [];
  701. % Figuring out the text color of the comments that had color
  702. NEV.Data.Comments.Color = dec2hex(NEV.Data.Comments.TimeStampStarted);
  703. NEV.Data.Comments.Color(colorFlag == 1,:) = repmat('0', size(NEV.Data.Comments.Color(colorFlag == 1,:)));
  704. NEV.Data.Comments.TimeStampStarted(colorFlag == 0) = NEV.Data.Comments.TimeStamp(colorFlag == 0);
  705. clear commentIndices;
  706. end
  707. if ~isempty(videoSyncPacketIDIndices)
  708. NEV.Data.VideoSync.TimeStamp = Timestamp(videoSyncPacketIDIndices);
  709. NEV.Data.VideoSync.FileNumber = tRawData(timeStampBytes+3:timeStampBytes+4, videoSyncPacketIDIndices);
  710. NEV.Data.VideoSync.FileNumber = typecast(NEV.Data.VideoSync.FileNumber(:), 'uint16').';
  711. NEV.Data.VideoSync.FrameNumber = tRawData(timeStampBytes+5:timeStampBytes+8, videoSyncPacketIDIndices);
  712. NEV.Data.VideoSync.FrameNumber = typecast(NEV.Data.VideoSync.FrameNumber(:), 'uint32').';
  713. NEV.Data.VideoSync.ElapsedTime = tRawData(timeStampBytes+9:timeStampBytes+12, videoSyncPacketIDIndices);
  714. NEV.Data.VideoSync.ElapsedTime = typecast(NEV.Data.VideoSync.ElapsedTime(:), 'uint32').';
  715. NEV.Data.VideoSync.SourceID = tRawData(timeStampBytes+13:timeStampBytes+16, videoSyncPacketIDIndices);
  716. NEV.Data.VideoSync.SourceID = typecast(NEV.Data.VideoSync.SourceID(:), 'uint32').';
  717. clear videoSyncPacketIDIndices;
  718. end
  719. if ~isempty(trackingPacketIDIndices)
  720. tmp.TimeStamp = Timestamp(trackingPacketIDIndices);
  721. tmp.TimeStampSec = double(tmp.TimeStamp)/30000;
  722. % This portion is commented out because it does not contain any
  723. % information as of yet.
  724. tmp.ParentID = tRawData(timeStampBytes+3:timeStampBytes+4, trackingPacketIDIndices);
  725. tmp.ParentID = typecast(tmp.ParentID(:), 'uint16').';
  726. tmp.NodeID = tRawData(timeStampBytes+5:timeStampBytes+6, trackingPacketIDIndices);
  727. tmp.NodeID = typecast(tmp.NodeID(:), 'uint16').';
  728. tmp.NodeCount = tRawData(timeStampBytes+7:timeStampBytes+8, trackingPacketIDIndices);
  729. tmp.NodeCount = typecast(tmp.NodeCount(:), 'uint16').';
  730. tmp.MarkerCount = tRawData(timeStampBytes+9:timeStampBytes+10, trackingPacketIDIndices);
  731. tmp.MarkerCount = typecast(tmp.MarkerCount(:), 'uint16').';
  732. tmp.rigidBodyPoints = tRawData(timeStampBytes+11:NEV.MetaTags.PacketBytes, trackingPacketIDIndices);
  733. tmp.rigidBodyPoints = reshape(typecast(tmp.rigidBodyPoints(:), 'uint16'), size(tmp.rigidBodyPoints, 1)/2, size(tmp.rigidBodyPoints, 2));
  734. if (isfield(NEV, 'ObjTrackInfo'))
  735. for IDX = 1:size(NEV.ObjTrackInfo,2)
  736. emptyChar = find(NEV.ObjTrackInfo(IDX).TrackableName == 0, 1);
  737. NEV.ObjTrackInfo(IDX).TrackableName(emptyChar:end) = [];
  738. if ~(~isempty(strfind(NEV.ObjTrackInfo(IDX).TrackableName, '1')) || ...
  739. ~isempty(strfind(NEV.ObjTrackInfo(IDX).TrackableName, '2')) || ...
  740. ~isempty(strfind(NEV.ObjTrackInfo(IDX).TrackableName, '3')) || ...
  741. ~isempty(strfind(NEV.ObjTrackInfo(IDX).TrackableName, '4')))
  742. nameLength = min(length(NEV.ObjTrackInfo(IDX-1).TrackableName(1:end-1)), length(NEV.ObjTrackInfo(IDX).TrackableName(1:end-1)));
  743. if ~strcmpi(NEV.ObjTrackInfo(IDX-1).TrackableName(1:nameLength-1), NEV.ObjTrackInfo(IDX).TrackableName(1:nameLength-1))
  744. objectIndex = 1;
  745. else
  746. objectIndex = objectIndex + 1;
  747. end
  748. NEV.ObjTrackInfo(IDX).TrackableName(emptyChar) = num2str(objectIndex);
  749. end
  750. indicesOfEvent = find(tmp.NodeID == IDX-1);
  751. if ~isempty(indicesOfEvent)
  752. NEV.Data.Tracking.(NEV.ObjTrackInfo(IDX).TrackableName).TimeStamp = tmp.TimeStamp(indicesOfEvent);
  753. NEV.Data.Tracking.(NEV.ObjTrackInfo(IDX).TrackableName).TimeStampSec = tmp.TimeStampSec(indicesOfEvent);
  754. NEV.Data.Tracking.(NEV.ObjTrackInfo(IDX).TrackableName).ParentID = tmp.ParentID(indicesOfEvent);
  755. NEV.Data.Tracking.(NEV.ObjTrackInfo(IDX).TrackableName).NodeCount = tmp.NodeCount(indicesOfEvent);
  756. NEV.Data.Tracking.(NEV.ObjTrackInfo(IDX).TrackableName).MarkerCount = tmp.MarkerCount(indicesOfEvent);
  757. NEV.Data.Tracking.(NEV.ObjTrackInfo(IDX).TrackableName).MarkerCoordinates(size(NEV.Data.Tracking.(NEV.ObjTrackInfo(IDX).TrackableName).TimeStamp,2)).X = [];
  758. NEV.Data.Tracking.(NEV.ObjTrackInfo(IDX).TrackableName).MarkerCoordinates(size(NEV.Data.Tracking.(NEV.ObjTrackInfo(IDX).TrackableName).TimeStamp,2)).X = [];
  759. for xyIDX = 1:size(NEV.Data.Tracking.(NEV.ObjTrackInfo(IDX).TrackableName).TimeStamp,2)
  760. NEV.Data.Tracking.(NEV.ObjTrackInfo(IDX).TrackableName).MarkerCoordinates(xyIDX).X = ...
  761. tmp.rigidBodyPoints(1:2:NEV.Data.Tracking.(NEV.ObjTrackInfo(IDX).TrackableName).MarkerCount(xyIDX)*2, indicesOfEvent(xyIDX));
  762. NEV.Data.Tracking.(NEV.ObjTrackInfo(IDX).TrackableName).MarkerCoordinates(xyIDX).Y = ...
  763. tmp.rigidBodyPoints(2:2:NEV.Data.Tracking.(NEV.ObjTrackInfo(IDX).TrackableName).MarkerCount(xyIDX)*2, indicesOfEvent(xyIDX));
  764. end
  765. end
  766. end
  767. end
  768. clear trackingPacketIDIndices tmp;
  769. end
  770. if ~isempty(patientTrigPacketIDIndices)
  771. NEV.Data.PatientTrigger.TimeStamp = Timestamp(patientTrigPacketIDIndices);
  772. NEV.Data.PatientTrigger.TriggerType = tRawData(timeStampBytes+3:timeStampBytes+4, patientTrigPacketIDIndices);
  773. NEV.Data.PatientTrigger.TriggerType = typecast(NEV.Data.PatientTrigger.TriggerType(:), 'uint16').';
  774. clear patientTrigPacketIDIndices;
  775. end
  776. if ~isempty(reconfigPacketIDIndices)
  777. NEV.Data.Reconfig.TimeStamp = Timestamp(reconfigPacketIDIndices);
  778. NEV.Data.Reconfig.ChangeType = tRawData(timeStampBytes+3:timeStampBytes+4, reconfigPacketIDIndices);
  779. NEV.Data.Reconfig.ChangeType = typecast(NEV.Data.Reconfig.ChangeType(:), 'uint16').';
  780. NEV.Data.Reconfig.CompName = char(tRawData(timeStampBytes+5:timeStampBytes+20, reconfigPacketIDIndices));
  781. NEV.Data.Reconfig.ConfigChanged = char(tRawData(timeStampBytes+21:Trackers.countPacketBytes, reconfigPacketIDIndices));
  782. clear reconfigPacketIDIndices;
  783. end
  784. if ~isempty(logEventPacketIDIndices)
  785. NEV.Data.LogEvent.TimeStamp = Timestamp(logEventPacketIDIndices);
  786. tmp.Mode = tRawData(timeStampBytes+3:timeStampBytes+4, logEventPacketIDIndices);
  787. NEV.Data.LogEvent.Mode = typecast(tmp.Mode(:), 'uint16').';
  788. NEV.Data.LogEvent.Application = char(tRawData(timeStampBytes+5:timeStampBytes+20, logEventPacketIDIndices).');
  789. end
  790. if ~isempty(recEventPacketIDIndices)
  791. NEV.Data.RecordingEvents.TimeStamp = Timestamp(recEventPacketIDIndices);
  792. tmp.EventCode = tRawData(timeStampBytes+3:timeStampBytes+4, recEventPacketIDIndices);
  793. NEV.Data.RecordingEvents.EventCode = typecast(tmp.EventCode(:), 'uint16').';
  794. end
  795. end % end if ~isempty(allExtraDataPacketIndices)
  796. clear Timestamp tRawData count idx;
  797. % now read waveform
  798. fseek(FID, Trackers.fExtendedHeader + 12, 'bof'); % Seek to location of spikes
  799. fseek(FID, (Trackers.readPackets(1)-1) * Trackers.countPacketBytes, 'cof');
  800. NEV.Data.Spikes.WaveformUnit = Flags.waveformUnits;
  801. NEV.Data.Spikes.Waveform = fread(FID, [(Trackers.countPacketBytes-12)/2 Trackers.readPackets(2)], ...
  802. [num2str((Trackers.countPacketBytes-12)/2) '*int16=>int16'], 12);
  803. NEV.Data.Spikes.Waveform(:, [digserIndices allExtraDataPacketIndices]) = [];
  804. clear allExtraDataPacketIndices;
  805. if strcmpi(Flags.waveformUnits, 'uv')
  806. elecDigiFactors = double(1000./[NEV.ElectrodesInfo(NEV.Data.Spikes.Electrode).DigitalFactor]);
  807. NEV.Data.Spikes.Waveform = bsxfun(@rdivide, double(NEV.Data.Spikes.Waveform), elecDigiFactors);
  808. if strcmpi(Flags.WarningStat, 'warning')
  809. fprintf(1,'\nThe spike waveforms are in unit of uV.\n');
  810. fprintf(2,'WARNING: This conversion may lead to loss of information.');
  811. fprintf(1,'\nRefer to help for more information.\n');
  812. end
  813. end
  814. end
  815. clear digserIndices;
  816. %% Parse digital data if requested
  817. if ~isempty(DigiValues)
  818. if strcmpi(Flags.ParseData, 'parse')
  819. try
  820. DigiValues = char(DigiValues);
  821. Inputs = {'Digital'; 'AnCh1'; 'AnCh2'; 'AnCh3'; 'AnCh4'; 'AnCh5'; 'PerSamp'; 'Serial'};
  822. AsteriskIndices = find(DigiValues == '*');
  823. DataBegTimestamp = digserTimestamp(AsteriskIndices);
  824. splitDigiValues = regexp(DigiValues(2:end), '*', 'split')';
  825. for idx = 1:length(splitDigiValues)
  826. try
  827. if isempty(find(splitDigiValues{idx} == ':', 1))
  828. splitDigiValues{idx}(find(splitDigiValues{idx} == '#')) = [];
  829. NEV.Data.SerialDigitalIO(idx).Value = splitDigiValues{idx};
  830. NEV.Data.SerialDigitalIO(idx).Type = 'Marker';
  831. else
  832. [tempParsedCommand error] = parseCommand(splitDigiValues{idx});
  833. if ~error
  834. pcFields = fields(tempParsedCommand);
  835. NEV.Data.SerialDigitalIO(idx).Value = splitDigiValues{idx};
  836. for fidx = 1:length(pcFields)
  837. NEV.Data.SerialDigitalIO(idx).(pcFields{fidx}) = tempParsedCommand.(pcFields{fidx});
  838. end
  839. else
  840. NEV.Data.SerialDigitalIO(idx).Value = splitDigiValues{idx};
  841. NEV.Data.SerialDigitalIO(idx).Type = 'UnparsedData';
  842. Flags.UnparsedDigitalData = 1;
  843. end
  844. end
  845. catch
  846. disp(['Error parsing: ' splitDigiValues{idx}]);
  847. disp('Please refer to the help for more information on how to properly format the digital data for parsing.');
  848. end
  849. end
  850. % Populate the NEV structure with Timestamp and inputtypes for the
  851. % digital data
  852. if ~isempty(DataBegTimestamp)
  853. c = num2cell(DataBegTimestamp); [NEV.Data.SerialDigitalIO(1:length(NEV.Data.SerialDigitalIO)).TimeStamp] = deal(c{1:end});
  854. c = num2cell(DataBegTimestamp/NEV.MetaTags.SampleRes); [NEV.Data.SerialDigitalIO.TimeStampSec] = deal(c{1:end});
  855. c = {Inputs{NEV.Data.SerialDigitalIO.InsertionReason(AsteriskIndices)}}; [NEV.Data.SerialDigitalIO.InputType] = deal(c{1:end});
  856. end
  857. clear Inputs DigiValues digserTimestamp;
  858. catch
  859. disp(lasterr);
  860. disp('An error occured during reading digital data. This is due to a problem with formatting digital data.');
  861. disp('Refer to help ''help openNEV'' for more information on how to properly format the digital data.');
  862. disp('Try using openNEV with ''noparse'', i.e. openNEV(''noparse'').');
  863. end
  864. else
  865. NEV.Data.SerialDigitalIO.TimeStamp = digserTimestamp;
  866. NEV.Data.SerialDigitalIO.TimeStampSec = double(digserTimestamp)/30000;
  867. NEV.Data.SerialDigitalIO.UnparsedData = DigiValues;
  868. if strcmpi(Flags.Direct, 'direct')
  869. % Finding the members that have bit 16 as the strobe high
  870. DShighs = find(NEV.Data.SerialDigitalIO.UnparsedData >= bin2dec('1000000000000000'));
  871. uniqueDShighs = DShighs([1; find(diff(DShighs)>1)+1]);
  872. DShighUniqueBin = dec2bin(NEV.Data.SerialDigitalIO.UnparsedData(uniqueDShighs));
  873. DShighUniqueDec = bin2dec(DShighUniqueBin(:,2:16));
  874. % Removing the non-strobed-high values from SerialDigitalIO
  875. extraMembers = setxor(uniqueDShighs, 1:length(NEV.Data.SerialDigitalIO.UnparsedData));
  876. NEV.Data.SerialDigitalIO.TimeStamp(extraMembers) = [];
  877. NEV.Data.SerialDigitalIO.TimeStampSec(extraMembers) = [];
  878. NEV.Data.SerialDigitalIO.UnparsedData = DShighUniqueDec;
  879. clear DShighs DShighUniqueBin DShighUniqueDec extraMembers;
  880. end
  881. clear digserTimestamp DigiValues
  882. end
  883. else
  884. if strcmpi(Flags.ReadData, 'read')
  885. if strcmpi(Flags.Report, 'report')
  886. disp('No digital data to read.');
  887. end
  888. end
  889. end
  890. if strcmpi(Flags.ParseData, 'parse')
  891. if Flags.UnparsedDigitalData && strcmpi(Flags.WarningStat, 'warning')
  892. fprintf(2, 'WARNING: The NEV file contains unparsed digital data.\n');
  893. end
  894. end
  895. %% Show a report if 'report' is passed as an argument
  896. if strcmpi(Flags.Report, 'report')
  897. % Displaying report
  898. disp( '*** FILE INFO **************************');
  899. disp(['File Name = ' NEV.MetaTags.Filename]);
  900. disp(['Filespec = ' NEV.MetaTags.FileSpec]);
  901. disp(['Data Duration (min) = ' num2str(round(NEV.MetaTags.DataDuration/NEV.MetaTags.SampleRes/60))]);
  902. disp(['Packet Counts = ' num2str(Trackers.countDataPacket)]);
  903. disp(' ');
  904. disp( '*** BASIC HEADER ***********************');
  905. disp(['Sample Resolution = ' num2str(NEV.MetaTags.SampleRes)]);
  906. disp(['Date and Time = ' NEV.MetaTags.DateTime]);
  907. disp(['Comment = ' NEV.MetaTags.Comment(1:64) ]);
  908. disp([' ' NEV.MetaTags.Comment(65:128) ]);
  909. disp([' ' NEV.MetaTags.Comment(129:192)]);
  910. disp([' ' NEV.MetaTags.Comment(193:256)]);
  911. disp(['The load time was for NEV file was ' num2str(toc, '%0.1f') ' seconds.']);
  912. end
  913. %% Saving the NEV structure as a MAT file for easy access
  914. if strcmpi(Flags.SaveFile, 'save')
  915. if exist(matPath, 'file') == 2 && strcmpi(Flags.Overwrite, 'nooverwrite')
  916. if strcmpi(Flags.WarningStat, 'warning')
  917. disp(['File ' matPath ' already exists.']);
  918. overWrite = input('Would you like to overwrite (Y/N)? ', 's');
  919. else
  920. overWrite = 'n';
  921. end
  922. if strcmpi(overWrite, 'y')
  923. if strcmpi(Flags.WarningStat, 'warning')
  924. disp('Saving MAT file. This may take a few seconds...');
  925. end
  926. save(matPath, 'NEV', '-v7.3');
  927. else
  928. if strcmpi(Flags.WarningStat, 'warning')
  929. disp('File was not overwritten.');
  930. end
  931. end
  932. elseif exist(matPath, 'file') == 2 && strcmpi(Flags.Overwrite, 'overwrite')
  933. if strcmpi(Flags.WarningStat, 'warning')
  934. disp(['File ' matPath ' already exists.']);
  935. disp('Overwriting the old MAT file. This may take a few seconds...');
  936. end
  937. save(matPath, 'NEV', '-v7.3');
  938. else
  939. if strcmpi(Flags.WarningStat, 'warning')
  940. disp('Saving MAT file. This may take a few seconds...');
  941. end
  942. save(matPath, 'NEV', '-v7.3');
  943. end
  944. clear overWrite;
  945. end
  946. NEV = killUnwantedChannels(NEV, Flags.selChannels);
  947. if ~nargout
  948. assignin('base', 'NEV', NEV);
  949. else
  950. varargout{1} = NEV;
  951. end
  952. fclose(FID);
  953. clear Flags Trackers FID matPath;
  954. function NEV = killUnwantedChannels(NEV, selectedChannels)
  955. if ~strcmpi(selectedChannels, 'all')
  956. if any(selectedChannels < 1)
  957. disp('Invalid channel. Channels cannot be 0 or negative values. Channel selection ignored.');
  958. else
  959. uniqueChannels = unique(NEV.Data.Spikes.Electrode);
  960. if ~isempty(setdiff(selectedChannels, uniqueChannels))
  961. disp('Some of the selected channels in c:xxx command are not in the data file. These will not be loaded.')
  962. end
  963. unWantedChannels = setdiff(uniqueChannels, selectedChannels);
  964. for idx = 1:length(unWantedChannels)
  965. NEV.Data.Spikes.Waveform(:, NEV.Data.Spikes.Electrode == unWantedChannels(idx)) = [];
  966. NEV.Data.Spikes.Unit(NEV.Data.Spikes.Electrode == unWantedChannels(idx)) = [];
  967. NEV.Data.Spikes.TimeStamp(NEV.Data.Spikes.Electrode == unWantedChannels(idx)) = [];
  968. NEV.Data.Spikes.Electrode(NEV.Data.Spikes.Electrode == unWantedChannels(idx)) = [];
  969. end
  970. end
  971. end