OSCR

Feasibility of fNIRS for assessing n-back task-related prefrontal cortex oxygenation after continuous cycling at varying intensities: an evaluation of protocol feasibility.

Code ↔ Paper

2 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 2 matches
  1. [1] § Materials and methods › Data processing and scientific feasibility assessment ↔ qtnirs.m, lines 1–68 · score 0.86 · peak power, quality assessment, good quality, fNIRS, Quality thresholds, QT NIRS
  2. [2] § Materials and methods › Data processing and scientific feasibility assessment ↔ utils/@QTNirs/QTNirs.m, lines 2–26 · score 0.74 · AR IRLS, channel pruning, QT NIRS, GLM, model

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

MATLAB · 1,566 lines · 68 KB · CC-BY-NC-SA-4.0 · 1 match

  1. function quality_matrices = qtnirs(dotNirsFilePath,varargin)
  2. % QT-NIRS is a Matlab-based tool for the quality assessment of fNIRS data.
  3. % QT-NIRS can quantify the quality of an fNIRS recording in two different ways, by using a GUI or through a function call.
  4. % Graphically, the QTNIRS GUI allows the user to locate a working folder for processing and quantifying the .nirs files within the working folder.
  5. % Programmatically, the users also can retrieve a set of quality measures by calling qtnirs from a Matlab script.
  6. %
  7. % Usage information
  8. % Using QT-NIRS inside of a script allows the users to specify a set of
  9. % parameters for the quality assessment. The 'dotNirsFilePath' parameter
  10. % can be the path of a .nirs file or the path to a folder containing
  11. % several .nirs files or a struct containing:
  12. % d*
  13. % t*
  14. % CondNames
  15. % aux
  16. % s*
  17. % SD*
  18. % procResult
  19. % userdata
  20. % procInput
  21. % *required
  22. % In addition to the .nirs path, the user
  23. % can specify a list of parameters in a pairwise mode including:
  24. %
  25. % Parameter keyword Description
  26. % freqCut: 1x2 array [fmin fmax] representing the bandpass of the cardiac pulsation (default [0.5 2.5])
  27. % window : length in seconds of the window (defaut: 5)
  28. % overlap: fraction overlap (0..0.99) between adjacent windows (default: 0, no overlap)
  29. % qualityThreshold: The required quality value (normalized; 0-1) of good-quality windows in every channel (default: 0.75)
  30. % conditionsMask: A binary mask or keyword to indicate the conditions
  31. % for computing the periods of interest. Valid keywords include 'all' and 'resting' to consider all or none of the conditions (default: 'all').
  32. % lambdaMask: A binary array mapping the selected two wavelength to compute the SCI (default: [1 1], the first two WLs)
  33. % dodFlag: A flag indicating to work from DOD data (default: 0)
  34. % guiFlag: A flag indicating whether to start or not the GUI.
  35. %
  36. %
  37. % An example of QT-NIRS usage is:
  38. %
  39. % bpFmin = 0.5; bpFmax = 2.5;
  40. % windowSec = 5;
  41. % windowOverlap = 0;
  42. % quality_threshold = 0.9;
  43. % qualityMatrices = qtnirs([pwd,filesep,'tmpDotNirs.nirs'],...
  44. % 'freqCut',[bpFmin, bpFmax],...
  45. % 'window',windowSec,...
  46. % 'overlap',windowOverlap,....
  47. % 'qualityThreshold',quality_threshold,...j
  48. % 'conditionsMask','all',...
  49. % 'dodFlag',0,...
  50. % 'guiFlag',0);
  51. %
  52. % The 'qualityMatrices' output variable is an structure that includes the set of fields:
  53. %
  54. % sci_array: Matrix containing the SCI values (dimension: #timewindows X #channels)
  55. % power_array: Matrix containing the PeakPower values (dimension: #timewindows X #channels)
  56. % combo_array: Matrix containing the QualityMask values (dimension: #timewindows X #channels)
  57. % combo_array_expanded: Matrix containing the QualityMask values for the advanced mode (#timewindows X #channels)
  58. % bad_links: List of the channels (averaged across timewindows) below the 'qualityThreshold' value
  59. % bad_windows: List of the timewindows (averaged across channels) below the 'qualityThreshold' value
  60. % sampPerWindow: Samples within a time window
  61. % fs: Sampling frequency
  62. % n_windows: Number of time windows
  63. % cardiac_data: Filtered version of the fNIRS data (dimension: #WLs X #samples X #channels)
  64. % good_combo_link: List of the channels (averaged across the time windows) above the 'qualityThreshold' value
  65. % good_combo_window: List of the time windows (averaged across the channels) above the 'qualityThreshold' value
  66. % woi: Data structure cointaining the Windows of Interest information (epochs of interest throughout the recording)
  67. % MeasListAct: Array mask of the channels achieving the required level of quality (length: #Channels X #WLs)
  68. % REMOVE THE .git FOLDERS
  69. % qtpath = mfilename('fullpath');
  70. % qtpath = qtpath(1:strfind(qtpath,[filesep 'qtnirs']));
  71. % pathCell = regexp(path, pathsep, 'split');
  72. % if ispc % Windows is not case-sensitive
  73. % onPath = any(strcmpi(qtpath, pathCell));
  74. % else
  75. % onPath = any(strcmp(qtpath, pathCell));
  76. % end
  77. % %cd(qtpath(1:end-7))
  78. % % Add that folder plus all subfolders to the path.
  79. % %addpath(pwd);
  80. % if ~onPath
  81. % addpath(genpath(qtpath));
  82. % end
  83. %
  84. % if nargin < 1
  85. % qtnirsLoadFileGUI(pwd);
  86. % return;
  87. % end
  88. if exist('dotNirsFilePath','var')==0
  89. dotNirsFilePath = pwd;
  90. end
  91. if ischar(dotNirsFilePath)
  92. if isfile(dotNirsFilePath)
  93. [filepath,name,ext] = fileparts(dotNirsFilePath);
  94. switch ext
  95. case '.nirs'
  96. rawNirs = load(dotNirsFilePath,'-mat');
  97. case '.snirf'
  98. rawSnirf = SnirfClass(dotNirsFilePath);
  99. rawNirs.d = rawSnirf.Get_d;
  100. %rawNirs.s = rawSnirf.Get_s;
  101. %rawNirs.t = rawSnirf.Get_t;
  102. rawNirs.t = rawSnirf.data.time;
  103. rawNirs.s = rawSnirf.GetStims(rawNirs.t);
  104. rawNirs.SD = rawSnirf.Get_SD;
  105. rawNirs.aux = rawSnirf.GetAux;
  106. case '.mat' % NeuroDOT format
  107. rawNdot = load(dotNirsFilePath,'-mat');
  108. rawNirs.d = rawNdot.data';
  109. rawNirs.t = 0:1/rawNdot.info.system.framerate:(size(rawNdot.data,2)-1)/rawNdot.info.system.framerate;
  110. s_temp = zeros(size(rawNdot.data,2),max(rawNdot.info.paradigm.synchtype));
  111. for pulse = 1:size(s_temp,2)
  112. varname = ['Pulse_' num2str(pulse)];
  113. s_temp(rawNdot.info.paradigm.synchpts(rawNdot.info.paradigm.(varname)),pulse) = 1;
  114. end
  115. rawNirs.s = s_temp;
  116. rawNirs.SD.nScrs = rawNdot.info.io.Ns;
  117. rawNirs.SD.nDets = rawNdot.info.io.Nd;
  118. rawNirs.SD.Lambda = unique(rawNdot.info.pairs.lambda);
  119. rawNirs.SD.SrcPos2 = rawNdot.info.optodes.spos2;
  120. rawNirs.SD.DetPos2 = rawNdot.info.optodes.dpos2;
  121. rawNirs.SD.SrcPos3 = rawNdot.info.optodes.spos3;
  122. rawNirs.SD.DetPos3 = rawNdot.info.optodes.dpos3;
  123. rawNirs.SD.MeasList = [rawNdot.info.pairs.Src rawNdot.info.pairs.Det ones(length(rawNdot.info.pairs.WL),1) rawNdot.info.pairs.WL] ;
  124. otherwise
  125. error('The input file should be a .nirs file format');
  126. end
  127. % if strcmpi(ext,'.nirs')
  128. % rawNirs = load(dotNirsFilePath,'-mat');
  129. % else
  130. % error('The input file should be a .nirs file format');
  131. % %We should check that the required variables are in the file
  132. % end
  133. elseif isfolder(dotNirsFilePath)
  134. disp(['The input data is a folder. ',...
  135. 'All .nirs files inside ',dotNirsFilePath,' will be evaluated.']);
  136. qtnirsLoadFileGUI(dotNirsFilePath);
  137. return;
  138. else
  139. error('The input path does not exist.');
  140. end
  141. elseif isstruct(dotNirsFilePath)
  142. rawNirs = dotNirsFilePath;
  143. flagValidStruct = (isfield(rawNirs,'d') && ...
  144. isfield(rawNirs,'t') && ...
  145. isfield(rawNirs,'SD') && ...
  146. (isfield(rawNirs,'StimDesign') || isfield(rawNirs,'s')));
  147. if flagValidStruct == true
  148. filepath = pwd;
  149. name = 'QTNIRSAnalized';
  150. ext = '.nirs';
  151. else
  152. error(['The input data does not have the required fields (t, SD, s).']);
  153. end
  154. elseif isa(dotNirsFilePath,'nirs.core.Data')
  155. rawNirs = struct;
  156. rawNirs.SD = nirs.util.probe2sd( dotNirsFilePath.probe );
  157. rawNirs.d = dotNirsFilePath.data;
  158. %is it OD data?
  159. crit_od_1 = false;
  160. crit_od_2 = false;
  161. % Mean around zero
  162. if max(mean(rawNirs.d))<0.1 %is the max mean lower than 0.1
  163. crit_od_1 = true;
  164. end
  165. % Negative values (other than measurement errors)
  166. % is the number of negative values greater than the number of channels (N_ch)?
  167. % this allows to consider a max of N_ch wrong negative raw values
  168. if length(find(rawNirs.d(:)<0)) > size(rawNirs.d,2)
  169. crit_od_2 = true;
  170. end
  171. if crit_od_1 && crit_od_2
  172. rawNirs.procResult.dod = rawNirs.d;
  173. else
  174. rawNirs.procResult.dod = [];
  175. end
  176. rawNirs.t = dotNirsFilePath.time;
  177. rawNirs.s = false(size(rawNirs.t));
  178. for icond = 1:length(dotNirsFilePath.stimulus.keys)
  179. stim = dotNirsFilePath.stimulus( dotNirsFilePath.stimulus.keys{icond} );
  180. rawNirs.s = rawNirs.s | stim.getStimVector( rawNirs.t );
  181. end
  182. rawNirs.s=1*rawNirs.s;
  183. rawNirs.aux=rawNirs.s;
  184. filepath = pwd;
  185. name = 'QTNIRSAnalized';
  186. ext = '.nirs';
  187. elseif isa(dotNirsFilePath,'SnirfClass')
  188. rawSnirf = dotNirsFilePath;
  189. rawNirs.d = rawSnirf.Get_d;
  190. %rawNirs.s = rawSnirf.Get_s;
  191. %rawNirs.t = rawSnirf.Get_t;
  192. rawNirs.t = rawSnirf.data.time;
  193. rawNirs.s = rawSnirf.GetStims(rawNirs.t);
  194. rawNirs.SD = rawSnirf.Get_SD;
  195. rawNirs.aux = rawSnirf.GetAux;
  196. filepath = pwd;
  197. name = 'SnirfClass';
  198. ext = '.snirf';
  199. else
  200. disp('Filetype is not valid.');
  201. end
  202. propertyArgIn = varargin;
  203. while length(propertyArgIn) >= 2
  204. prop = propertyArgIn{1};
  205. val = propertyArgIn{2};
  206. propertyArgIn = propertyArgIn(3:end);
  207. switch prop
  208. case 'freqCut'
  209. if isfloat(val) && length(val)==2
  210. fcut_ = [min(val) max(val)];
  211. end
  212. case 'window'
  213. if length(val)==1
  214. window_ = ceil(val);
  215. end
  216. case 'overlap'
  217. if isfloat(val) && val >= 0 && val <= 1
  218. overlap_ = val;
  219. end
  220. case 'qualityThreshold'
  221. if isfloat(val) && val >= 0 && val <= 1
  222. q_threshold = val;
  223. end
  224. case 'sciThreshold'
  225. if isfloat(val) && val >= 0 && val <= 1
  226. sci_threshold = val;
  227. end
  228. case 'pspThreshold'
  229. if isfloat(val) && val >= 0 && val <= 1
  230. psp_threshold = val;
  231. end
  232. case 'conditionsMask'
  233. if ischar(val)
  234. switch val
  235. case 'all'
  236. cond_mask = ones(1,size(rawNirs.s,2));
  237. case 'resting'
  238. cond_mask = val;
  239. otherwise
  240. warning(['Value ',val,' in "cond_mask" parameter not valid.',...
  241. 'Using the complete scan time.']);
  242. cond_mask = 'resting';
  243. end
  244. elseif isnumeric(val)
  245. if ~(any(val>1 | val<0))
  246. cond_mask = val;
  247. else
  248. warning(['Value ',num2str(val),' not valid, use only binary values (0/1).',...
  249. 'Using the complete scan time.']);
  250. cond_mask = 'resting';
  251. end
  252. end
  253. case 'lambdaMask'
  254. errFlag = false;
  255. if ~(any(val>1 | val<0))
  256. if length(val) ~= length(rawNirs.SD.Lambda)
  257. warning(['The number of elements in the "lambdaMask" mask',...
  258. ' does not match with the number of WLs in the scan.',...
  259. ' Using the first two WLs.']);
  260. errFlag = true;
  261. end
  262. if sum(val)~=2
  263. warning(['Incorrect number of "1" in the "lambdaMask" mask.',...
  264. ' Set ONLY two vaules to "1". Using the first two WLs.']);
  265. errFlag = true;
  266. end
  267. if ~errFlag
  268. lambda_mask_ = logical(val);
  269. lambdas_ = find(lambda_mask_);
  270. end
  271. else
  272. warning(['Elements in the "lambdaMask" mask',...
  273. ' must be "1" and/or "0". Using the first two WLs.']);
  274. end
  275. case 'dodFlag'
  276. if val == 1
  277. if isfield(rawNirs,'procResult') && ~isempty(rawNirs.procResult.dod)
  278. dodFlag_ = 1;
  279. else
  280. dodFlag_ = 0;
  281. warning('OD data is not available, I will use the raw data.');
  282. end
  283. else
  284. dodFlag_ = 0;
  285. end
  286. case 'guiFlag'
  287. if val == 1
  288. guiFlag_ = 1;
  289. else
  290. guiFlag_ = 0;
  291. end
  292. end
  293. end
  294. frequency_samp = 1/mean(diff(rawNirs.t));
  295. % Creating 's' variable (stimuli matrix) from the information in StimDesign
  296. if ~isfield(rawNirs,'s')
  297. if isfield(rawNirs,'StimDesign')
  298. nStim = length(rawNirs.StimDesign);
  299. sTmp = zeros(size(rawNirs.d,1),nStim);
  300. for iStim = 1:nStim
  301. for iOnset=1:length(rawNirs.StimDesign(iStim).onset)
  302. onsetTmp = floor(rawNirs.StimDesign(iStim).onset(iOnset) * frequency_samp);
  303. durTmp = floor(rawNirs.StimDesign(iStim).dur(iOnset)* frequency_samp);
  304. %sTmp(floor(rawNirs.StimDesign(iStim).onset(iOnset) * frequency_samp),iStim) = 1;
  305. sTmp(onsetTmp:(onsetTmp+durTmp),iStim) = 1;
  306. end
  307. end
  308. rawNirs.s = sTmp;
  309. clear sTmp;
  310. else
  311. error('Stimuli information is not available.');
  312. end
  313. end
  314. if ~exist('fcut_','var')
  315. fcut_ = [0.5 2.5];
  316. end
  317. if ~exist('window_','var')
  318. window_ = 5;
  319. end
  320. if ~exist('overlap_','var')
  321. overlap_ = 0;
  322. end
  323. if ~exist('q_threshold','var')
  324. q_threshold = 0.75;
  325. end
  326. if ~exist('sci_threshold','var')
  327. sci_threshold = 0.8;
  328. end
  329. if ~exist('psp_threshold','var')
  330. psp_threshold = 0.1;
  331. end
  332. if ~exist('cond_mask','var') || strcmp(cond_mask,'all')
  333. cond_mask = ones(1,size(rawNirs.s,2));
  334. end
  335. if ~exist('lambda_mask_','var')
  336. lambdas_ = unique(rawNirs.SD.MeasList(:,4))';
  337. lambdas_ = lambdas_(1:2);
  338. lambda_mask_ = true(1,length(lambdas_));
  339. if length(lambda_mask_) ~= length(rawNirs.SD.Lambda)
  340. for ii=3:length(rawNirs.SD.Lambda)
  341. lambda_mask_(end+1) = 0;
  342. end
  343. end
  344. end
  345. if ~exist('dodFlag_','var')
  346. dodFlag_ = -1;
  347. end
  348. if ~exist('guiFlag_','var')
  349. guiFlag_ = 1;
  350. end
  351. %------ Sorting for nirstoolbox compatibility ------
  352. varNames = {'source','detector','dummy','type'};
  353. MeasList_table = table(rawNirs.SD.MeasList(:,1),...
  354. rawNirs.SD.MeasList(:,2),...
  355. rawNirs.SD.MeasList(:,3),...
  356. rawNirs.SD.MeasList(:,4),...
  357. 'VariableNames',varNames);
  358. colsToSortBy = {'source', 'detector', 'type'};
  359. [MeasList_table, idxML] = sortrows(MeasList_table, colsToSortBy);
  360. rawNirs.SD.MeasList = table2array(MeasList_table);
  361. rawNirs.d = rawNirs.d(:,idxML);
  362. if dodFlag_ == 1
  363. rawNirs.procResult.dod = rawNirs.procResult.dod(:,idxML);
  364. end
  365. %---------------------------------------------------
  366. nirsplot_parameters.dotNirsPath = filepath;
  367. nirsplot_parameters.dotNirsFile = name;
  368. nirsplot_parameters.dotNirsExt = ext;
  369. nirsplot_parameters.fcut = fcut_;
  370. nirsplot_parameters.window = window_;
  371. nirsplot_parameters.overlap = overlap_;
  372. nirsplot_parameters.lambda_mask = lambda_mask_;
  373. nirsplot_parameters.lambdas = lambdas_;
  374. nirsplot_parameters.dodFlag = dodFlag_;
  375. nirsplot_parameters.mergewoi_flag = false;
  376. nirsplot_parameters.quality_threshold = q_threshold;
  377. nirsplot_parameters.sci_threshold = sci_threshold;
  378. nirsplot_parameters.psp_threshold = psp_threshold;
  379. % Bug found by Benjamin Zinszer (miscalculation in the number of channels)
  380. nirsplot_parameters.n_channels = size(rawNirs.d,2)/length(rawNirs.SD.Lambda);
  381. if isfield(rawNirs.SD,'SrcPos')
  382. nirsplot_parameters.n_sources = size(rawNirs.SD.SrcPos,1);
  383. nirsplot_parameters.n_detectors = size(rawNirs.SD.DetPos,1);
  384. else
  385. nirsplot_parameters.n_sources = size(rawNirs.SD.SrcPos2,1);
  386. nirsplot_parameters.n_detectors = size(rawNirs.SD.DetPos2,1);
  387. end
  388. nirsplot_parameters.s = rawNirs.s;
  389. nirsplot_parameters.t = rawNirs.t;
  390. nirsplot_parameters.fs = frequency_samp;
  391. nirsplot_parameters.mergewoiFlag = true;
  392. nirsplot_parameters.cond_mask = cond_mask;
  393. nirsplot_parameters.save_report_table = false;
  394. nirsplot_parameters.sclAlpha = 0.65;
  395. nirsplot_parameters.rectangle_line_width = 1.2;
  396. nirsplot_parameters.guiFlag = guiFlag_;
  397. % Call the GUI for parameter inputs
  398. S=dbstack;
  399. if guiFlag_ == 1
  400. if length(S)== 1
  401. qtnirsLoadFileGUI(nirsplot_parameters)
  402. end
  403. % Create GUI
  404. prev_window = findall(groot,'Type','Figure');
  405. if ~isempty(prev_window)
  406. for ifig=1:length(prev_window)
  407. if strcmp(prev_window(ifig).Name,'QT-NIRS-View')==1
  408. close(prev_window(ifig));
  409. elseif contains(prev_window(ifig).Name,'Homer3')==1
  410. qtnirsLoadFileGUI(nirsplot_parameters)
  411. end
  412. end
  413. end
  414. [main_fig_axes,main_fig] = createGUI();
  415. else
  416. main_fig = figure('Units','normalized',...
  417. 'Visible','off','Name','QT-NIRS-View',...
  418. 'NumberTitle','off','MenuBar','none');
  419. main_fig_axes = [];
  420. end
  421. nirsplot_parameters.main_fig_axes = main_fig_axes;
  422. setappdata(main_fig,'nirsplot_parameters',nirsplot_parameters);
  423. switch ext
  424. case '.nirs'
  425. setappdata(main_fig,'rawNirs',rawNirs);
  426. case '.snirf'
  427. %setappdata(main_fig,'rawNirs',rawSnirf);
  428. setappdata(main_fig,'rawNirs',rawNirs);
  429. case '.mat'
  430. setappdata(main_fig,'rawNirs',rawNirs);
  431. end
  432. % Computation
  433. [quality_matrices] = qualityCompute(main_fig);
  434. nirsplot_parameters.quality_matrices = quality_matrices;
  435. setappdata(main_fig,'nirsplot_parameters',nirsplot_parameters);
  436. if guiFlag_ == 1
  437. main_fig.Visible = 'on';
  438. hideMACheckB = findobj('Tag','hideMACheckB');
  439. updateQPlots(hideMACheckB,[]);
  440. %rawNT = nirs.io.loadDotNirs(dotNirsFilePath,true);
  441. %rawNT.draw(1:(nirsplot_parameters.n_channels * 2),[],main_fig_axes.inspector);
  442. else
  443. close(main_fig);
  444. end
  445. report_table = [];
  446. if nirsplot_parameters.save_report_table == true
  447. report_table = saveQuality(quality_matrices);
  448. end
  449. % Wait for calls
  450. %% -------------------------------------------------------------------------
  451. function [main_fig_axes,main_fig] = createGUI()
  452. % Main figure container
  453. pos.main = [0.20 0.05 0.75 0.85]; % left, bottom, width, height
  454. main_fig = figure('Units','normalized',...
  455. 'Position',pos.main,'Visible','off',...
  456. 'Name','QT-NIRS-View','NumberTitle','off','MenuBar','none','Toolbar','figure');
  457. % Axes
  458. % SCI
  459. myAxDim.width = 0.9;
  460. myAxDim.height = (1/4)*0.75; % Four axes over the 80% of the figure
  461. myAxDim.xSep = 0.04;
  462. myAxDim.ySep = (1 - myAxDim.height*4) / 5;
  463. pos.inspAx = [myAxDim.xSep,myAxDim.ySep+(0*(myAxDim.height+myAxDim.ySep)),...
  464. myAxDim.width,myAxDim.height];
  465. main_fig_axes.inspector = axes(main_fig,'Units','normalized',...
  466. 'Position',pos.inspAx,...
  467. 'Title','Inspector');
  468. main_fig_axes.inspector.XLabel.String = 'Time (s)';
  469. main_fig_axes.inspector.YLabel.String = 'Channel #';
  470. pos.comboAx = [myAxDim.xSep,myAxDim.ySep+(1.05*(myAxDim.height+myAxDim.ySep)),...
  471. myAxDim.width,myAxDim.height];
  472. main_fig_axes.combo = axes(main_fig,'Units','normalized',...
  473. 'Position',pos.comboAx,...
  474. 'Title','Overall quality');
  475. main_fig_axes.combo.YLabel.String = 'Channel #';
  476. main_fig_axes.combo.YLabel.FontWeight = 'bold';
  477. colorbar(main_fig_axes.combo,'Visible','off','Tag','colorb_combo')
  478. pos.powerAx = [myAxDim.xSep,myAxDim.ySep+(2*(myAxDim.height+myAxDim.ySep)),...
  479. myAxDim.width,myAxDim.height];
  480. main_fig_axes.power = axes(main_fig,'Units','normalized',...
  481. 'Position',pos.powerAx,...
  482. 'Title','Power peak');
  483. main_fig_axes.power.YLabel.String = 'Channel #';
  484. main_fig_axes.power.YLabel.FontWeight = 'bold';
  485. colorbar(main_fig_axes.power,'Visible','off','Tag','colorb_power')
  486. pos.sciAx = [myAxDim.xSep,myAxDim.ySep+(3*(myAxDim.height+myAxDim.ySep)),...
  487. myAxDim.width,myAxDim.height];
  488. main_fig_axes.sci = axes(main_fig,'Units','normalized',...
  489. 'Position',pos.sciAx,...
  490. 'Title','SCI');
  491. main_fig_axes.sci.YLabel.String = 'Channel #';
  492. main_fig_axes.sci.YLabel.FontWeight = 'bold';
  493. colorbar(main_fig_axes.sci,'Visible','on','Tag','colorb_sci')
  494. pos.inspectBtn = [myAxDim.xSep, (myAxDim.height+myAxDim.ySep)*1.025,...
  495. 0.08, myAxDim.ySep*0.7];
  496. uicontrol(main_fig,'Style', 'pushbutton', 'String', 'Inspect',...
  497. 'FontSize',12,'FontWeight','bold','Units','normalized','Position', pos.inspectBtn,...
  498. 'Callback', @inspectActive,'Tag','inspectBtn');
  499. pos.helpBtn = [pos.inspectBtn(1)+pos.inspectBtn(3)+myAxDim.xSep,...
  500. pos.inspectBtn(2),0.05,pos.inspectBtn(4)];
  501. % uicontrol(main_fig,'Style','pushbutton','String','?',...
  502. % 'FontSize',12,'FontWeight','bold','Units','normalized','Position',...
  503. % pos.helpBtn,'Callback', @showHelp,'Tag','helpBtn');
  504. pos.chSelBtn = [pos.inspectBtn(1)+pos.inspectBtn(3)+myAxDim.xSep,...
  505. pos.inspectBtn(2),0.15,pos.inspectBtn(4)];
  506. uicontrol(main_fig,'Style','pushbutton','String','Channel selection',...
  507. 'FontSize',12,'FontWeight','bold','Units','normalized','Position',...
  508. pos.chSelBtn,'Callback', @selectGoodChannels,'Tag','chSelBtn');
  509. % pos.woiSelBtn = [(pos.chSelBtn(1)+pos.chSelBtn(3))*1.15,...
  510. % pos.inspectBtn(2),0.15,pos.inspectBtn(4)];
  511. % woiSelBtn = uicontrol(mainFig,'Style','pushbutton','String','WOI selection',...
  512. % 'FontSize',14,'FontWeight','bold','Units','normalized','Position',...
  513. % pos.woiSelBtn,'Callback', @selectGoodWOI);
  514. pos.HideMA = [pos.chSelBtn(1)+pos.chSelBtn(3)+myAxDim.xSep,...
  515. pos.inspectBtn(2),...
  516. 0.1,...
  517. pos.inspectBtn(4)];
  518. uicontrol(main_fig,'Style','checkbox','String','Hide MAs',...
  519. 'FontSize',12,'FontWeight','bold','Units','normalized','Position',...
  520. pos.HideMA,'Callback', @updateQPlots,'Tag','hideMACheckB');
  521. pos.SaveBtn = [pos.HideMA(1)+pos.HideMA(3)+myAxDim.xSep,...
  522. pos.inspectBtn(2),0.1,pos.inspectBtn(4)];
  523. uicontrol(main_fig,'Style','pushbutton','String','Save .nirs',...
  524. 'FontSize',12,'FontWeight','bold','Units','normalized','Position',...
  525. pos.SaveBtn,'Callback', @save2dotnirs, 'Tag','saveBtn','Enable','off');
  526. pos.AdvView = [pos.SaveBtn(1)+pos.SaveBtn(3)+myAxDim.xSep,...
  527. pos.inspectBtn(2),...
  528. 0.1,...
  529. pos.inspectBtn(4)];
  530. uicontrol(main_fig,'Style','checkbox','String','Advanced mode',...
  531. 'FontSize',12,'FontWeight','bold','Units','normalized','Position',...
  532. pos.AdvView,'Callback', @updateQPlots,'Tag','advModeCheckB');
  533. %main_fig.Visible = 'on';
  534. end
  535. %% -------------------------------------------------------------------------
  536. function showHelp(source,event)
  537. helpFig = figure('Units','normalized',...
  538. 'Visible','off','Position',[0.3,0.3,0.3,0.2],...
  539. 'Name','NIRSPlot Help','NumberTitle','off','MenuBar','none');
  540. helpStr = sprintf(['Controls\nLeft-click: Select a window and channel \n',...
  541. 'Right-click: Select the complete channel \n',...
  542. 'Up|Down key: move up/down one channel \n',...
  543. 'Left|Right key: move forward/backward one window \n',...
  544. 'ESC key: exit from the Inspector mode']);
  545. pos.helpTxt = [0.1,0,0.9,0.9];
  546. uicontrol(helpFig,'Style','text','String',helpStr,...
  547. 'FontSize',14,'Units','normalized','Position',pos.helpTxt,...
  548. 'HorizontalAlignment','left');
  549. helpFig.Visible='on';
  550. end
  551. %% -------------------------------------------------------------------------
  552. function inspectActive(source,event)
  553. nirsplot_param = getappdata(source.Parent,'nirsplot_parameters');
  554. n_channels = nirsplot_param.n_channels;
  555. qMats = nirsplot_param.quality_matrices;
  556. overlap_samples = qMats.overlap_samples;
  557. s = nirsplot_param.s;
  558. t = nirsplot_param.t;
  559. allowed_samp = qMats.allowed_samp;
  560. button = 0;
  561. flagDispWindow = false;
  562. pastChannel = 0;
  563. pastWindow = 0;
  564. while button ~= 27
  565. [iWindow,iChannel,button] = my_ginput(1);
  566. iWindow = floor(iWindow);
  567. iChannel = floor(iChannel);
  568. switch button
  569. case 1
  570. flagDispWindow = true;
  571. case 3
  572. %xLimWindow = [1,(qMats.sampPerWindow*qMats.n_windows)];
  573. xLimWindow = [1,allowed_samp];
  574. pastChannel = iChannel;
  575. flagDispWindow = false;
  576. case 28 % left-arrow key
  577. if flagDispWindow==true
  578. iWindow = pastWindow - 1;
  579. end
  580. iChannel = pastChannel;
  581. case 29 % right-arrow key
  582. if flagDispWindow==true
  583. iWindow = pastWindow + 1;
  584. end
  585. iChannel = pastChannel;
  586. case 30 % up-arrow key
  587. if flagDispWindow==true
  588. iChannel = pastChannel - 1;
  589. iWindow = pastWindow;
  590. else
  591. iChannel = pastChannel - 1;
  592. end
  593. case 31 % down-arrow key
  594. if flagDispWindow==true
  595. iChannel = pastChannel + 1;
  596. iWindow = pastWindow;
  597. else
  598. iChannel = pastChannel + 1;
  599. end
  600. end
  601. if flagDispWindow == true
  602. %xLimWindow = [(qMats.sampPerWindow*iWindow)+1,...
  603. % qMats.sampPerWindow*(iWindow+1)];
  604. %xLimWindow = [(qMats.sampPerWindow*(iWindow-1))+1,...
  605. % (qMats.sampPerWindow*iWindow)];
  606. %xLimWindow = [((qMats.sampPerWindow-overlap_samples)*(iWindow-1))+overlap_samples+1,...
  607. % ((qMats.sampPerWindow-overlap_samples)*iWindow+overlap_samples)];
  608. %xLimWindow = [(iWindow-1)*qMats.sampPerWindow-(iWindow-1)*(qMats.overlap_samples)+1,...
  609. % iWindow*qMats.sampPerWindow-(iWindow-1)*(qMats.overlap_samples)];
  610. if nirsplot_param.overlap~=0
  611. if mod(iWindow,2)==0
  612. jj = floor((iWindow-1)/2)+1;
  613. xLimWindow = [(jj-1)*qMats.sampPerWindow+1 , jj*qMats.sampPerWindow];
  614. xLimWindow = xLimWindow + qMats.overlap_samples ;
  615. else
  616. jj = floor(iWindow/2)+1;
  617. xLimWindow = [(jj-1)*qMats.sampPerWindow+1 , jj*qMats.sampPerWindow];
  618. end
  619. else
  620. xLimWindow = [(iWindow-1)*qMats.sampPerWindow+1 , iWindow*qMats.sampPerWindow];
  621. end
  622. %disp(['xLimWindow:',num2str(xLimWindow(1)),'-',num2str(xLimWindow(2))]);
  623. end
  624. if button ~=27
  625. if iChannel>0 && iChannel<=n_channels && iWindow>0 && iWindow<=qMats.n_windows
  626. updateIPlot(source,iChannel,xLimWindow,iWindow,s,t);
  627. pastWindow = iWindow;
  628. pastChannel = iChannel;
  629. end
  630. end
  631. end
  632. end
  633. %% -------------------------------------------------------------------------
  634. function updateQPlots(source,event)
  635. % UpdatePlot updates the quality plots with the 'qualityMats' input arg
  636. % bad channels are ploted according to 'plot_bad' flag
  637. nirsplot_param = getappdata(source.Parent,'nirsplot_parameters');
  638. qMats = nirsplot_param.quality_matrices;
  639. myAxes = nirsplot_param.main_fig_axes;
  640. n_channels = nirsplot_param.n_channels;
  641. overlap = nirsplot_param.overlap;
  642. woi = nirsplot_param.quality_matrices.woi;
  643. sclAlpha = nirsplot_param.sclAlpha;
  644. window_time = nirsplot_param.window;
  645. sciThrld = nirsplot_param.sci_threshold;
  646. pspThrld = nirsplot_param.psp_threshold;
  647. raw = getappdata(source.Parent,'rawNirs');
  648. mydivmap = [ 0 0.2706 0.1608
  649. 0 0.4078 0.2157
  650. 0.1373 0.5176 0.2627
  651. 0.2549 0.6706 0.3647
  652. 0.4706 0.7765 0.4745
  653. 0.5765 0.8235 0.5176
  654. 0.6784 0.8667 0.5569
  655. 0.8510 0.9412 0.6392
  656. 0.9686 0.9882 0.7255
  657. 1.0000 1.0000 0.8980];
  658. %Unpacking
  659. sci_array = qMats.sci_array;
  660. power_array = qMats.power_array;
  661. combo_array = qMats.combo_array;
  662. combo_array_expanded = qMats.combo_array_expanded;
  663. woiMatrgb = zeros(n_channels,qMats.n_windows,3);
  664. woiMatrgb(:,:,:) = repmat(~woi.mat,1,1,3)*(hex2dec('bf')/255);
  665. alphaMat = ~woi.mat * sclAlpha;
  666. if strcmp(source.Tag,'hideMACheckB')
  667. hideMAVal = source.Value;
  668. advModeObj = source.Parent.findobj('Tag','advModeCheckB');
  669. advModeVal = advModeObj.Value;
  670. else
  671. advModeVal = source.Value;
  672. hideMA = source.Parent.findobj('Tag','hideMACheckB');
  673. hideMAVal = hideMA.Value;
  674. end
  675. %mygray = [0 0 0; repmat([0.7 0.7 0.7],100,1); 1 1 1];
  676. %mymap = [0 0 0;repmat([1 0 0],100,1);1 1 1 ];
  677. overlap_samples_ = nirsplot_param.window*nirsplot_param.fs*nirsplot_param.overlap;
  678. window_samples_ = nirsplot_param.window*nirsplot_param.fs;
  679. n_windows_ = (length(raw.t)-overlap_samples_)/(window_samples_-overlap_samples_);
  680. %colorb_sci = findobj('Tag','colorb_sci');
  681. %-
  682. % WE USE OPTION 1, BUT ONLY NEED TO "EXTEND" THE COMBO VIEW
  683. sci_mask = sci_array>=sciThrld;
  684. power_mask = power_array>=pspThrld;
  685. % Scalp Contact Index
  686. imagesc(myAxes.sci,sci_mask);
  687. colormap(myAxes.sci,[0 0 0; 1 1 1]);
  688. myAxes.sci.CLim = [0,1];
  689. colorbar(myAxes.sci,'eastoutside',...
  690. 'Tag','colorb_sci',...
  691. 'Ticks',[0.25 0.75],...
  692. 'Limits',[0,1],...
  693. 'TickLabels',{'Bad','Good'});
  694. % Power peak
  695. imagesc(myAxes.power,power_mask);
  696. colormap(myAxes.power,[0 0 0; 1 1 1]);
  697. myAxes.power.CLim = [0,1];
  698. colorbar(myAxes.power,'eastoutside',...
  699. 'Tag','colorb_psp',...
  700. 'Ticks',[0.25 0.75],...
  701. 'Limits',[0,1],...
  702. 'TickLabels',{'Bad','Good'});
  703. % Combo quality
  704. if ~hideMAVal
  705. imagesc(myAxes.combo,combo_array_expanded);
  706. myAxes.combo.CLim = [0, 4];
  707. %myAxes.combo.YLim =[1, n_channels];
  708. %myAxes.combo.XLim =[1, size(combo_array,2)];
  709. %colormap(myAxes.combo,[0 0 0;1 1 1]);
  710. % SCI,Power combo_array_expanded QualityColor
  711. % 0,0 0 [0 0 0]
  712. % 0,1 1 [0 0 0]
  713. % 2,0 2 [1 0 0]
  714. % 2,1 3 [1 1 1]
  715. % X,X 4 [0 0 1] Saturation
  716. qualityColor = [0 0 0; 0 0 0; 1 0 0; 1 1 1;0 0 1];
  717. colormap(myAxes.combo,qualityColor);
  718. colorbar(myAxes.combo,"eastoutside","Ticks",[0.7 1.0 2.05 2.75 3.5],...
  719. 'TickLabels',...
  720. {[char(hex2dec('2717')),'SCI ', char(hex2dec('2717')),'Power'],...
  721. [char(hex2dec('2717')),'SCI ', char(hex2dec('2713')),'Power'],...
  722. [char(hex2dec('2713')),'SCI ', char(hex2dec('2717')),'Power'],...
  723. [char(hex2dec('2713')),'SCI ', char(hex2dec('2713')),'Power'],...
  724. 'Saturation'});
  725. else
  726. % Combo quality
  727. imagesc(myAxes.combo,combo_array);
  728. myAxes.combo.CLim = [0, 1];
  729. %myAxes.combo.YLim =[1, n_channels];
  730. myAxes.combo.Colormap = [0 0 0;1 1 1];
  731. tickOffsetWind = 50/nirsplot_param.window;
  732. ticksVals = (0:n_windows_)*window_samples_;
  733. ticksVals = ticksVals(1:tickOffsetWind:length(ticksVals));
  734. ticksVals = floor(ticksVals./window_samples_);
  735. ticksLab = 0:50:nirsplot_param.t(end);
  736. myAxes.combo.XAxis.TickValues=ticksVals(2:end);
  737. myAxes.combo.XAxis.TickLabels=split(num2str(ticksLab(2:end)));
  738. colorbar(myAxes.combo,"eastoutside","Ticks",[0.25 0.75],...
  739. 'Limits',[0,1],'TickLabels',{'Bad','Good'});
  740. end
  741. myAxes.combo.YLabel.String = 'Channel #';
  742. myAxes.combo.YLabel.FontWeight = 'bold';
  743. % For figures MAs detected/undetected
  744. myAxes.combo.YAxis.TickValues = 1:n_channels;
  745. myAxes.combo.YAxis.TickLabels = num2cell([num2str(raw.SD.MeasList(1:length(raw.SD.Lambda):end,1)),repmat('-',n_channels,1),num2str(raw.SD.MeasList(1:length(raw.SD.Lambda):end,2))],2);
  746. myAxes.combo.YAxis.FontSize = 7;
  747. hold(myAxes.sci,'on');
  748. hold(myAxes.power,'on');
  749. hold(myAxes.combo,'on');
  750. % Drawing green bands
  751. imagesc(myAxes.sci,woiMatrgb,'AlphaData',alphaMat);
  752. %hold(myAxes.power,'on');
  753. imagesc(myAxes.power,woiMatrgb,'AlphaData',alphaMat);
  754. %hold(myAxes.combo,'on');
  755. imagesc(myAxes.combo,woiMatrgb,'AlphaData',alphaMat);
  756. %-
  757. if advModeVal
  758. % Scalp Contact Index
  759. imagesc(myAxes.sci,sci_array);
  760. colormap(myAxes.sci,mydivmap);
  761. colorbar(myAxes.sci,'eastoutside',...
  762. 'Tag','colorb_sci',...
  763. 'Ticks',[0 sciThrld 1],...
  764. 'Limits',[0,1],...
  765. 'TickLabels',{'0',['SCIThld:',num2str(sciThrld)],'1'});
  766. % Power peak
  767. imagesc(myAxes.power,power_array);
  768. colormap(myAxes.power,mydivmap);
  769. myAxes.power.CLim = [0,0.5];
  770. colorbar(myAxes.power,'eastoutside',...
  771. 'Tag','colorb_psp',...
  772. 'Ticks',[0 pspThrld 0.5],...
  773. 'Limits',[0,0.5],...
  774. 'TickLabels',{'0',['PSPThld:',num2str(pspThrld)],...
  775. '0.5'});
  776. end
  777. %the next if-else sentence could be ereased
  778. % For visual consistency among axes
  779. myAxes.inspector.YLimMode = 'manual';
  780. myAxes.inspector.YLabel.String = 'Channel #';
  781. myAxes.inspector.XLabel.String = 'Time (s)';
  782. myAxes.inspector.YLabel.FontWeight = 'bold';
  783. myAxes.inspector.XLabel.FontWeight = 'bold';
  784. colorbar(myAxes.inspector,'Visible','off');
  785. end
  786. %% -------------------------------------------------------------------------
  787. function updateIPlot(source,iChannel,xLimWindow,iWindow,s,t)
  788. disp(['channel:' num2str(iChannel)]);
  789. raw = getappdata(source.Parent,'rawNirs');
  790. nirsplot_param = getappdata(source.Parent,'nirsplot_parameters');
  791. qMats = nirsplot_param.quality_matrices;
  792. myAxes = nirsplot_param.main_fig_axes;
  793. n_channels = nirsplot_param.n_channels;
  794. conditions_mask = nirsplot_param.cond_mask;
  795. woi = nirsplot_param.quality_matrices.woi;
  796. fs = nirsplot_param.fs;
  797. fcut = nirsplot_param.fcut;
  798. window_time = nirsplot_param.window;
  799. overlap_samples = qMats.overlap_samples;
  800. rectangle_line_width = nirsplot_param.rectangle_line_width;
  801. sclAlpha = nirsplot_param.sclAlpha;
  802. dViewCheckb = findobj('Tag','hideMACheckB');
  803. myAxes.inspector.XLim= [t(xLimWindow(1)),t(xLimWindow(2))];
  804. YLimStd = [min(qMats.cardiac_data(:,xLimWindow(1):xLimWindow(2),iChannel),[],'all'),...
  805. max(qMats.cardiac_data(:,xLimWindow(1):xLimWindow(2),iChannel),[],'all')]*1.05;
  806. XLimStd = myAxes.inspector.XLim;
  807. % Normalization of cardiac_data between [a,b]
  808. a = -1;
  809. b = 1;
  810. cardiac_wl1_norm = a + (((qMats.cardiac_data(1,xLimWindow(1):xLimWindow(2),iChannel)-YLimStd(1)).*(b-a))./ (YLimStd(2)-YLimStd(1)));
  811. cardiac_wl2_norm = a + (((qMats.cardiac_data(2,xLimWindow(1):xLimWindow(2),iChannel)-YLimStd(1)).*(b-a))./ (YLimStd(2)-YLimStd(1)));
  812. YLimStd = [a,b].*1.05;
  813. cla(myAxes.inspector);
  814. plot(myAxes.inspector,t(xLimWindow(1):xLimWindow(2)),...
  815. cardiac_wl1_norm,'-b');
  816. hold(myAxes.inspector,'on');
  817. plot(myAxes.inspector,t(xLimWindow(1):xLimWindow(2)),...
  818. cardiac_wl2_norm,'-r');
  819. if(isfield(raw.SD,'Lambda'))
  820. WLs = raw.SD.Lambda(nirsplot_param.lambda_mask);
  821. strLgnds = {num2str(WLs(1)),num2str(WLs(2))};
  822. else
  823. strLgnds = {'\lambda 1','\lambda 2'};
  824. end
  825. updateQPlots(dViewCheckb,[]);
  826. %if (xLimWindow(2)-xLimWindow(1)+1) == (qMats.n_windows*qMats.sampPerWindow)
  827. if (xLimWindow(2)-xLimWindow(1)+1) == (qMats.n_windows*(qMats.sampPerWindow-overlap_samples)+overlap_samples)
  828. xRect = 0.5; %Because of the offset at the begining of a window
  829. yRect = iChannel-0.5;
  830. wRect = qMats.n_windows;
  831. hRect = 1;
  832. %poiMatrgb = zeros(n_channels,xLimWindow(2)-overlap_samples,3);
  833. %poiMatrgb(:,:,:) = repmat(repelem(~woi.mat(1,:),qMats.sampPerWindow-overlap_samples),n_channels,1,3).*(hex2dec('bf')/255);
  834. poiMatrgb=repmat(~woi.poi_mat,1,1,3).*(hex2dec('bf')/255);
  835. alphaMat = poiMatrgb(:,:,1) * sclAlpha;
  836. impoiMat = imagesc(myAxes.inspector,'XData',...
  837. [t(xLimWindow(1)),t(xLimWindow(2))],...
  838. 'YData',YLimStd,'CData',poiMatrgb,'AlphaData',alphaMat);
  839. %ticksVals = linspace(0,XLimStd(2),8);
  840. ticksVals = (0:50:nirsplot_param.t(end));
  841. myAxes.inspector.XAxis.TickValues=ticksVals(2:end);
  842. %ticksLab = round(linspace(0,nirsplot_param.t(end),8));
  843. ticksLab = 0:50:nirsplot_param.t(end);
  844. myAxes.inspector.XAxis.TickLabels=split(num2str(ticksLab(2:end)));
  845. % Drawing onsets
  846. if ~ischar(conditions_mask)
  847. c = sum(conditions_mask);
  848. COI = find(conditions_mask);
  849. if c<9
  850. colorOnsets = colorcube(8);
  851. else
  852. colorOnsets = colorcube(c+1);
  853. colorOnsets = colorOnsets(1:end-1,:);
  854. end
  855. for j=1:c
  856. %mapping from 0,1 to 0,25%ofPeakToPeak
  857. yOnset = (s(xLimWindow(1):xLimWindow(2),COI(j))*(YLimStd(2)-YLimStd(1))*0.25)-abs(YLimStd(1));
  858. plot(myAxes.inspector,t(xLimWindow(1):xLimWindow(2)),...
  859. yOnset,'LineWidth',2,...
  860. 'Color',colorOnsets(j,:));
  861. strLgnds(2+j) = {['Cond ',num2str(COI(j))]};
  862. end
  863. end
  864. else
  865. %ticksVals = linspace(myAxes.inspector.XAxis.Limits(1),myAxes.inspector.XAxis.Limits(2),8);
  866. %ticksVals = linspace(myAxes.inspector.XAxis.Limits(1),myAxes.inspector.XAxis.Limits(2),5);
  867. ticksVals = myAxes.inspector.XAxis.Limits(1);
  868. ticksVals = round(ticksVals(1)): (round(ticksVals(1))+window_time);
  869. myAxes.inspector.XAxis.TickValues=ticksVals(1:end);
  870. ticksLab = round(ticksVals);
  871. myAxes.inspector.XAxis.TickLabels=split(num2str(ticksLab(1:end)));
  872. xRect = iWindow-0.5;
  873. yRect = iChannel-0.5;
  874. xQlabels = xRect + 1;
  875. yQlabels = yRect + 1;
  876. wRect = 1;
  877. hRect = 1;
  878. %fprintf('SCI:%.3f \t Power:%.3f\n',qMats.sci_array(iChannel,iWindow),qMats.power_array(iChannel,iWindow));
  879. textHAlign = 'left';
  880. textVAlign = 'top';
  881. if xRect > (qMats.n_windows/2)
  882. textHAlign = 'right';
  883. xQlabels = xRect - 0.5;
  884. end
  885. if yRect > (n_channels/2)
  886. textVAlign = 'bottom';
  887. yQlabels = yRect - 0.5;
  888. end
  889. text(myAxes.power,xQlabels,yQlabels,num2str(qMats.power_array(iChannel,iWindow),'%.3f'),...
  890. 'Color','red','FontSize',10,'FontWeight','bold','BackgroundColor','#FFFF00',...
  891. 'Margin',1,'Clipping','on',...
  892. 'HorizontalAlignment',textHAlign,'VerticalAlignment',textVAlign);
  893. text(myAxes.sci,xQlabels,yQlabels,num2str(qMats.sci_array(iChannel,iWindow),'%.3f'),...
  894. 'Color','red','FontSize',10,'FontWeight','bold','BackgroundColor','#FFFF00',...
  895. 'Margin',1,'Clipping','on',...
  896. 'HorizontalAlignment',textHAlign,'VerticalAlignment',textVAlign);
  897. %--graphical debug
  898. % graphicDebug(qMats.cardiac_data(1,xLimWindow(1):xLimWindow(2),iChannel),...
  899. % qMats.cardiac_data(2,xLimWindow(1):xLimWindow(2),iChannel),fs,fcut);
  900. % figure(source.Parent);
  901. end
  902. myAxes.inspector.YLim = YLimStd;
  903. myAxes.inspector.XLim = XLimStd;
  904. %myAxes.inspector.YLabel.String = ['Channel ', num2str(iChannel)];
  905. myAxes.inspector.YLabel.String = ['S', num2str(raw.SD.MeasList(iChannel*length(raw.SD.Lambda),1)),'-D',num2str(raw.SD.MeasList(iChannel*length(raw.SD.Lambda),2)),'(',num2str(iChannel),')'];
  906. lgn = legend(myAxes.inspector,strLgnds,'Box','off','FontSize',10);
  907. rectangle(myAxes.combo,'Position',[xRect yRect wRect hRect],...
  908. 'EdgeColor','m','FaceColor','none','Linewidth',rectangle_line_width);
  909. rectangle(myAxes.power,'Position',[xRect yRect wRect hRect],...
  910. 'EdgeColor','m','FaceColor','none','Linewidth',rectangle_line_width);
  911. rectangle(myAxes.sci,'Position',[xRect yRect wRect hRect],...
  912. 'EdgeColor','m','FaceColor','none','Linewidth',rectangle_line_width);
  913. end
  914. %% -------------------------------------------------------------------------
  915. function [qualityMats] = qualityCompute(main_fig)
  916. raw = getappdata(main_fig,'rawNirs');
  917. nirsplot_param = getappdata(main_fig,'nirsplot_parameters');
  918. fcut = nirsplot_param.fcut;
  919. window = nirsplot_param.window;
  920. overlap = nirsplot_param.overlap;
  921. lambda_mask = nirsplot_param.lambda_mask;
  922. lambdas = nirsplot_param.lambdas;
  923. n_channels = nirsplot_param.n_channels;
  924. qltyThld = nirsplot_param.quality_threshold;
  925. sciThrld = nirsplot_param.sci_threshold;
  926. pspThrld = nirsplot_param.psp_threshold;
  927. scanInfo = nirsplot_param.dotNirsFile;
  928. dodFlag = nirsplot_param.dodFlag;
  929. if dodFlag == 1
  930. % dm = mean(abs(raw.d),1);
  931. % raw.d = exp(-raw.procResult.dod).*(ones(size(raw.d,1),1)*dm);
  932. raw.d = raw.procResult.dod;
  933. end
  934. % Set the bandpass filter parameters
  935. %fs = 1/mean(diff(raw.t));
  936. fs = nirsplot_param.fs;
  937. n_samples = size(raw.d,1);
  938. fcut_min = fcut(1);
  939. fcut_max = fcut(2);
  940. if fcut_max >= (fs)/2
  941. fcut_max = (fs)/2 - eps;
  942. warning(['The highpass cutoff has been reduced from ',...
  943. num2str(fcut(2)), ' Hz to ', num2str(fcut_max),...
  944. ' Hz to satisfy the Nyquist sampling criterion']);
  945. end
  946. [B1,A1]=butter(1,[fcut_min*(2/fs) fcut_max*(2/fs)]);
  947. nirs_data = zeros(length(lambdas),n_samples,n_channels);
  948. cardiac_data = zeros(length(raw.SD.Lambda),n_samples,n_channels); % Lambdas x time x channels
  949. for j = 1:length(raw.SD.Lambda)
  950. % Filter everything but the cardiac component
  951. idx = find(raw.SD.MeasList(:,4) == j);
  952. nirs_data(j,:,:) = raw.d(:,idx);
  953. filtered_nirs_data=filtfilt(B1,A1,squeeze(nirs_data(j,:,:)));
  954. cardiac_data(j,:,:)=filtered_nirs_data./repmat(std(filtered_nirs_data,0,1),size(filtered_nirs_data,1),1); % Normalized heartbeat
  955. end
  956. overlap_samples = floor(window*fs*overlap);
  957. window_samples = floor(window*fs);
  958. if overlap ==0
  959. n_windows = floor((n_samples)/(window_samples));
  960. else % Valid for overlap=50%
  961. n_windows = 2*floor((n_samples)/(window_samples))-1;
  962. end
  963. cardiac_data = cardiac_data(find(lambda_mask),:,:);
  964. sci_array = zeros(size(cardiac_data,3),n_windows); % Number of optode is from the user's layout, not the machine
  965. power_array = zeros(size(cardiac_data,3),n_windows);
  966. fpower_array = zeros(size(cardiac_data,3),n_windows);
  967. cardiac_windows = zeros(length(lambdas),window_samples,n_channels,n_windows);
  968. for j = 1:n_windows
  969. if overlap~=0
  970. if mod(j,2)==0
  971. jj = floor((j-1)/2)+1;
  972. interval = (jj-1)*window_samples+1 : jj*window_samples;
  973. interval = interval + overlap_samples ;
  974. else
  975. jj = floor(j/2)+1;
  976. interval = (jj-1)*window_samples+1 : jj*window_samples;
  977. end
  978. else
  979. interval = (j-1)*window_samples+1 : j*window_samples;
  980. end
  981. cardiac_windows(:,:,:,j) = cardiac_data(:,interval,:);
  982. % if j<5 || j>(n_windows-4)
  983. % disp(['interval(',num2str(j),'):',num2str(interval(1)),'-',num2str(interval(end))]);
  984. % end
  985. end
  986. for j = 1:n_windows
  987. cardiac_window = cardiac_windows(:,:,:,j);
  988. sci_array_channels = zeros(1,size(cardiac_window,3));
  989. power_array_channels = zeros(1,size(cardiac_window,3));
  990. fpower_array_channels = zeros(1,size(cardiac_window,3));
  991. for k = 1:size(cardiac_window,3) % Channels iteration
  992. %cross-correlate the two wavelength signals - both should have cardiac pulsations
  993. similarity = xcorr(squeeze(cardiac_window(1,:,k)),squeeze(cardiac_window(2,:,k)),'unbiased');
  994. if any(abs(similarity)>eps)
  995. % this makes the SCI=1 at lag zero when x1=x2 AND makes the power estimate independent of signal length, amplitude and Fs
  996. similarity = length(squeeze(cardiac_window(1,:,k)))*similarity./sqrt(sum(abs(squeeze(cardiac_window(1,:,k))).^2)*sum(abs(squeeze(cardiac_window(2,:,k))).^2));
  997. similarity(isnan(similarity)) = 0;
  998. [pxx,f] = periodogram(similarity,hamming(length(similarity)),length(similarity),fs,'power');
  999. [pwrest,idx] = max(pxx(f<fcut_max)); % FIX Make it age-dependent
  1000. sci=similarity(length(squeeze(cardiac_window(1,:,k))));
  1001. power=pwrest;
  1002. fpower=f(idx);
  1003. sci_array_channels(k) = sci;
  1004. power_array_channels(k) = power;
  1005. fpower_array_channels(k) = fpower;
  1006. else
  1007. warning('Similarity results close to zero. This is due to the optical signal hitting noise floor or saturation values.');
  1008. sci_array_channels(k) = 0;
  1009. power_array_channels(k) = 0;
  1010. fpower_array_channels(k) = -1;
  1011. end
  1012. end
  1013. sci_array(:,j) = sci_array_channels; % Adjust not based on machine
  1014. power_array(:,j) = power_array_channels;
  1015. fpower_array(:,j) = fpower_array_channels;
  1016. end
  1017. % Summary analysis
  1018. if (1)
  1019. [woi,allowed_samp] = getWOI(window_samples,n_windows,overlap_samples,nirsplot_param);
  1020. idxPoi = logical(woi.mat(1,:));
  1021. else
  1022. [woi,allowed_samp] = getWOI(window_samples,n_windows,overlap_samples,nirsplot_param);
  1023. woi.mat = ones(n_channels,n_windows)
  1024. allowed_samp = ones(1,window_samples*n_windows);
  1025. woi.poi_mat = repmat(allowed_samp,n_channels,1);
  1026. idxPoi = logical(woi.mat(1,:));
  1027. end
  1028. mean_sci_link = mean(sci_array(:,idxPoi),2);
  1029. std_sci_link = std(sci_array(:,idxPoi),0,2);
  1030. good_sci_link = sum(sci_array(:,idxPoi)>=sciThrld,2)/size(sci_array(:,idxPoi),2);
  1031. mean_sci_window = mean(sci_array(:,idxPoi),1);
  1032. std_sci_window = std(sci_array(:,idxPoi),0,1);
  1033. good_sci_window = sum(sci_array(:,idxPoi)>=sciThrld,1)/size(sci_array(:,idxPoi),1);
  1034. mean_power_link = mean(power_array(:,idxPoi),2);
  1035. std_power_link = std(power_array(:,idxPoi),0,2);
  1036. good_power_link = sum(power_array(:,idxPoi)>=pspThrld,2)/size(power_array(:,idxPoi),2);
  1037. mean_power_window = mean(power_array(:,idxPoi),1);
  1038. std_power_window = std(power_array(:,idxPoi),0,1);
  1039. good_power_window = sum(power_array(:,idxPoi)>=pspThrld,1)/size(power_array(:,idxPoi),1);
  1040. combo_array = (sci_array >= sciThrld) & (power_array >= pspThrld);
  1041. saturat_mat = fpower_array==-1;
  1042. combo_array_expanded = 2*(sci_array >= sciThrld) + (power_array >= pspThrld) +...
  1043. saturat_mat*4;
  1044. mean_combo_link = mean(combo_array,2);
  1045. std_combo_link = std(combo_array,0,2);
  1046. good_combo_link = mean(combo_array(:,idxPoi),2);
  1047. mean_combo_window = mean(combo_array,1);
  1048. std_combo_window = std(combo_array,0,1);
  1049. idx_gcl = good_combo_link>=qltyThld;
  1050. good_combo_window = mean(combo_array(idx_gcl,:),1);
  1051. % Detecting experimental blocks
  1052. exp_blocks = zeros(1,length(woi.start));
  1053. for iblock = 1:length(woi.start)
  1054. block_start_w = woi.start(iblock);
  1055. block_end_w = woi.end(iblock);
  1056. exp_blocks(iblock) = mean(good_combo_window(block_start_w:block_end_w));
  1057. end
  1058. % Detect artifacts and bad links
  1059. bad_links = find(mean_combo_link<qltyThld);
  1060. bad_windows = find(mean_combo_window<qltyThld);
  1061. % Packaging sci, peakpower and combo
  1062. qualityMats.sci_array = sci_array;
  1063. qualityMats.power_array = power_array;
  1064. qualityMats.combo_array = combo_array;
  1065. qualityMats.combo_array_expanded = combo_array_expanded;
  1066. qualityMats.bad_links = bad_links;
  1067. qualityMats.bad_windows = bad_windows;
  1068. qualityMats.sampPerWindow = window_samples;
  1069. qualityMats.fs = fs;
  1070. qualityMats.n_windows = n_windows;
  1071. qualityMats.overlap_samples = overlap_samples;
  1072. qualityMats.cardiac_data = cardiac_data;
  1073. % Bug found by Benjamin Zinszer (miscalculation in the S-D pairs)
  1074. qualityMats.good_combo_link = [raw.SD.MeasList(1:length(raw.SD.Lambda):end,1),...
  1075. raw.SD.MeasList(1:length(raw.SD.Lambda):end,2),good_combo_link];
  1076. qualityMats.good_combo_window = good_combo_window;
  1077. qualityMats.woi = woi;
  1078. qualityMats.allowed_samp = allowed_samp;
  1079. qualityMats.MeasListAct = repelem(idx_gcl,2);%[idx_gcl; idx_gcl];
  1080. qualityMats.MeasList = raw.SD.MeasList;
  1081. qualityMats.thresholds.sci = sciThrld;
  1082. qualityMats.thresholds.peakpower = pspThrld;
  1083. qualityMats.thresholds.quality = qltyThld;
  1084. qualityMats.scanInfo = scanInfo ;
  1085. %
  1086. end
  1087. %% -------------------------------------------------------------------------
  1088. function [woi,allowed_samp] = getWOI(window_samples,n_windows,overlap_samples,nirsplot_parameters)
  1089. % Assuming no overlaped trials
  1090. % The maximum number of allowed samples is window_samples*n_windows to consider
  1091. % an integer number of windows, module(total_samples,n_windows) = 0
  1092. fs = nirsplot_parameters.fs;
  1093. s = nirsplot_parameters.s;
  1094. t = nirsplot_parameters.t;
  1095. mergewoi_flag = nirsplot_parameters.mergewoi_flag;
  1096. n_channels = nirsplot_parameters.n_channels;
  1097. %allowed_samp = n_windows*window_samples;
  1098. %allowed_samp = n_windows*(window_samples-overlap_samples)+overlap_samples;
  1099. if nirsplot_parameters.overlap ~= 0
  1100. allowed_samp = (n_windows*window_samples+window_samples)/2;
  1101. else
  1102. allowed_samp = n_windows*window_samples;
  1103. end
  1104. if strcmp(nirsplot_parameters.cond_mask,'all')
  1105. conditions_mask = ones(1,size(s,2));
  1106. elseif strcmp(nirsplot_parameters.cond_mask,'resting')
  1107. woi = struct;
  1108. woi.mat = ones(n_channels,n_windows);
  1109. woi.poi_mat = ones(n_channels,allowed_samp,1);
  1110. woi.start = 1;
  1111. woi.end = n_windows;
  1112. return
  1113. else
  1114. conditions_mask = logical(nirsplot_parameters.cond_mask);
  1115. end
  1116. poi = sum(s(1:allowed_samp,conditions_mask),2);
  1117. poi = poi(1:allowed_samp);
  1118. % Sometimes 's' variable encodes the stimuli durations by including consecutive
  1119. % values of 1. We are interested on the onsets, then we remove consecutive ones.
  1120. idxpoi = find(poi);
  1121. poi = zeros(size(poi));
  1122. poi(idxpoi(diff([0;idxpoi])>1)) = 1;
  1123. nOnsets = length(find(poi));
  1124. idxStim = find(poi);
  1125. interOnsetTimes = t(idxStim(2:end)) - t(idxStim(1:end-1));
  1126. medIntTime = median(interOnsetTimes);
  1127. iqrIntTime = iqr(interOnsetTimes);
  1128. %blckDurTime = (medIntTime/2) + (0.5*iqrIntTime);
  1129. blckDurTime = medIntTime + (0.5*iqrIntTime);
  1130. blckDurSamp = round(fs*blckDurTime);
  1131. blckDurWind = floor(blckDurSamp/((window_samples-overlap_samples)));% floor(blckDurSamp/window_samples);
  1132. woi = struct('mat',zeros(n_channels,n_windows),...
  1133. 'start',zeros(1,nOnsets),...
  1134. 'end',zeros(1,nOnsets));
  1135. woi_array = zeros(1,n_windows);
  1136. % Since we are relying on windows, we do not need the POIs variables instead
  1137. % we need WOIs variables information
  1138. for i=1:nOnsets
  1139. startPOI = idxStim(i)-blckDurSamp;
  1140. if startPOI < 1
  1141. startPOI = 1;
  1142. end
  1143. startWOI = ceil(startPOI/((window_samples-overlap_samples)));%floor(startPOI/window_samples);
  1144. if startWOI==0
  1145. startWOI = 1;
  1146. end
  1147. endPOI = idxStim(i)+blckDurSamp;
  1148. if endPOI > allowed_samp
  1149. endPOI = allowed_samp;
  1150. end
  1151. endWOI = floor(endPOI/((window_samples-overlap_samples)));%ceil(endPOI/window_samples);
  1152. poi(startPOI:endPOI) = 1;
  1153. woi_array(startWOI:endWOI) = 1;
  1154. woi.start(i) = startWOI;
  1155. woi.end(i) = endWOI;
  1156. end
  1157. % See my comment about the preference of WOIs rather than of POIs, if POI
  1158. % information is needed, uncomment next two lines and return POIs variables
  1159. poi = poi';
  1160. poiMat_ = repmat(poi,n_channels,1);
  1161. woiblank = 0;
  1162. idxInit = [];
  1163. woitmp = woi_array;
  1164. % If the gap's duration between two consecutives blocks of interest is less than the
  1165. % block's average duration, then those two consecutives blocks will merge.
  1166. % This operation has a visual effect (one bigger green block instead of
  1167. % two green blocks with a small gap in between), and for quality
  1168. % results, the windows inside of such a gap are now considered for quality computation.
  1169. for i =1:n_windows
  1170. if woitmp(i) == 0
  1171. if isempty(idxInit)
  1172. idxInit = i;
  1173. end
  1174. woiblank = woiblank +1;
  1175. else
  1176. if ~isempty(idxInit)
  1177. if (woiblank <= blckDurWind)
  1178. woitmp(idxInit:i) = 1;
  1179. end
  1180. woiblank = 0;
  1181. idxInit = [];
  1182. end
  1183. end
  1184. end
  1185. if mergewoi_flag == true
  1186. woi_array = woitmp;
  1187. end
  1188. woi.mat = repmat(woi_array,n_channels,1);
  1189. woi.poi_mat = poiMat_;
  1190. end
  1191. %% -------------------------------------------------------------------------
  1192. function dotNirsOutput = selectGoodChannels(source, events)
  1193. bpGoodQuality(source.Parent);
  1194. uiwait(source.Parent);
  1195. nirsplot_param = getappdata(source.Parent,'nirsplot_parameters');
  1196. if isfield(nirsplot_param.quality_matrices,'active_channels')
  1197. disp(['Threshold was changed to ',num2str(nirsplot_param.quality_threshold)]);
  1198. saveBtn = findobj('Tag','saveBtn');
  1199. saveBtn.Enable = 'on';
  1200. end
  1201. dotNirsOutput = 0;
  1202. end
  1203. %% -------------------------------------------------------------------------
  1204. %!This function is not tested yet!
  1205. function report_table = saveQuality()
  1206. qMats = getappdata(source.Parent,'qualityMats');
  1207. report_table = table({qMats.bad_links'}, {qMats.bad_windows});
  1208. report_table.Properties.VariableNames = {'file_idx','Bad_Links','Bad_Windows'};
  1209. for i=1:size(report_table,1)
  1210. a = report_table.Bad_Links{i};
  1211. b = report_table.Bad_Windows{i};
  1212. a1 = num2str(a);
  1213. b1 = num2str(b);
  1214. report_table.Bad_Links{i} = a1;
  1215. report_table.Bad_Windows{i} = b1;
  1216. end
  1217. writetable(report_table,'Quality_Report.xls');
  1218. end
  1219. %% -------------------------------------------------------------------------
  1220. function saving_status = save2dotnirs(source, events)
  1221. nirsplot_param = getappdata(source.Parent,'nirsplot_parameters');
  1222. active_channels = nirsplot_param.quality_matrices.active_channels;
  1223. dotNirsPath = nirsplot_param.dotNirsPath;
  1224. dotNirsFileName = nirsplot_param.dotNirsFile;
  1225. dotNirsExt = nirsplot_param.dotNirsExt;
  1226. outputFolder = 'qtnirs_proc';
  1227. if ~exist(outputFolder,'dir')
  1228. mkdir(outputFolder);
  1229. end
  1230. switch dotNirsExt
  1231. case '.nirs'
  1232. raw = getappdata(source.Parent,'rawNirs');
  1233. raw.SD.MeasListAct = [active_channels; active_channels];
  1234. raw.tIncMan = ones(length(raw.t),1);
  1235. if ~isfield(raw, 'aux')
  1236. raw.aux = [];
  1237. end
  1238. save([dotNirsPath,filesep,outputFolder,filesep,dotNirsFileName,'_qt-proc.nirs'],...
  1239. '-struct','raw','-MAT');
  1240. case '.snirf'
  1241. raw = getappdata(source.Parent,'rawNirs');
  1242. raw.SD.MeasListAct = [active_channels; active_channels];
  1243. raw.tIncMan = ones(length(raw.t),1);
  1244. if ~isfield(raw, 'aux')
  1245. raw.aux = [];
  1246. end
  1247. snirf_saved = SnirfClass(raw);
  1248. snirf_saved.Save([dotNirsPath,filesep,outputFolder,filesep,dotNirsFileName,'_qt-proc.snirf']);
  1249. end
  1250. %Notify to the user if the new file was succesfully created
  1251. saving_status = exist([dotNirsPath,filesep,outputFolder,filesep,dotNirsFileName,'_qt-proc',dotNirsExt],'file');
  1252. if saving_status
  1253. msgbox('Operation Completed','Success');
  1254. else
  1255. msgbox('Operation Failed','Error');
  1256. end
  1257. end
  1258. %%
  1259. function graphicDebug(window1,window2,fs,fcut)
  1260. %cross-correlate the two wavelength signals - both should have cardiac pulsations
  1261. [similarity,lags] = xcorr(window1,window2,'unbiased');
  1262. if any(abs(similarity)>eps)
  1263. % this makes the SCI=1 at lag zero when x1=x2 AND makes the power estimate independent of signal length, amplitude and Fs
  1264. similarity = length(window1)*similarity./sqrt(sum(abs(window1).^2)*sum(abs(window2).^2));
  1265. else
  1266. warning('Similarity results close to zero');
  1267. end
  1268. [pxx,f] = periodogram(similarity,hamming(length(similarity)),length(similarity),fs,'power');
  1269. f3=figure(3);
  1270. clf(f3);
  1271. subplot(1,3,1);
  1272. plot(window1-2,'k-');
  1273. hold on;
  1274. plot(window2+2,'k--');
  1275. ylabel('Raw intensity','FontSize',15);% x_{\lambda_1}, x_{\lambda_2}');
  1276. legend('$x_{\lambda_1}$', '$x_{\lambda_2}$','Interpreter','latex','FontSize',16);
  1277. ylim([-7 7]);
  1278. subplot(1,3,2);
  1279. plot(f3.Children(1),lags,similarity,'k-');
  1280. yline(0.8,'r--');
  1281. ylim([-1 1]);
  1282. ylabel('$\bar{x}_{\lambda_1} \otimes \bar{x}_{\lambda_2}$','Interpreter','latex','FontSize',16);
  1283. subplot(1,3,3);
  1284. plot(f3.Children(1),f,pxx,'k-');
  1285. ylabel('$F(x_{\lambda_1} \otimes x_{\lambda_2})$','Interpreter','latex','FontSize',16);
  1286. ylim([0 0.5]);
  1287. yline(0.1,'r--');
  1288. end
  1289. %% -------------------------------------------------------------------------
  1290. function [qualityMats] = qualityCompute2(main_fig)
  1291. raw = getappdata(main_fig,'rawNirs');
  1292. nirsplot_param = getappdata(main_fig,'nirsplot_parameters');
  1293. fcut = nirsplot_param.fcut;
  1294. window = nirsplot_param.window;
  1295. overlap = nirsplot_param.overlap;
  1296. lambda_mask = nirsplot_param.lambda_mask;
  1297. lambdas = nirsplot_param.lambdas;
  1298. n_channels = nirsplot_param.n_channels;
  1299. qltyThld = nirsplot_param.quality_threshold;
  1300. sciThrld = nirsplot_param.sci_threshold;
  1301. pspThrld = nirsplot_param.psp_threshold;
  1302. % Set the bandpass filter parameters
  1303. %fs = 1/mean(diff(raw.t));
  1304. fs = nirsplot_param.fs;
  1305. fcut_min = fcut(1);
  1306. fcut_max = fcut(2);
  1307. if fcut_max >= (fs)/2
  1308. fcut_max = (fs)/2 - eps;
  1309. warning(['The highpass cutoff has been reduced from ',...
  1310. num2str(fcut(2)), ' Hz to ', num2str(fcut_max),...
  1311. ' Hz to satisfy the Nyquist sampling criterion']);
  1312. end
  1313. [B1,A1]=butter(1,[fcut_min*(2/fs) fcut_max*(2/fs)]);
  1314. overlap_samples = floor(window*fs*overlap);
  1315. window_samples = floor(window*fs);
  1316. n_windows = floor((size(raw.d,1)-overlap_samples)/(window_samples-overlap_samples));
  1317. cardiac_windows = zeros(length(lambdas),window_samples,n_channels,n_windows);
  1318. nirs_data = zeros(length(lambdas),window_samples,n_channels);
  1319. cardiac_data = zeros(length(lambdas),window_samples,n_channels); % #Lambdas x #Windows x #Channels
  1320. for lam = 1:length(lambdas)
  1321. for j = 1:n_windows
  1322. interval = (j-1)*window_samples-(j-1)*(overlap_samples)+1 : j*window_samples-(j-1)*(overlap_samples);
  1323. idx = raw.SD.MeasList(:,4) == lambdas(lam);
  1324. nirs_data(lam,:,:) = raw.d(interval,idx);
  1325. filtered_nirs_data=filtfilt(B1,A1,squeeze(nirs_data(lam,:,:)));
  1326. cardiac_data(lam,:,:)=filtered_nirs_data./repmat(std(filtered_nirs_data,0,1),size(filtered_nirs_data,1),1); % Normalized heartbeat
  1327. cardiac_windows(lam,:,:,j) = cardiac_data(lam,:,:);
  1328. end
  1329. end
  1330. overlap_samples = floor(window*fs*overlap);
  1331. window_samples = floor(window*fs);
  1332. n_windows = floor((size(raw.d,1)-overlap_samples)/(window_samples-overlap_samples));
  1333. cardiac_data = cardiac_data(lambda_mask,:,:);
  1334. sci_array = zeros(size(cardiac_data,3),n_windows); % Number of optode is from the user's layout, not the machine
  1335. power_array = zeros(size(cardiac_data,3),n_windows);
  1336. parfor j = 1:n_windows
  1337. cardiac_window = cardiac_windows(:,:,:,j);
  1338. sci_array_channels = zeros(1,size(cardiac_window,3));
  1339. power_array_channels = zeros(1,size(cardiac_window,3));
  1340. fpower_array_channels = zeros(1,size(cardiac_window,3));
  1341. for k = 1:size(cardiac_window,3) % Channels iteration
  1342. %cross-correlate the two wavelength signals - both should have cardiac pulsations
  1343. similarity = xcorr(squeeze(cardiac_window(1,:,k)),squeeze(cardiac_window(2,:,k)),'unbiased');
  1344. if any(abs(similarity)>eps)
  1345. % this makes the SCI=1 at lag zero when x1=x2 AND makes the power estimate independent of signal length, amplitude and Fs
  1346. similarity = length(squeeze(cardiac_window(1,:,k)))*similarity./sqrt(sum(abs(squeeze(cardiac_window(1,:,k))).^2)*sum(abs(squeeze(cardiac_window(2,:,k))).^2));
  1347. else
  1348. warning('Similarity results close to zero');
  1349. end
  1350. [pxx,f] = periodogram(similarity,hamming(length(similarity)),length(similarity),fs,'power');
  1351. [pwrest,idx] = max(pxx(f<fcut_max)); % FIX Make it age-dependent
  1352. sci=similarity(length(squeeze(cardiac_window(1,:,k))));
  1353. power=pwrest;
  1354. fpower=f(idx);
  1355. sci_array_channels(k) = sci;
  1356. power_array_channels(k) = power;
  1357. fpower_array_channels(k) = fpower;
  1358. end
  1359. sci_array(:,j) = sci_array_channels; % Adjust not based on machine
  1360. power_array(:,j) = power_array_channels;
  1361. % fpower_array(:,j) = fpower_array_channels;
  1362. end
  1363. % Summary analysis
  1364. [woi] = getWOI(window_samples,n_windows,nirsplot_param);
  1365. idxPoi = logical(woi.mat(1,:));
  1366. mean_sci_link = mean(sci_array(:,idxPoi),2);
  1367. std_sci_link = std(sci_array(:,idxPoi),0,2);
  1368. good_sci_link = sum(sci_array(:,idxPoi)>=sciThrld,2)/size(sci_array(:,idxPoi),2);
  1369. mean_sci_window = mean(sci_array(:,idxPoi),1);
  1370. std_sci_window = std(sci_array(:,idxPoi),0,1);
  1371. good_sci_window = sum(sci_array(:,idxPoi)>=sciThrld,1)/size(sci_array(:,idxPoi),1);
  1372. mean_power_link = mean(power_array(:,idxPoi),2);
  1373. std_power_link = std(power_array(:,idxPoi),0,2);
  1374. good_power_link = sum(power_array(:,idxPoi)>=pspThrld,2)/size(power_array(:,idxPoi),2);
  1375. mean_power_window = mean(power_array(:,idxPoi),1);
  1376. std_power_window = std(power_array(:,idxPoi),0,1);
  1377. good_power_window = sum(power_array(:,idxPoi)>=pspThrld,1)/size(power_array(:,idxPoi),1);
  1378. combo_array = (sci_array >= sciThrld) & (power_array >= pspThrld);
  1379. combo_array_expanded = 2*(sci_array >= sciThrld) + (power_array >= pspThrld);
  1380. mean_combo_link = mean(combo_array,2);
  1381. std_combo_link = std(combo_array,0,2);
  1382. good_combo_link = mean(combo_array(:,idxPoi),2);
  1383. mean_combo_window = mean(combo_array,1);
  1384. std_combo_window = std(combo_array,0,1);
  1385. idx_gcl = good_combo_link>=qltyThld;
  1386. good_combo_window = mean(combo_array(idx_gcl,:),1);
  1387. % Detecting experimental blocks
  1388. exp_blocks = zeros(1,length(woi.start));
  1389. for iblock = 1:length(woi.start)
  1390. block_start_w = woi.start(iblock);
  1391. block_end_w = woi.end(iblock);
  1392. exp_blocks(iblock) = mean(good_combo_window(block_start_w:block_end_w));
  1393. end
  1394. % Detect artifacts and bad links
  1395. bad_links = find(mean_combo_link<qltyThld);
  1396. bad_windows = find(mean_combo_window<qltyThld);
  1397. % Packaging sci, peakpower and combo
  1398. qualityMats.sci_array = sci_array;
  1399. qualityMats.power_array = power_array;
  1400. qualityMats.combo_array = combo_array;
  1401. qualityMats.combo_array_expanded = combo_array_expanded;
  1402. qualityMats.bad_links = bad_links;
  1403. qualityMats.bad_windows = bad_windows;
  1404. qualityMats.sampPerWindow = window_samples;
  1405. qualityMats.fs = fs;
  1406. qualityMats.n_windows = n_windows;
  1407. qualityMats.overlap_samples = overlap_samples;
  1408. qualityMats.cardiac_data = cardiac_data;
  1409. % Bug found by Benjamin Zinszer (miscalculation in the S-D pairs)
  1410. qualityMats.good_combo_link = [raw.SD.MeasList(1:length(raw.SD.Lambda):end,1),...
  1411. raw.SD.MeasList(1:length(raw.SD.Lambda):end,2),good_combo_link];
  1412. qualityMats.good_combo_window = good_combo_window;
  1413. qualityMats.woi = woi;
  1414. qualityMats.allowed_samp = allowed_samp;
  1415. qualityMats.MeasListAct = repelem(idx_gcl,2);%[idx_gcl; idx_gcl];
  1416. qualityMats.MeasList = raw.SD.MeasList;
  1417. qualityMats.thresholds.sci = sciThrld;
  1418. qualityMats.thresholds.peakpower = pspThrld;
  1419. qualityMats.thresholds.quality = qltyThld;
  1420. %
  1421. end
  1422. end %end of nirsplot function definition

qtnirs.m at commit cc6372c, under CC-BY-NC-SA-4.0 · at the source

Overview

Authors: Julius Debertshaeuser1, Olga Tarassova2,3, Jana Strahler1, Sara Klinger1, Emerald G. Heiland2,4, Maria M. Ekblom2,5
  1. Department of Sportspsychology, Department of Sport and Sport Science, Albert-Ludwigs-University Freiburg, Freiburg, Germany
  2. Department of Physical Activity and Health, The Swedish School of Sport and Health Sciences (GIH), Stockholm, Sweden
  3. Department of Physiology, Nutrition and Biomechanics, The Swedish School of Sport and Health Sciences (GIH), Stockholm, Sweden
  4. Department of Surgical Sciences, Medical Epidemiology, Uppsala University, Uppsala, Sweden
  5. Division of Physiotherapy, Department of Neurobiology, Care Sciences and Society, Karolinska Institutet, Huddinge, Sweden
Journal: Frontiers in human neuroscience, volume 20, article 1856059
Dates: received 14 April 2026; accepted 9 July 2026; published online 31 July 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.3389/fnhum.2026.1856059 · PMID 42602215 · PMCID PMC13473378 · OpenAlex W7171993932
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: fNIRS (modality), human (organism), systems (subfield)
Methods: Spectral & time-frequency, Statistics, Machine learning, Preprocessing, fMRI & imaging
Keywords: acute exercise, feasibility, fNIRS, QT-NIRS, scalp coupling index
Topic: Optical Imaging and Spectroscopy Techniques (Radiology, Nuclear Medicine and Imaging, Medicine), according to OpenAlex
Citations: not cited yet (Europe PMC); 80 references in the paper

Abstract

Introduction: While previous research has shown that single bouts of acute exercise can enhance cognitive performance, the physiological mechanisms behind this remain unclear. Functional near-infrared spectroscopy (fNIRS) constitutes a promising tool to capture brain activity in this research field, but the feasibility of implementing such setups in combination with stationary cycling has not yet been evaluated. Thus, in this exploratory feasibility and methodological validation study, we investigated (1) procedural feasibility of the experimental protocol and (2) scientific feasibility, including dual-metric data quality assessment via scalp coupling index (SCI) and quality testing of near-infrared scans (QT-NIRS), as well as behavioral and prefrontal hemodynamic indicators of n-back task engagement.

Methods: Of 14 eligible, nine young and healthy participants (2 female, 7 male) completed 20 min of low-, moderate- and high-intensity continuous-cycling in a randomized cross-over design. Prefrontal cortex (PFC) activation was captured during numerical n-back tasks, administered before and with a 10-min delay after exercise. Procedural feasibility was descriptively assessed via participant attrition, protocol timing adherence, fNIRS setup reliability, target exercise load estimation, and monitoring of affect and fatigue. Scientific feasibility was evaluated through average SCI values, agreement between oxygenated and deoxygenated hemoglobin (oxyHb, deoxyHb) β-coefficients derived from SCI- and QT-NIRS-based pruning (Lin’s concordance correlation coefficient, CCC), and n-back task sensitivity via accuracy, reaction time, and load-dependent prefrontal hemodynamic responses.

Results: Technical difficulties (n = 1), physical discomfort due to cap wear (n = 2), and undisclosed reasons (n = 2) were reasons for study discontinuation. Protocol timing adherence and fNIRS setup reliability were satisfactory overall, and target exercise load estimation was successful after manual adaptation. Affect and fatigue were stable across timepoints. The channel-averaged SCI value of 0.964 (SE = 0.003) and near-optimal β-agreement between techniques (oxyHb CCC = 0.958; deoxyHb CCC = 0.983) suggested that good quality data were retrieved from the setup. N-back task behavioral and hemodynamic outcomes were load-dependent.

Discussion: These findings provide preliminary support for the scientific feasibility of assessing n-back task-induced changes in PFC activation using fNIRS. Future studies should consider minor adjustments to pre-experimental design and fitness assessment to potentially reduce attrition and improve target exercise load estimation.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repository

Its files are read in the Code ↔ Paper reader above, with 2 matches between paragraphs and lines of code.

lpollonini/qt-nirs

License: CC-BY-NC-SA-4.0
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: cc6372c5f18bb2338ff4914302498464403c4985, 11 August 2026
Languages: MATLAB (10)
Size: 17 files, 10 scripts
Software Heritage: archived
Found in: the end of the paper
Holds: README, license file, CITATION.cff
Not found: environment file, tests, continuous integration, documentation
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
12 files

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 10 scripts, each with its path and the digest of its content;
  • 2 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data availability statement

The raw data supporting the conclusions of this article will be made available by the authors, without undue reservation.

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 27 September 2026: the first record

Recorded: type, language, journal, volume, pages, dates, 6 authors, 5 keywords, 76 references.

Cite

This paper

Debertshaeuser, J., Tarassova, O., Strahler, J., Klinger, S., Heiland, E. G., & Ekblom, M. M. (2026). Feasibility of fNIRS for assessing n-back task-related prefrontal cortex oxygenation after continuous cycling at varying intensities: an evaluation of protocol feasibility. Frontiers in human neuroscience, 20, 1856059. https://doi.org/10.3389/fnhum.2026.1856059

BibTeX

@article{debertshaeuser2026feasibility,
author = {Debertshaeuser, Julius and Tarassova, Olga and Strahler, Jana and Klinger, Sara and Heiland, Emerald G. and Ekblom, Maria M.},
title = {{Feasibility of fNIRS for assessing n-back task-related prefrontal cortex oxygenation after continuous cycling at varying intensities: an evaluation of protocol feasibility}},
journal = {Frontiers in human neuroscience},
year = {2026},
month = jul,
volume = {20},
pages = {1856059},
publisher = {Frontiers Media SA},
issn = {1662-5161},
doi = {10.3389/fnhum.2026.1856059},
url = {https://doi.org/10.3389/fnhum.2026.1856059},
pmid = {42602215},
pmcid = {PMC13473378}
}

RIS

TY - JOUR
AU - Debertshaeuser, Julius
AU - Tarassova, Olga
AU - Strahler, Jana
AU - Klinger, Sara
AU - Heiland, Emerald G.
AU - Ekblom, Maria M.
TI - Feasibility of fNIRS for assessing n-back task-related prefrontal cortex oxygenation after continuous cycling at varying intensities: an evaluation of protocol feasibility
T2 - Frontiers in human neuroscience
J2 - Front Hum Neurosci
PY - 2026
DA - 2026/07/31
VL - 20
SP - 1856059
SN - 1662-5161
PB - Frontiers Media SA
DO - 10.3389/fnhum.2026.1856059
UR - https://doi.org/10.3389/fnhum.2026.1856059
LA - en
ER -

CSL-JSON

{
"id": "10.3389/fnhum.2026.1856059",
"type": "article-journal",
"title": "Feasibility of fNIRS for assessing n-back task-related prefrontal cortex oxygenation after continuous cycling at varying intensities: an evaluation of protocol feasibility",
"container-title": "Frontiers in human neuroscience",
"author": [
{
"family": "Debertshaeuser",
"given": "Julius"
},
{
"family": "Tarassova",
"given": "Olga"
},
{
"family": "Strahler",
"given": "Jana"
},
{
"family": "Klinger",
"given": "Sara"
},
{
"family": "Heiland",
"given": "Emerald G."
},
{
"family": "Ekblom",
"given": "Maria M."
}
],
"container-title-short": "Front Hum Neurosci",
"volume": "20",
"page": "1856059",
"DOI": "10.3389/fnhum.2026.1856059",
"PMID": "42602215",
"PMCID": "PMC13473378",
"ISSN": "1662-5161",
"publisher": "Frontiers Media SA",
"URL": "https://doi.org/10.3389/fnhum.2026.1856059",
"language": "en",
"issued": {
"date-parts": [
[
2026,
7,
31
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1117/1.nph.12.2.025011 [code]
NIRSTORM: a Brainstorm extension dedicated to functional near-infrared spectroscopy data analysis, advanced 3D reconstructions, and optimal probe design
Journal: —
In common: Signal Processing Toolbox, fNIRS, 6 references
[2] doi:10.1117/1.nph.13.s3.s32602 [code]
Cedalion tutorial: a Python-based framework for comprehensive analysis of multimodal fNIRS and DOT from the lab to the everyday world.
Journal: Neurophotonics
In common: fNIRS, 6 references
[3] doi:10.1117/1.nph.13.3.035005 [code]
Extending effective multiplicity for independent designs in multichannel fNIRS studies.
Journal: Neurophotonics
In common: fNIRS, 4 references
[4] doi:10.1364/boe.604286
Computational validation of optical adaptive depth steering for continuous-wave fNIRS.
Journal: Biomedical optics express
In common: fNIRS, 4 references
[5] doi:10.1117/1.nph.13.2.025009
Distinct neural signatures of phonemic and semantic verbal fluency: a double dissociation in cortical activation and functional connectivity revealed by fNIRS.
Journal: Neurophotonics
In common: fNIRS, systems, 3 references
[6] doi:10.1117/1.nph.13.3.035009
Single-subject detection of speech network activation using functional near-infrared spectroscopy.
Journal: Neurophotonics
In common: fNIRS, 3 references
[7] doi:10.1523/eneuro.0423-25.2026 [code]
Cortically Mediated Muscle Responses to Balance Perturbations Increase with Perturbation Magnitude in Older Adults with and without Parkinson's Disease.
Journal: eNeuro
In common: systems, 3 references
[8] doi:
Material context moderates the occupation-adjusted association between Visualization and prefrontal hemodynamics during naturalistic design: an exploratory wearable fNIRS study
Journal: Frontiers in neuroergonomics
In common: fNIRS, 3 references
[9] doi:10.1117/1.nph.13.3.035006 [code]
Characterizing developmental changes in infant habituation using functional change point detection.
Journal: Neurophotonics
In common: fNIRS, 2 references
[10] doi:10.1016/j.dcn.2026.101782 [code]
Do babies perceive cries as speech?
Journal: Developmental cognitive neuroscience
In common: fNIRS, 2 references

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.