-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTBS.m
More file actions
9986 lines (7817 loc) · 404 KB
/
TBS.m
File metadata and controls
9986 lines (7817 loc) · 404 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
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 TBS
% Add Ab and registration functions
methods (Static) % General stuff ===================================
%% Function: extractStructVar
% Discription: extract all variables from structure to workspace
function extractStructVar(S,ws)
% Input: S, structure
% ws, 'base' or 'caller'
% Output: void, variable in work space
fields = fieldnames(S);
for i = 1:length(fields)
assignin(ws,fields{i},S.(fields{i}));
end
end
%% Function: var2struct
% Discription: pack variable into structure, with the same name
function S = var2struct(ws,varName)
% Input: varName, cell
% ws, workspace, caller/base
% Output: S, struct
if ~iscell(varName)
error('Function var2struct: input varName is not cell array')
end
for i = 1:length(varName)
S.(varName{i}) = evalin(ws, varName{i});
end
end
%% Function: getStack
% Discription: Get stacks of an image
function stack = getStack(fileName,stackNumber)
% Input: fileName, string
% chNum, num/mat, specific stack number
% Output: stack, M*N*O matrix
% This will have error for large tif file
if nargin == 1 || isempty(stackNumber)
info = imfinfo(fileName);
stackNumber = 1:size(info,1);
end
for i = 1:length(stackNumber)
stack(:,:,i) = imread(fileName,stackNumber(i));
end
end
%% Funciton: saveStack
% Discription: save image stack
function saveStack(stack,fileName,appendTF)
% Input: stack, 3d mat
% fileName, str, w/ or w/o path
% appendTF, logical, whether only save as append
% Output: void. image will be saved on the disk
% 07202021: combine with saveStackAppend
if numel(size(stack)) > 3
stack = reshape(stack,size(stack,1),size(stack,2),[]);
warning('Stack will be saved as 3-D stack.')
end
if nargin == 2
appendTF = false;
end
for i = 1:size(stack,3)
% Not append only
if i == 1 && ~appendTF
imwrite(stack(:,:,i),fileName);
else
imwrite(stack(:,:,i),fileName,'WriteMode','append')
end
end
end
%% Function: cell2stack
% Discription: Change cell array (w/ mat) into a stacked mat
function stack = cell2stack(cellArray,dimension4stackCell)
% Updated 11082019, change cell2mat to switch and loop, much faster
% Input: cellArray, cell array w/ a mat per cell
% dimension4stackCell, dimsion for stacking the cells
% (the matrix in the cells)
% Output: stack, mat
stack = cellArray{1};
for i = 2:length(cellArray)
stack = cat(dimension4stackCell,stack,cellArray{i});
end
end
%% Function: stack2cell
% Discription: change stack (3d-mat) to cell array
function cellArray = stack2cell(stack)
% Input: stack,3d mat
% Output: cellArray, cell, 1*1*size(stack,3)
nStack = size(stack,3);
cellArray = mat2cell(stack,size(stack,1),size(stack,2),ones(nStack,1));
end
%% Function: stack2spCell
% Discription: change stack 3d mat into 3d cell with sparse matrix
% Similar as stack to cell, but each cell contains sparse mat
function stackCell = stack2spCell(stack)
% Input: stack, 3d-mat
% Output: stackCell, cell with 2d sparse mat
% Right now sparse only support double and logical
if ~islogical(stack)
stack = double(stack);
end
stackCell = TBS.stack2cell(stack);
% Change into sparse matrix
stackCell = cellfun(@(X) sparse(X),stackCell,'Uniformoutput',false);
end
%% Function: spCell2stack
% Discription: change cell with sparse matrix per cell to mat
function stack = spCell2stack(sparseCell)
% Input: sparseCell,cell array with sparse mat
% Output: stack, mat
sparseCell = cellfun(@full,sparseCell,'Uniformoutput',false);
stack = cell2mat(sparseCell);
end
%% Function: hasThisRow
% Discription: whether the table has this row
function TF = hasThisRow(tbl,rowName)
% Input: tbl, table
% rowName, str or cell
% Output: TF, logical output same size as rowName
if istable(tbl) == 0
error('Input tbl is not a table');
end
TF = ismember(rowName,tbl.Properties.RowNames);
end
%% Function: strrepRowName
% Discription: strrep old str to new string in row names
function tbl = strrepRowName(tbl,oldStr,newStr)
% Input: tbl, table
% oldStr, newStr, old and new string for the row name
if ~istable(tbl)
error('Input tbl is not a table');
end
rowNames = tbl.Properties.RowNames;
rowNames = cellfun(@(X) strrep(X,oldStr,newStr),rowNames,...
'Uniformoutput',false);
tbl.Properties.RowNames = rowNames;
end
%% Function: getScaleTform
% Discription: get transformation matrix (3x3, 4x4) for scaling
function scaleTform = getScaleTform(scaleFactor,dim)
% Input: scaleFactor, num
% dim, dimension for the transformation
% scaleTform: dim x dim mat
scaleTform = eye(dim+1);
scaleTform(1,1) = scaleFactor;
scaleTform(2,2) = scaleFactor;
end
%% Function: find3
% Discription: find nonzeros element in 3d space
function [row, col, z, v] = find3(matIn)
% Input: matIn, mat, 3d
sz = size(matIn);
ind = find(matIn);
v = matIn(ind);
v = double(v);
[row,col,z] = ind2sub(sz,ind);
end
%% Function: im2xyzv
% Discription: convert image pixel to xyzv (double)
function xyzv = im2xyzv(im)
% Input: im, mat, image stack
[y,x,z,v] = TBS.find3(im);
xyzv = [x,y,z,v];
end
%% Function: isOutOfRngeDot
% Discription: check whether dots are out of pixel area
function TF = isOutOfRngeDot(sz,dotMat)
% Input: sz, mat, image size
% dotMat, mat, coordinates, same size as sz
% Output: TF, logical vector
% Shift x-y to row-col
sz(1:2) = fliplr(sz(1:2));
% 02/14/2022: add round
dotMat = round(dotMat);
TF = dotMat < 1 | dotMat > sz;
TF = any(TF,2);
end
%% Function: xyzv2im
% Discription: convert the sub to image
function im = xyzv2im(sz,xyz,v)
% Note, if v is empty, will be logical
% Update: include out of range and round
% Input: sz, size of the image
% xyz, mat, xy/xyz of the location
% v, vector, value
xyz = round(xyz);
row = TBS.isOutOfRngeDot(sz,xyz);
if any(row)
xyz = xyz(~row,:);
if ~isempty(v)
v = v(~row,:);
end
warning(['Function xyzv2im: eliminated out of range dots ',...
num2str(sum(row))]);
end
% Allow both 2 or 3 dimensiton
if size(xyz,2) == 2
ind = sub2ind(sz,xyz(:,2),xyz(:,1));
elseif size(xyz,2) >= 3
ind = sub2ind(sz,xyz(:,2),xyz(:,1),xyz(:,3));
end
if isempty(v) || islogical(v)
im = false(sz);
im(ind) = true;
else
% Add value using the same class type
classType = class(v);
classFh = str2func(classType);
im = zeros(sz);
im = classFh(im);
im(ind) = v;
end
end
%% Function: xyz2v
% Discription: get the value in im
function v = xyz2v(xyz,im)
% Input: xyz, mat, coordinates
% im, 3-D or 2-D mat
% Output: v, vector,
xyz = round(xyz);
if size(xyz,2) == 2
ind = sub2ind(size(im),xyz(:,2),xyz(:,1));
elseif size(xyz,2) == 3
ind = sub2ind(size(im),xyz(:,2),xyz(:,1),xyz(:,3));
end
v = im(ind);
end
%% Funciton: getImValidLim
% Discription: get the valid pixel limits along an axis
function axLim = getImValidLim(im,axNum)
% Input: im, image stack
% axNum, num, of axis
% Output: axLim, mat with min and max pixel location
% Find the other axes
plate = 1:ndims(im);
plate = plate(plate ~= axNum);
axLim = any(im,plate);
axLim = [find(axLim,1,'first'),find(axLim,1,'last')];
end
%% Function: imtrim
% Discription: trim out the zero element from image in specific ax
function im = imtrim(im,ax)
% Input: im, mat, image stack (max 3-d)
% ax, mat, axes to be trimmed
% Output: im, trimed image stack
for a = ax
% Get axis limit
axLim = TBS.getImValidLim(im,ax(a));
% Trim
switch a
case 1
im = im(axLim(1):axLim(2),:,:);
case 2
im = im(:,axLim(1):axLim(2),:);
case 3
im = im(:,:,axLim(1):axLim(2));
otherwise
error('Currently only support 3 axis')
end
end
end
%% Function: rotz/roty/rotx
% Discription: Rotation matrix for rotations around z/y/x-axis
% Input: ang, num, angle
function R = rotz(ang)
R = eye(3);
R(1,1) = cosd(ang); R(1,2) = sind(ang);
R(2,1) = -sind(ang); R(2,2) = cosd(ang);
end
function R = roty(ang)
R = eye(3);
R(1,1) = cosd(ang); R(1,3) = -sind(ang);
R(3,1) = sind(ang); R(3,3) = cosd(ang);
end
function R = rotx(ang)
R = eye(3);
R(2,2) = cosd(ang); R(2,3) = sind(ang);
R(3,2) = -sind(ang); R(3,3) = cosd(ang);
end
%% Function: imfillHoles3
% Discription: fill holes in stacks of images
function im = imfillHoles3(im)
% Input/output: im, image stacks
for z = 1:size(im,3)
im(:,:,z) = imfill(im(:,:,z),'holes');
end
end
%% Function: outlineSpCell2Full
% Discription: get full stack from compressed data
function stack = outlineSpCell2Full(outlineSpCell)
% Input: cell or mat
% Output: mat
if iscell(outlineSpCell)
outlineSpCell = TBS.spCell2stack(outlineSpCell);
end
stack = TBS.imfillHoles3(outlineSpCell);
end
%% Function: RB2paddingSize
% Discription: get the padding size from imref2d/3d
function paddingSize = RB2paddingSize(RB)
% Input: RB, imref2d/3d object
% Output: paddingSize, 1 x 2/3 vector
if isa(RB,'imref2d')
paddingSize = -[RB.XWorldLimits(1),RB.YWorldLimits(1)]+0.5;
elseif isa(RB,'imref3d')
paddingSize = -[RB.XWorldLimits(1),RB.YWorldLimits(1),...
RB.ZWorldLimits(1)]+0.5;
else
error('Currently onlly suport imref2d/3d.')
end
end
%% Function: RB2imSize
% Discription: get the image size from imref2d/3d
function imSize = RB2imSize(RB)
% Input: RB, imref2d/3d object
% Output: image, 1 x 2/3 vector
% row & col
imSize = [RB.YIntrinsicLimits; RB.XIntrinsicLimits];
if isa(RB,'imref3d')
imSize = [imSize; RB.ZIntrinsicLimits];
end
imSize = imSize(:,2)-imSize(:,1);
imSize = reshape(imSize,1,[]);
end
%% Function: repmat2size
% Discription: repmat input1 to the same size as input2
function X = repmat2size(X,Y,dim)
% Input: X, mat/cell
% Y, cell
% dim, dimension for repmat
% Output: X, cell
n = cellfun(@(X) size(X,dim),Y);
if isempty(dim) || dim == 1
X = arrayfun(@(X2,Y2) repmat(X2,Y2,1),X,n,'UniformOutput',false);
elseif dim == 2
X = arrayfun(@(X2,Y2) repmat(X2,1,Y2),X,n,'UniformOutput',false);
end
end
%% Function: getParaInObj
% Discription: Get the median of parameter in objects from cell
% array
function computedPara = getParaInObj(objCell,parameterStr,funStr)
% Input: objCell, cell of object
% parameterStr, str, string of parameter name
% funStr, str, string of function name
% Output: computedPara, num, computed parameters
% Get the parapeters
computedPara = cellfun(@(X) X.(parameterStr),objCell,'UniformOutput',false);
computedPara = cell2mat(computedPara);
% Apply the function to the parameters
fh = str2func(funStr);
if contains(funStr,{'min','max'}) == 1
computedPara = fh(computedPara,[],'all');
else
computedPara = fh(computedPara,'all');
end
end
%% Function: fitWithoutOutlier
% Discription: get fit without outlier using the default outlier setting
function [fitOutlierExclude,outlier] = fitWithoutOutlier(x,y,fitType)
% Input: x, mat
% y, mat/cell
% fitType, str, type for fitting
% Output: fitOutlierExclude,fitObject
% outlier, mat/cell(if y is cell, same format as y)
sizeY = [];
% if y is cell array, get the mat size inside each cell
if iscell(y) % Change required: This need to put outside the funciton
sizeY = cellfun(@(X) size(X,1),y);
y = vertcat(y{:});
end
if iscell(x)
x = vertcat(x{:});
end
fitOriginal = fit(x,y,fitType);
% Find outlier, using the diff between modeled and real value
fdata = feval(fitOriginal,x);
outlier = fdata - y;
outlier = isoutlier(outlier);
% Fit without outlier
fitOutlierExclude = fit(x,y,fitType,'Exclude',outlier);
% Format the outlier into same format as y
if isempty(sizeY) == 0
% Format the outliers into cell array as y
outlier = mat2cell(outlier,sizeY,1);
end
end
%% Function: shuffleRows
% Discription: random shuffle rows
function [A,I] = shuffleRows(A)
% Input & output: A, cell/mat
% I, row number for the shuffling
n = size(A,1);
I = randperm(n);
A = A(I,:);
end
%% Function: repmat2cell
% Discription: repmat content to the same row number as cell array
function cellOut = repmat2cell(matIn,cellIn)
% Input: matIn, cell/mat, content for repmat
% cellIn, cell, prvides row format for each cell
% Output: cellOut, cell, with repeated rows of matIn per cell
if size(matIn,1)~= size(cellIn,1)
error('The length of both input are not the same.');
elseif size(cellIn,2) ~= 1
error('There are more than one column for 2nd input.')
end
if ~iscell(matIn)
matIn = mat2cell(matIn,ones(size(matIn,1),1));
end
% Allow empty dotCell
I = ~cellfun(@isempty,cellIn);
cellOut = cell(size(cellIn));
cellOut(I) = cellfun(@(X,Y) repmat(X,size(Y,1),1),...
matIn(I),cellIn(I),'UniformOutput',false);
end
%% Function: nonzeroAvgFilter
% Discription: average filter of non-zero elements
function im = nonzeroAvgFilter(im,h)
% 03162022, delete exclude0
% Input & output: im, mat, image
% h, mat, filter
% Sum
im2 = convn(im,h,'same');
% number of voxel/pixel
fh = @(X) cast(X,class(im));
n = fh(im ~= 0);
n = convn(n,h,'same');
im = im2./n;
% Delete pixel with nan
TF = isnan(im);
im(TF) = 0;
end
%% Function: nonzeroMedFilt
function im = nonzeroMedFilt(im,h)
% Note: parfor is used
% Input: h, logical matrix, filter voxel
sz = size(im);
% Loop through all voxel within the filter
I = find(h);
disp(['Function nonzeroMedFilt in progress, filter size ',...
num2str(numel(I))]);
im2 = [];
parfor i = 1:numel(I) % parfor
h2 = false(size(h));
h2(i) = true;
iIm = convn(im,h2,'same');
im2(:,i) = reshape(iIm,[],1);
disp(['Voxel: ',num2str(i)]);
end
% Set 0 to nan, get median without nan
im2(im2 == 0) = nan;
im2 = median(im2,2,'omitnan');
im = reshape(im2,sz);
end
%% Function: getMedEdges
% Discription: get middle of edges
function edges = getMedEdges(edges)
% Input & output: edges, vector
edges = edges(1:end-1)+edges(2:end);
edges = edges./2;
end
%% Function: axLabelSettings
% Discription: Set front and size for all axes
function axLabelSettings(frontName,frontSize)
% Input: frontName, str, front name
% fontSize, num, front size
ax = {'XAxis'; 'YAxis'; 'ZAxis'};
g = gca;
for i = 1:numel(ax)
g.(ax{i}).Label.FontName = frontName;
g.(ax{i}).Label.FontSize = frontSize;
end
end
%% Function: accumarrayMean
% Discription: accumarray-mean function, faster
function B = accumarrayMean(ind,data)
% Input: ind, vector, Output indices
% data, vector
% Output: B, vector, mean of data for each indices
data = accumarray(ind,data);
n = accumarray(ind,1);
B = data./n;
end
%% Function: nestTF
function TF = nestTF(TF,TF2)
TF(TF) = TF2;
end
end
methods (Static) % Default settings ================================
%% Function: getSystemSetting
function sysSetting = getSysSetting
% Output: sysSetting, struct
sysSetting = [];
% Image setting general
sysSetting.slidePrepend = 'Slide';
sysSetting.delimiter = '_';
sysSetting.imFormat = '.tif';
sysSetting.nNameElement = 5;
sysSetting.sectionElement = 1;
sysSetting.seqElement = 2;
sysSetting.regionElement = 3;
sysSetting.tileElement = 4;
sysSetting.nameElement = [sysSetting.sectionElement,...
sysSetting.regionElement];
% Image prepend: sequencing /immuno data
sysSetting.seqPrepend = 'Seq';
sysSetting.abPrepend = 'Ab';
% Image append: correction type
sysSetting.pixelCorrectAppend = '_pixelCorrected';
sysSetting.localCorrectAppend = '_localCorrected';
sysSetting.chCorrectAppend = '_chCorrected';
sysSetting.temporaryAppend = '_temporary';
% Special setting for experiments
sysSetting.injectionAppend = 'Injection';
sysSetting.somaAppend = 'Soma';
end
%% Function: getInitialFixSeq
% Discription: define fix seq using directory, allow special case
function initialFixSeq = getInitialFixSeq(directory)
% Input: directory, struct/str
% Output: initialFixSeq, num
if isobject(directory)
directory = directory.main;
end
if contains(directory,{'09062019_65A_3rd','08282019_65A_2nd'})
initialFixSeq = 8;
else
initialFixSeq = 9;
end
end
%% Function: getImageSetting
function imageSetting = getImageSetting(sysSetting,directory)
imageSetting = [];
excludeSeq = []; % Exclude cycles
imageSetting.mouseID = '65A';
imageSetting.sectionLoc = {'L','R'};
imageSetting.chNum = 4;
imageSetting.tileSize = [1200 1200];
imageSetting.resolution = 0.55;
imageSetting.slideThickness = 20;
imageSetting.cameraOffset = 100;
imageSetting.imageBits = 'uint16';
imageSetting.overlapPrecentage = 17;
imageSetting = TBS.getOverlapPixel(imageSetting);
% Cell array for tile position
% ie: 20x whole brain: [11, 20]; 10x whole brain: [6, 10];
% per row: [nRow, nCol]
tileSetting = [1 1; 2 2; 3 2; 3 3; 11 20];
imageSetting.tilePos = TBS.getTilePosition(tileSetting);
if nargin == 1 || isempty(directory)
return
end
% Seq setting -------------------------------------------------
% Get max seq number
% getFolderNumber(directory,folderAppend)
maxSeq = TBS.getFolderNumber(directory.main,sysSetting.seqPrepend);
maxSeq = max(maxSeq);
imageSetting.seqCycles = TBS.getSeqCycles(maxSeq,excludeSeq);
imageSetting.initialFixSeq = TBS.getInitialFixSeq(directory.main);
end
%% Function: getBcSetting
% Discription: barcode & bscalling setting
function bcSetting = getBcSetting
bcSetting = [];
% Maximum intervel for sequencing result
bcSetting.maxSeqInterval = 3;
% Sequencing cycles are not included for counting BC length
bcSetting.seqNotInMinBscallCycles = [9,10];
% Minimum BC length
% 08312021: nSeeq - exclude cycle number - maxHamming
bcSetting.minBClen = 13;
% Minimum digits of nucleotide
bcSetting.minDiffNt = 3;
% Max hamming distance for sequantical matching
bcSetting.maxHamming = 2;
% Number of nt for degenerate BC
bcSetting.degenerateN = 6;
% Setting for soma areas --------------------------------------
% Section number of the soma zone (mannually identified)
bcSetting.somaSectionRnge = [9 70];
bcSetting.somaSlideRnge = ceil(bcSetting.somaSectionRnge./2);
% min counts for soma pixel (arbitrary)
bcSetting.nearSomaRolony.minPixelCount = 35;
% min distance to soma pixel (arbitrary)
% Note 10 pixel distance doesnt work
bcSetting.nearSomaRolony.minDistance = 20;
% Setting for count filters -----------------------------------
% Count filter for soma and axon
% Unspecific barcode is 9403
bcSetting.minSomaCount = 0;
bcSetting.maxSomaCount = 7000;
bcSetting.minAxonCount = 3;
bcSetting.maxAxonCount = 1000;
% Min axonBC count for the strongest target region
bcSetting.regionMinCount = 10;
% Setting for isSoma ------------------------------------------
% Soma radius range, in micron
bcSetting.hasSoma.somaR = 100;
% Min pixel count within radius
bcSetting.hasSoma.minSomaPixelCount = 80;
% Setting for rolony correction -------------------------------
% max same dot dotID for different dot
bcSetting.maxDiffDotId = 4;
% Setting for floating rolony slide ---------------------------
% Region to be included for floating rolony computation
bcSetting.floatingSlide.regionName = {'Injection','Thalamus','Visual'};
% Minimum rolony count for floating rolony
% (not close to any rolony in the neighboring secitons)
bcSetting.floatingSlid.threhold = 3;
% Settinf for glia --------------------------------------------
% Radius for glia cells
bcSetting.gliaR = 200;
end
%% Function: getRefSetting
% Discription: get reference settings
function refSetting = getRefSetting(directory)
% Input: directory, str, Directory of reference map & txt
% Output: refSetting, struct, reference settings
refSetting = [];
refSetting.directory = directory;
% Reference scale of these maps: micron per pixel
refSetting.refScale = 1/25;
% reference map: allen ccf3, 25 um, nissle
refSetting.nisslName = 'ara_nissl_25.nrrd';
% Annotation map, same resolution
refSetting.annoName = 'annotation_25.nrrd';
% Average template, same resolution
refSetting.avgName = 'average_template_25.nrrd';
% Annotation structure ----------------------------------------
% Name for txt file
refSetting.annoTxtName = 'Allen_api_MouseBrainAtlas.txt';
% Annotation structure
cd(directory);
annoStruct = fileread(refSetting.annoTxtName);
annoStruct = jsondecode(annoStruct);
annoStruct = annoStruct.msg;
refSetting.annoStruct = annoStruct;
end
%% Function: mouseSlideNum
% Discription: special case for slide number for each mouse
function slideNum = mouseSlideNum(slideNum,mouseID)
% Input & output: slideNum, vector/num, original slide number
% mouseID, str
if strcmp(mouseID,'65A') == 1
% ie. 12 change to 13
slideNum(slideNum > 11.5) = slideNum(slideNum > 11.5) + 1;
% Change to 12
slideNum(slideNum == 11.5) = slideNum(slideNum == 11.5) + 0.5;
end
end
%% Function: QCtform
% Discription: quanlity check for tform using scale
function TF = QCtform(tform,tolerance)
% Input: tform, mat, transformation matrix
% tolerance,num, tolerance of error, <1
% Output: TF, logical, whether it pass transformation matrix
% Defualt tolerance
if nargin == 1
tolerance = 0.8;
end
% 07032021: exclude reflection
if tform(1,1) < 0 && tform(2,2) < 0
TF = false; return
end
% Check individual axis
scale = sum(abs(tform(1:2,1:2)),2);
% 1/toerance: > 1 (upper limit)
TF1 = all(scale >= tolerance & scale <= 1/tolerance);
% Check area size (determinant)
% No reflection is allowed (no negative determinant)
area = det(tform(1:2,1:2));
TF2 = area >= tolerance & area <= 1/tolerance;
TF = TF1 & TF2;
end
%% Function: getTilePosition
% Discription: get tile position using number of rows and columns
function tilePos = getTilePosition(tileSetting)
% Note, tile position only support snake left-up pattern
% updated 03132021
% Input: tileSetting, mat, one tiling patter per row
% 1st column, row #; 2nd column, col #
% Output: tilePos, cell, one tiling pattern per cell
tilePos = {};
for i = 1:size(tileSetting)
nRow = tileSetting(i,1);
nCol = tileSetting(i,2);
[nGrid,iTilePos] = indivTilePosition(nRow,nCol);
tilePos{nGrid} = iTilePos;
end
% Function: indivTilePosition ------------------------------
% Discription: get individual tile position
function [nGrid,iTilePos] = indivTilePosition(nRow,nCol)
% Input: nRow/nCol, num, row/column number for tiling
% Output: nGrid, num, number of tile
% iTilePos, mat
nGrid = nRow*nCol; % Number of grid
% Construct current tile positions (snake left-up pattern)
iTilePos = 1:nGrid;
iTilePos = reshape(iTilePos,nCol,nRow);
iTilePos = iTilePos';
iTilePos(1:2:end,:) = fliplr(iTilePos(1:2:end,:));
iTilePos = flipud(iTilePos);
end
end
%% Function: getChScore2Inten
% Discription: default chScore2Inten for 65A
function chProfileSetting = getChScore2Inten(chProfileSetting)
% This setting is mannually selected, use for all experiments
% for 65A, uneven equal intensity will affect the alignment
% using chCorrected image
chProfileSetting.chScore2Inten.mean = 68.5;
chProfileSetting.chScore2Inten.std = 39.5;
end
%% Function: getChColor
% Discription: Get the color of the channel
function iColor = getChColor(iCh)
% Input: iCh, number
% Output: iColor, str
switch iCh
case 1
iColor = 'c';
case 2
iColor = 'y';
case 3
iColor = 'm';
case 4
iColor = 'k';
otherwise
error('Function getChColor: Channel number is not supported');
end
end
%% Function: get2ndInfectionBC
% Discription: get barcode form secondary infection
function BC = get2ndInfectionBC
% Output: mannual identified BC from secondary infection
% one BC per row; one col per seq cycle
BC = [1 2 4 2 4 1 1 1 3 2 1 3 1 4 4 1 1;
2 3 2 2 1 3 1 4 3 2 4 4 3 3 3 3 1;
2 3 4 1 2 2 2 2 3 2 1 3 1 4 2 3 4;
1 2 2 0 2 2 2 0 1 0 2 1 2 0 1 0 0;
3 4 2 1 3 4 4 1 3 2 2 3 3 2 1 1 2;
4 4 4 1 2 4 2 1 3 2 1 1 2 3 1 4 3;
1 2 1 1 2 3 1 3 3 2 2 1 4 1 1 2 2;
4 1 4 1 3 4 1 3 3 2 1 3 1 2 4 1 3;
2 1 1 1 4 3 4 1 3 2 1 3 3 4 3 2 1;
1 2 1 4 4 3 1 3 3 2 3 3 1 3 4 3 4;
2 3 2 4 2 1 4 3 3 2 2 4 2 1 2 2 3;
3 2 4 2 4 1 3 2 3 2 3 2 1 1 2 3 3;
4 1 2 1 3 1 1 2 3 2 3 1 1 2 1 1 1;
1 2 1 4 2 3 4 4 3 2 1 3 1 4 4 1 4;
2 4 3 1 2 4 1 3 3 2 1 4 4 1 1 2 3;
2 2 2 3 3 4 2 2 3 2 2 4 3 1 2 3 2;
2 1 2 3 4 2 3 3 2 2 0 2 2 0 2 3 1];
end
%% Function: delWrongTile
% Discription: delete wrong tiles (identified mannually)
function tbl = delWrongTile(tbl)
% Input & output: table
% Wrong tile list (defined mannually)
wrongTile = {'EF65ASlide49R_Seq15_Contra',...
'EF65ASlide49R_Seq15_Visual',...
'EF65ASlide49R_Seq15_SupCol',...
};
% Add delimiter for the tile name
wrongTile = cellfun(@(X) [X,'_'],wrongTile,'UniformOutput',false);
% Find and delete the row
rowName = tbl.Properties.RowNames;
row = contains(rowName,wrongTile);
tbl = tbl(~row,:);
end
%% Function: correctSelfAlignment
% Discription: correct self-alignment transformation matrix
function corrSelfAlignTform = correctSelfAlignment(refSectionNum,imageSetting,sysSetting,directory)
% Mannual defined correction
% Input: refSectionNum, num, reference section number
% imageSetting,sysSetting,directory, struct
% Output: corrSelfAlignTform, table, corrected self-aligned tform
load(fullfile(directory.main,'selfAlignTform.mat'));
% Section number
sectionNum = TBS.getSectionNumber(selfAlignTform,imageSetting,sysSetting);
% Translation correction --------------------------------------
% Correction for translation
corrTranslation = sectionNum - refSectionNum;
% Mannual define translation for 0.055 scale factor: 0.4
corrTranslation = abs(corrTranslation).*(-0.4);
D = {};
parfor i = 1:size(selfAlignTform,1) % parfor
iTranslation = [corrTranslation(i),0];
% Transformation matrix for translation
iTform = eye(3);
iTform(3,1:2) = iTranslation;
iTform = affine2d(iTform);
sz = size(selfAlignTform.D{i});
% Combine displacement field
iD = TBS.tform2D(iTform,sz);
iD = TBS.Doperation(selfAlignTform.D{i},iD);
D{i,1} = iD;
disp(['Corrected selfAlignTform: ',num2str(i)]);
end
selfAlignTform.D = D;
% Delete distored sections ------------------------------------
% Mannually identified
delSection = [108];
row = ismember(sectionNum,delSection);
selfAlignTform = selfAlignTform(~row,:);
% Save --------------------------------------------------------
corrSelfAlignTform = selfAlignTform;
save(fullfile(directory.main,'corrSelfAlignTform.mat'),'corrSelfAlignTform');