-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathNrModel.m
1435 lines (1233 loc) · 58.3 KB
/
NrModel.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
classdef NrModel < handle
properties (SetObservable)
expInfo
rawDataDir
rawFileList
resultDir
trialTable
selectedFileIdx
trialArray
currentTrialIdx
motionCorrConfig
alignFilePath
alignResult
setupMode %1=SetupA; 3=SetupC/VR
loadMapFromFile %Mainly for SetupC mode
blankingstructureFileList %Mainly for SetupC mode
responseOption
responseMaxOption
localCorrelationOption
SetupCAnatomyOption = struct('skipping',5,...
'offset',0);
SetupCResponseOption = struct('skipping',5,...
'lowerPercentile',25,...
'offset',0);
SetupCMaxResponseOption=struct('skipping',5,...
'lowerPercentile',25,...
'slidingWindowSize',3,...
'offset',0);
SetupCCorrOption= struct('skipping',5,...
'tileSize',16 );
roiDir
jroiDir
maskDir
precalculatedMapDir
loadFileType
planeNum
trialOptionRaw
trialOptionBinned
alignToTemplate
mapsAfterLoading
loadTemplateRoi
roiTemplateFilePath
binConfig
roiFileIdentifier
registerWithBunwarpj = false
transformParam
referenceTrialIdx
transformationName
calculatedTransformationsIdx
calculatedTransformationsList
TransformationTooltip
stackModel
end
properties (SetAccess = private, SetObservable = true)
anatomyConfig
alignConfig
end
methods
function self = NrModel(varargin)
pa = inputParser;
addParameter(pa,'rawDataDir','',@ischar);
addParameter(pa,'rawFileList','',@iscell);
addParameter(pa,'resultDir','',@ischar);
addParameter(pa,'precalculatedMapDir','',@ischar);
defaultExpInfo.frameRate = 1;
defaultExpInfo.nPlane = 1;
defaultExpInfo.mapSize = [512, 512];
addParameter(pa,'expInfo',defaultExpInfo,@isstruct);
% addParameter(pa,'alignFilePath','',@ischar)
addParameter(pa,'roiDir','',@ischar);
addParameter(pa,'loadFileType','raw',@ischar);
defaultTrialOptionRaw = struct('process',true,...
'noSignalWindow',[1 12], ...
'intensityOffset',-30);
defaultTrialOptionBinned = struct('process',false,...
'noSignalWindow',[], ...
'intensityOffset',100);
addParameter(pa,'trialOptionRaw',defaultTrialOptionRaw, ...
@isstruct);
addParameter(pa,'trialOptionBinned', ...
defaultTrialOptionBinned,@isstruct);
defaultResponseOption = struct('offset',0,...
'fZeroWindow',[1 5],...
'responseWindow',[10 15]);
defaultResponseMaxOption = struct('offset',0,...
'fZeroWindow',[1 5],...
'slidingWindowSize',3);
addParameter(pa,'responseOption',defaultResponseOption, ...
@isstruct);
addParameter(pa,'responseMaxOption', ...
defaultResponseMaxOption,@isstruct);
addParameter(pa,'TransformationTooltip',struct(),@isstruct);
%SetupCTab map options
defaultSetupCAnatomyOption = struct('skipping',5,...
'offset',0 );
defaultSetupCResponseOption = struct('skipping',5,...
'lowerPercentile',25,...
'offset',0);
defaultSetupCMaxResponseOption = struct('skipping',5,...
'lowerPercentile',25,...
'slidingWindowSize',3,...
'offset',0);
defaultSetupCCorrOption = struct('skipping',5,...
'tileSize',16 );
addParameter(pa,'SetupCAnatomyOption',defaultSetupCAnatomyOption, ...
@isstruct);
addParameter(pa,'SetupCResponseOption',defaultSetupCResponseOption, ...
@isstruct);
addParameter(pa,'SetupCMaxResponseOption',defaultSetupCMaxResponseOption, ...
@isstruct);
addParameter(pa,'SetupCCorrOption',defaultSetupCCorrOption, ...
@isstruct);
%SetupMode parameter
defaultSetupModeParameter = 1;
addParameter(pa, 'SetupMode',defaultSetupModeParameter, @isinteger);
defaultRoiFileIdentifier ="_RoiArray";
addParameter(pa, 'roiFileIdentifier',defaultRoiFileIdentifier, @isstring);
parse(pa,varargin{:})
pr = pa.Results;
self.trialArray = trialMvc.TrialModel.empty();
self.expInfo = pr.expInfo; % expInfo.nPlane is the total number of planes in the data
self.setupMode=pr.SetupMode;
self.rawDataDir = pr.rawDataDir;
self.rawFileList = pr.rawFileList;
self.resultDir = pr.resultDir;
self.precalculatedMapDir=pr.precalculatedMapDir;
self.alignResult = cell(1,pr.expInfo.nPlane);
if ~isempty(pr.roiDir)
self.roiDir = pr.roiDir;
else
self.roiDir = self.getDefaultDir('roi');
end
self.roiFileIdentifier=pr.roiFileIdentifier;
self.maskDir = self.getDefaultDir('mask');
self.loadFileType = pr.loadFileType;
self.trialOptionRaw = pr.trialOptionRaw;
self.trialOptionBinned = pr.trialOptionBinned;
self.responseOption = pr.responseOption;
self.responseMaxOption = pr.responseMaxOption;
self.SetupCAnatomyOption=pr.SetupCAnatomyOption;
self.SetupCResponseOption=pr.SetupCResponseOption;
self.SetupCCorrOption=pr.SetupCCorrOption;
self.mapsAfterLoading = {};
self.loadTemplateRoi = false;
self.roiTemplateFilePath = '';
self.planeNum = 1; % The plane number for loading file
% Bunwarpj
self.referenceTrialIdx = 1;
self.transformParam = Bunwarpj.TransformParam();
self.TransformationTooltip=struct();
end
function importRawData(self,expInfo,rawDataDir,rawFileList,resultDir)
self.expInfo = expInfo;
self.rawDataDir = rawDataDir;
self.rawFileList = rawFileList;
self.resultDir = resultDir;
end
function processRawData(self,varargin)
pa = inputParser;
addParameter(pa,'subtractScan',false);
addParameter(pa,'noSignalWindow',1);
addParameter(pa,'mcWithinTrial',false);
addParameter(pa,'computeAnatomy',true);
addParameter(pa,'mcBetweenTrial',false);
addParameter(pa,'mcBTTemplateIdx',1);
addParameter(pa,'binning',false);
addParameter(pa,'binDir','');
addParameter(pa,'binParam',[]);
parse(pa,varargin{:})
pr = pa.Results;
if pr.subtractScan
trialOption = struct('process',true,'noSignalWindow',pr.noSignalWindow);
else
trialOption = {}; %
end
% Motion correction within trial
if pr.mcWithinTrial
% For now motion correction within trial only
% support single plane data
% TODO add multiplane support
motionCorrDir = self.getDefaultDir('motion_corr');
self.motionCorrBatch(trialOption,motionCorrDir)
end
% Subsampling
if pr.binning
binParam = pr.binParam;
binParam.trialOption = trialOption;
for planeNum=1:self.expInfo.nPlane
self.binMovieBatch(binParam,pr.binDir,planeNum);
end
end
% Compute averaged anatomy image for each trial
if pr.computeAnatomy
if pr.binning
anatomyParam.inFileType = 'binned';
anatomyParam.trialOption = [];
else
anatomyParam.inFileType = 'raw';
anatomyParam.trialOption = trialOption;
end
for planeNum=1:self.expInfo.nPlane
self.calcAnatomyBatch(anatomyParam,planeNum);
end
end
% Motion correction between trials
if pr.mcBetweenTrial
templateRawName = self.rawFileList{pr.mcBTTemplateIdx};
for planeNum=1:self.expInfo.nPlane
outDir = fullfile(self.resultDir,self.alignDir);
self.alignTrialBatch(templateRawName,...
'planeNum',planeNum,...
'alignOption',{'plotFig',false},...
'outDir', outDir);
end
end
end
function tagArray = getTagArray(self)
tagArray = arrayfun(@(x) x.tag,self.trialArray, ...
'Uniformoutput',false);
end
function idx = getTrialIdx(self,tag)
tagArray = self.getTagArray();
idx = find(strcmp(tagArray,tag));
end
function trial = getTrialByTag(self,tag)
idx = self.getTrialIdx(tag);
trial = self.trialArray(idx);
end
function trial = loadTrialFromList(self,fileIdx,fileType, ...
planeNum)
if ~exist('planeNum','var')
planeNum = 1;
end
rawFileName = self.rawFileList{fileIdx};
fprintf('Loading %s\n planeNum: %d\n',rawFileName, ...
planeNum)
multiPlane = checkMultiPlane(self,planeNum);
if self.setupMode==3 %SetupC maps are precalculated so we use 'raw' so the names are correct
fileType='raw';
end
switch fileType
case 'raw'
fileName = rawFileName;
filePath = fullfile(self.rawDataDir, ...
fileName);
trialOption = self.trialOptionRaw;
if multiPlane
trialOption.zrange = [planeNum inf];
trialOption.nFramePerStep = ...
self.expInfo.nPlane;
frameRate = self.expInfo.frameRate /self.expInfo.nPlane;
else
frameRate = self.expInfo.frameRate;
end
case 'binned'
shrinkFactors = self.binConfig.param.shrinkFactors;
fileName = iopath.getBinnedFileName(rawFileName, ...
shrinkFactors);
if multiPlane
planeString = NrModel.getPlaneString(planeNum);
filePath = fullfile(self.binConfig.outDir, ...
planeString,fileName);
frameRate = self.expInfo.frameRate / ...
shrinkFactors(3) / self.expInfo.nPlane;
else
filePath = fullfile(self.binConfig.outDir, ...
fileName);
frameRate = self.expInfo.frameRate / ...
shrinkFactors(3);
end
trialOption = self.trialOptionBinned;
end
if self.alignToTemplate
offsetYx = self.getTrialOffsetYx(fileIdx,planeNum);
else
warning('The trial might not be aligned in X and Y!')
offsetYx = [0,0];
end
if multiPlane
planeString = NrModel.getPlaneString(planeNum);
roiDir = fullfile(self.roiDir,planeString);
else
roiDir = self.roiDir;
end
if ~exist(roiDir)
mkdir(roiDir)
end
if multiPlane
planeString = NrModel.getPlaneString(planeNum);
maskDir = fullfile(self.maskDir,planeString);
else
maskDir = self.maskDir;
end
if ~exist(maskDir)
mkdir(maskDir)
end
trialOption.yxShift = offsetYx;
trialOption.roiDir = roiDir;
trialOption.maskDir = maskDir;
trialOption.frameRate = frameRate;
trialOption.loadMapFromFile= self.loadMapFromFile;
trialOption.setupMode=self.setupMode;
trial = self.loadTrial(filePath,trialOption);
trial.sourceFileIdx = fileIdx;
end
function trial = loadAdditionalTrial(self,filePath,varargin)
% TODO save trial path into a property
trial = self.loadTrial(filePath,varargin{:});
end
function trial = loadTrial(self,filePath,trialOption)
tagArray = self.getTagArray();
tag = helper.generateRandomTag(6);
nstep = 1;
while ismember(tag,tagArray) && nstep < 100
tag = helper.generateRandomTag(5);
nstep = nstep+1;
end
if ismember(tag,tagArray)
error('Cannot get unused trial tag!')
end
trialOptionCell = helper.structToNameValPair(trialOption);
trial = trialMvc.TrialModel('filePath',filePath,trialOptionCell{:});
trial.tag = tag;
self.trialArray(end+1) = trial;
end
function selectTrial(self,tag)
if isempty(tag)
self.currentTrialIdx = [];
disp('No trial is selected..')
else
idx = self.getTrialIdx(tag);
if isempty(idx)
disp('No trial is selected')
else
if ~isequal(idx,self.currentTrialIdx)
self.currentTrialIdx = idx;
disp(sprintf('trial_%s # %d selected', tag, ...
self.currentTrialIdx))
end
end
end
end
function deleteTrial(self,idx)
self.trialArray(idx) = [];
end
function trial = getCurrentTrial(self)
trial = self.trialArray(self.currentTrialIdx);
end
function mapOption = getMapOption(self,mapType)
switch mapType
case 'response'
mapOption = self.responseOption;
case 'responseMax'
mapOption = self.responseMaxOption;
case 'localCorrelation'
mapOption = self.localCorrelationOption;
case 'SetupCAnatomy'
mapOption = self.SetupCAnatomyOption;
case 'SetupCResponse'
mapOption = self.SetupCResponseOption;
case 'SetupCResponseMax'
mapOption = self.SetupCMaxResponseOption;
case 'SetupCCorr'
mapOption = self.SetupCCorrOption;
otherwise
error('NrModel:mapTypeTagError',['Map type of ' ...
'the button is wrong!'])
end
end
function addMapCurrTrial(self,mapType)
mapOption = self.getMapOption(mapType);
trial = self.getCurrentTrial();
try
trial.calculateAndAddNewMap(mapType,mapOption);
catch ME
if strcmp(ME.identifier,['trialMvc.TrialModel:' ...
'windowValueError'])
self.view.displayError(ME);
return
end
rethrow(ME)
end
end
function updateMapCurrTrial(self,mapType)
mapOption = self.getMapOption(mapType);
trial = self.getCurrentTrial();
try
trial.findAndUpdateMap(mapType,mapOption);
catch ME
switch ME.identifier
case 'trialMvc.TrialModel:mapTypeError','trialMvc.TrialModel:windowValueError'
self.view.displayError(ME);
return
end
rethrow(ME)
end
end
function LoadMapsFromFileCurrTrial(self,TempMapFolder)
MapFiles=dir(strcat(TempMapFolder,"/*.mat"));
[~,idx] = sort([MapFiles.datenum]);
MapFiles = MapFiles(idx);
trial = self.getCurrentTrial();
for i=1:length(MapFiles)
trial.LoadAndAddMapFromFile(fullfile(MapFiles(i).folder,MapFiles(i).name));
end
%trial.LoadAndAddMapFromFile(MapFiles);
end
function motionCorrBatch(self,trialOption,outDir,fileIdx)
% MOTIONCORRBATCH motion correction within trial
% multiplane not yet implemented
self.motionCorrConfig.outDir = outDir;
if exist('fileIdx','var')
rawFileList = self.rawFileList(fileIdx);
else
rawFileList = self.rawFileList;
end
batch.motionCorrFromFile(self.rawDataDir,rawFileList,trialOption,outDir)
end
function binMovieBatch(self,param,outDir,planeNum,fileIdx)
if ~exist('outDir','var')
if length(self.binConfig.outDir)
outDir = self.binConfig.outDir;
else
error('Please specify output directory!')
end
end
if ~exist(outDir,'dir')
mkdir(outDir)
end
trialOption = param.trialOption;
if self.expInfo.nPlane > 1
if exist('planeNum','var')
planeString = NrModel.getPlaneString(planeNum);
outSubDir = fullfile(outDir,planeString);
if ~exist(outSubDir,'dir')
mkdir(outSubDir)
end
trialOption.nFramePerStep = self.expInfo.nPlane;
trialOption.zrange = [planeNum,inf];
else
error(['Please specify plane number for' ...
' multiplane data!']);
end
else
outSubDir = outDir;
end
if exist('fileIdx','var')
rawFileList = self.rawFileList(fileIdx);
else
rawFileList = self.rawFileList;
end
binConfig = batch.binMovieFromFile(self.rawDataDir, ...
rawFileList, ...
outSubDir,...
param.shrinkFactors,...
param.depth,...
trialOption);
binConfig.outDir = outDir;
binConfig.trialOption = param.trialOption;
self.binConfig = binConfig;
% timeStamp = helper.getTimeStamp();
% configFileName = ['binConfig-' timeStamp '.json'];
configFileName = 'binConfig.json';
configFilePath = fullfile(outDir,configFileName);
helper.saveStructAsJson(binConfig,configFilePath);
end
function readBinConfig(self,metaFilePath)
self.binConfig = jsondecode(fileread(metaFilePath));
end
function calcAnatomyBatch(self,param,planeNum,fileIdx)
outDir = self.getDefaultDir('anatomy');
if ~exist(outDir,'dir')
mkdir(outDir)
end
if ~isfield(param,'trialOption')
param.trialOption = {};
end
if exist('fileIdx','var')
rawFileList = self.rawFileList(fileIdx);
else
rawFileList = self.rawFileList;
end
outSubDir = self.appendPlaneDir(outDir, planeNum);
if ~exist(outSubDir,'dir')
mkdir(outSubDir)
end
if strcmp(param.inFileType,'raw')
trialOption = param.trialOption;
if self.expInfo.nPlane > 1
trialOption.nFramePerStep = self.expInfo.nPlane;
trialOption.zrange = [planeNum,inf];
end
[~,filePrefix] = batch.calcAnatomyFromFile(self.rawDataDir, ...
rawFileList,...
outSubDir, ...
trialOption);
elseif strcmp(param.inFileType,'binned')
binDir = self.binConfig.outDir;
if self.expInfo.nPlane > 1
binDir = fullfile(binDir,planeString);
end
if self.binConfig.filePrefix
binPrefix = self.binConfig.filePrefix;
binnedFileList = ...
iopath.modifyFileName(rawFileList,binPrefix,'','tif');
end
try
[~,filePrefix] = batch.calcAnatomyFromFile(binDir, ...
binnedFileList,outSubDir,param.trialOption);
catch ME
if strcmp(ME.identifier, ...
'batchCalcAnatomyFromFile:fileNotFound')
addMsg = ['Binned data does not exist! Please do ' ...
'binning first before calculating anatomy.'];
disp(addMsg)
end
rethrow(ME)
end
filePrefix = [filePrefix,binPrefix];
end
anatomyConfig.param = param;
anatomyConfig.filePrefix = filePrefix;
self.anatomyConfig = anatomyConfig;
configFileName = ['anatomyConfig.json'];
configFilePath = fullfile(outDir,configFileName);
helper.saveStructAsJson(anatomyConfig,configFilePath);
end
function readAnatomyConfig(self,filePath)
self.anatomyConfig = jsondecode(fileread(filePath));
end
function alignResult = alignTrialBatch(self,templateRawName,varargin)
pa = inputParser;
addParameter(pa,'planeNum',1,@isnumeric);
addParameter(pa,'fileIdx','all',@(x) ischar(x)|ismatrix(x));
addParameter(pa,'alignOption',{},@iscell);
addParameter(pa, 'outDir', '', @ischar);
parse(pa,varargin{:})
pr = pa.Results;
outFileName = 'alignResult.mat';
outDir = pr.outDir;
if ~exist(outDir,'dir')
mkdir(outDir)
end
anatomyPrefix = self.anatomyConfig.filePrefix;
templateName = iopath.modifyFileName(templateRawName, ...
anatomyPrefix,'','tif');
if ischar(pr.fileIdx)
rawFileList = self.rawFileList;
else
rawFileList = self.rawFileList(pr.fileIdx);
end
% TODO deal with error that no anatomy files found
% TODO deal with no anatomyConfig loaded
inDir = self.appendPlaneDir(self.getDefaultDir('anatomy'), pr.planeNum);
outSubDir = self.appendPlaneDir(outDir, pr.planeNum);
if ~exist(outSubDir,'dir')
mkdir(outSubDir)
end
anatomyFileList = iopath.modifyFileName(rawFileList, ...
anatomyPrefix, ...
'','tif');
stackFileName = iopath.modifyFileName(outFileName, ...
'stack_','','tif');
stackFilePath = fullfile(outSubDir,stackFileName);
alignResult = batch.alignTrials(inDir,...
anatomyFileList, ...
templateName,...
'stackFilePath',...
stackFilePath,...
pr.alignOption{:});
alignResult.anatomyPrefix = anatomyPrefix;
alignResult.templateRawName = templateRawName;
self.alignResult{pr.planeNum} = alignResult;
outFilePath = fullfile(outSubDir,outFileName);
save(outFilePath,'alignResult')
end
function loadAlignResult(self,planeNum)
fileName = 'alignResult.mat';
multiPlane = self.checkMultiPlane(planeNum);
if multiPlane
planeString = NrModel.getPlaneString(planeNum);
filePath = fullfile(self.resultDir,self.alignDir,planeString,...
fileName);
else
filePath = fullfile(self.resultDir,self.alignDir,fileName);
end
foo = load(filePath);
self.alignResult{planeNum} = foo.alignResult;
end
function arrangeTrialTable(self)
trialTable = batch.getTrialTable(self.rawFileList,self.expInfo.odorList);
trialTable = batch.addTrialNum(trialTable);
self.trialTable = trialTable;
end
function removeTrialFromTable(self, fileIdxList)
rowLogic = ismember(self.trialTable.fileIdx, fileIdxList);
self.trialTable(rowLogic,:) = [];
end
function [mapArray,varargout] = calcMapBatch(self,inFileType,mapType,mapOption,varargin)
pa = inputParser;
addParameter(pa,'trialOption',[]);
addParameter(pa,'planeNum',1,@isnumeric);
addParameter(pa,'sortBy','none',@ischar);
addParameter(pa,'odorDelayList',[],@ismatrix);
addParameter(pa,'saveMap',false);
addParameter(pa,'outFileType','mat',@ischar);
addParameter(pa,'fileIdx',0,@ismatrix);
parse(pa,varargin{:})
pr = pa.Results;
planeNum = pr.planeNum;
multiPlane = self.checkMultiPlane(planeNum);
trialOption = pr.trialOption;
if strcmp(inFileType,'raw')
inSubDir = self.rawDataDir;
inFileList = self.rawFileList;
if pr.fileIdx
inFileList = inFileList(pr.fileIdx);
end
if multiPlane
trialOption.frameRate = self.expInfo.frameRate/ ...
self.expInfo.nPlane;
trialOption.zrange = [planeNum inf];
trialOption.nFramePerStep = self.expInfo.nPlane;
else
trialOption.frameRate = self.expInfo.frameRate;
end
elseif strcmp(inFileType,'binned')
inDir = self.binConfig.outDir;
inFileList = self.getFileList('binned');
if pr.fileIdx
inFileList = inFileList(pr.fileIdx);
end
shrinkZ = self.binConfig.param.shrinkFactors(3);
if multiPlane
inSubDir = fullfile(inDir, ...
NrModel.getPlaneString(planeNum));
trialOption.frameRate = self.expInfo.frameRate/ ...
self.expInfo.nPlane/shrinkZ;
else
inSubDir = inDir;
trialOption.frameRate = self.expInfo.frameRate/ ...
shrinkZ;
end
else
error('inFileType should be either raw or binned!')
end
delayList = [];
if pr.saveMap
if strcmp(mapType, 'response')
outDir = self.getDefaultDir('response_map');
elseif strcmp(mapType, 'responseMax')
outDir = self.getDefaultDir('response_max_map');
end
if ~exist(outDir,'dir')
mkdir(outDir)
end
if multiPlane
outSubDir = fullfile(outDir, ...
NrModel.getPlaneString(planeNum));
if ~exist(outSubDir,'dir')
mkdir(outSubDir)
end
else
outSubDir = outDir;
end
else
outSubDir = [];
end
mapArray = batch.calcMapFromFile(inSubDir,...
inFileList,...
mapType,...
'mapOption',mapOption,...
'windowDelayList',delayList,...
'trialOption',trialOption,...
'outDir',outSubDir,...
'outFileType',pr.outFileType);
end
function offsetYx = getTrialOffsetYx(self,fileIdx,planeNum)
% GETTRIALOFFSETYX get trial offset in y and x axis by
% matching file name to the alignment result file list
if isempty(self.alignResult{planeNum})
try
self.loadAlignResult(planeNum);
catch ME
display('Cannot load alignment result!')
rethrow ME
end
end
alignResult = self.alignResult{planeNum};
rawFileName = self.rawFileList{fileIdx};
anatomyPrefix = alignResult.anatomyPrefix;
anatomyFileName = ...
iopath.modifyFileName(rawFileName, ...
anatomyPrefix,'','tif');
offsetYx = self.getOffsetYx(alignResult, anatomyFileName);
end
function offsetYx = getOffsetYx(self, alignResult, anatomyFileName)
inFileList = alignResult.inFileList;
idx = find(strcmp(inFileList,anatomyFileName));
if isempty(idx)
msg = ['Cannot find offset value in the aligment ' ...
'result for file: ' anatomyFileName];
error(msg);
else
offsetYx = alignResult.offsetYxMat(idx,:);
end
end
function [timeTraceMat,roiArr] = extractTimeTrace(self, fileIdx,...
varargin)
pa = inputParser;
addRequired(pa,'fileIdx');
addParameter(pa,'roiArr', []);
addParameter(pa,'roiFilePath', []);
addParameter(pa,'planeNum', 1);
parse(pa,fileIdx, ...
varargin{:})
pr = pa.Results;
planeNum = pr.planeNum;
multiPlane = self.checkMultiPlane(planeNum);
traceDir = fullfile(self.resultDir,'time_trace');
if multiPlane
planeString = NrModel.getPlaneString(planeNum);
traceDir = fullfile(traceDir,planeString);
end
if ~exist(traceDir,'dir')
mkdir(traceDir)
end
disp(sprintf('Extract time trace ...'))
disp(sprintf('Data file: #%d, %s', fileIdx, self.rawFileList{fileIdx}))
trial = self.loadTrialFromList(fileIdx,'raw',planeNum);
if ~isempty(pr.roiArr)
disp('ROI from stack')
trial.replaceRoiArr(pr.roiArr)
else
if ~exist(pr.roiFilePath,'file')
error(sprintf('ROI file %s does not exists!',roiFilePath))
end
disp(sprintf('ROI file: %s', roiFilePath))
trial.loadRoiArr(pr.roiFilePath);
end
[timeTraceMat,roiArr] = trial.extractTimeTraceMat();
dataFileBaseName = trial.name;
resFileName = [dataFileBaseName '_traceResult.mat'];
resFilePath = fullfile(traceDir,resFileName);
traceResult.timeTraceMat = timeTraceMat;
traceResult.roiArr = roiArr;
traceResult.roiFilePath = pr.roiFilePath;
traceResult.rawFilePath = trial.filePath;
save(resFilePath,'traceResult')
end
function extractTimeTraceBatch(self, fileIdxList, ...
varargin)
pa = inputParser;
addRequired(pa,'fileIdxList');
addParameter(pa,'roiArrStack', []);
addParameter(pa,'roiFileList', []);
addParameter(pa,'planeNum', 1);
addParameter(pa,'plotTrace', true);
parse(pa,fileIdxList, ...
varargin{:})
pr = pa.Results;
if pr.plotTrace
timeTraceFig = figure();
nrow = 4;
ncol = ceil(length(fileIdxList)/4);
end
for k=1:length(fileIdxList)
fileIdx = fileIdxList(k);
if ~isempty(pr.roiArrStack)
roiArr = pr.roiArrStack(k);
[timeTraceMat,roiArr] = self.extractTimeTrace(fileIdx,...
'roiArr', roiArr,...
'planeNum', pr.planeNum);
else
roiFilePath = pr.roiFileList{k};
[timeTraceMat,roiArr] = self.extractTimeTrace(fileIdx,...
'roiFilePath', roiFilePath,...
'planeNum', pr.planeNum);
end
if pr.plotTrace
figure(timeTraceFig)
subplot(nrow,ncol,k)
imagesc(timeTraceMat)
end
end
end
function SetupCExtractTracesDfoverf(self)
planeString = NrModel.getPlaneString(self.planeNum);
CalculatedTransformationName= self.calculatedTransformationsList(self.calculatedTransformationsIdx);
RoisStruc= load(fullfile(self.resultDir,"BUnwarpJ",CalculatedTransformationName,"Rois.mat"));
TempCellArray=struct2cell(RoisStruc.RoiArray);
blankingPath=fullfile(self.resultDir,strcat(nameParts{1},'_',nameParts{2},'_blankingstruct.mat'));
if exist(blankingPath)
load(blankingPath);
framesToBlank=[blankingstruct.blankingdx blankingstruct.blankingdy];
framesToBlank= unique(framesToBlank);
temprawfile(:,:,framesToBlank)= [];
end
self.BUnwarpJRoiCellarray=squeeze(TempCellArray(1,:,:));
NameCellArray=squeeze(TempCellArray(2,:,:));
NameCellArray=cellstr(NameCellArray);
disp("Start calculating cellTraces");
mkdir(fullfile(self.resultDir,'cellTraces',planeString,CalculatedTransformationName{1}));
for i=1:length(self.rawFileList)
AquiName=strsplit(self.rawFileList{i},'.');
outputFolder=(fullfile(self.resultDir,'cellTraces',planeString,CalculatedTransformationName{1},AquiName{1}));
mkdir(outputFolder);
index=find(contains(NameCellArray,AquiName{1}));
disp("load stack");
tempRawFile=load(fullfile(self.rawDataDir,self.rawFileList{index}));
disp("loading done");
%tempRawFile=load('C:\Data\temp\2020Oct13\registeredStacks\2020Oct13_003_neuRoiIO-test.mat');
tempRawFile=tempRawFile.stack;
stackMin=min(tempRawFile,[],'all');
tempRawFile=tempRawFile-stackMin;
AquiRois=self.BUnwarpJRoiCellarray{index};
maxRoiTag=AquiRois(length(AquiRois)).tag;
frameCount=size(tempRawFile);
mapSize=frameCount(1:2);
frameCount=frameCount(3);
%OutputMatrix=zeros(frameCount,maxRoiTag);
OutputMatrix=[];
oldTag=1;
for j=1:length(AquiRois)
tempRoi=AquiRois(j);
newtag=tempRoi.tag;
difTags=uint8(newtag-oldTag);
if difTags>1
for k=1:(difTags-1)
OutputMatrix(:,end+1)=zeros(frameCount,1);
end
end
mask = tempRoi.createMask(mapSize);
[maskIndX maskIndY] = find(mask==1);
roiMovie = tempRawFile(maskIndX,maskIndY,:);
timeTraceRaw = squeeze(mean(mean(roiMovie,1),2));
OutputMatrix(:,end+1)=timeTraceRaw;
oldTag=newtag;
end
%df/f calculations
fZeroRawPercentile=prctile(OutputMatrix,25,1);
fZeroRaw=double(OutputMatrix);
fZeroRaw(fZeroRaw> fZeroRawPercentile)=NaN;
fZeroRaw =mean(fZeroRaw,1,"omitnan");
offset=0;
OutputMatrix=(OutputMatrix-fZeroRaw)./(fZeroRaw-offset);
%save("C:\Data\temp\RoiTest.mat",'OutputMatrix');
save(fullfile(outputFolder,AquiName{1}),'OutputMatrix');
end
disp("cellTraces done");
end
function multiPlane = checkMultiPlane(self,planeNum)
multiPlane = false;
if isfield(self.expInfo,'nPlane')
nPlane = self.expInfo.nPlane;
if nPlane >1
if planeNum >= 1 && planeNum <= nPlane