-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMUSCLEMOTION v1-1beta.ijm
1309 lines (1180 loc) · 43.7 KB
/
MUSCLEMOTION v1-1beta.ijm
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
//BJ van Meer//L Sala
//F Burton//
//Leiden University Medical Center - 2017
macro "MUSCLEMOTION Action Tool - C1422444T0c10MTac10M;" {
//STATIC PARAMETERS
showStatus("Initialization...");
run("Input/Output...", "jpeg=100");
var versionNumber="1.0";
var referenceFrameSlice=1; //if nothing is set somehow, the reference frame will be set to 1
var hideIntermediateResults=true;
//this speeds up calculations by hiding some result windows
var checkClip=true;
//simple tool to check clipping in the plot
var checkSpeedlinearity=true;
//displays the final window to compare the measured speed and speed calculated from the measured contraction
var manualReferenceFrame = false; //will be changed to true if selected
var drawPeaks=true; //if transients are analyzed, the peaks are drawn
//DEFAULT VALUES - you might want to change this to have your custom defaults selected once you select 'Yes, but keep it simple'.
var default_recordedFramerate = 100; //frames per second
var default_speedWindow = 2; //frames; see UserManual
var default_MPstartRange = 1; //frame number
var default_MPendRange = -1; //frame number; -1 is infinite
var default_autoDetectStart = 1; //frame number; estimation at least 2 contraction periods between autoDetectStart and autoDetectStop
var default_autoDetectStop = 300; //frame number; estimation at least 2 contraction periods between autoDetectStart and autoDetectStop
var default_lowValueN = 20; //frames; see UserManual
var default_unitySelectionN = 10; //frames; see UserManual
var default_PeakDetectionWindow = 20; //frames; estimation around 0.75*[contraction period]
var default_peakThreshold = 30; //percentage
var default_baselineThreshold = 2; //percentage
var default_baselineNumberOfPoints = 5; //frames; averaging baseline
var default_highFreqBaselineDetection = "Yes"; //"Yes" or "No"; overrules baselineThreshold and baselineNumberOfPoints
var default_binaryFormatPercentages = "100010001"; // binary format, order is 10-20-...-80-90
var default_tiffImSequence = "No"; //"Yes" or "No"
var default_guassianBlur10 = "No"; //"Yes" or "No"
//DO NOT CHANGE
var simpleAnswers = newArray("Yes", "No");
var complexAnswers = newArray("Yes, but keep it simple", "Yes & show me advanced options", "No");
var percentageOptions = newArray("10", "20","30","40","50","60","70","80","90");
arrayLength=percentageOptions.length;
var percentagesDefaults=newArray(arrayLength);
//Let's start
showStatus("Get analysis parameters");
//load stored settings or iniate defaults
var batchAnalysis = readSettingValue("c1.batchAnalysis", "No");
var recordedFramerate = readSettingValue("c1.recordedFramerate", default_recordedFramerate);
var speedWindow = readSettingValue("c1.speedWindow", default_speedWindow);
var SNRimprovement = readSettingValue("c1.SNRimprovement", "Yes, but keep it simple");
var autodetectReferenceFrame = readSettingValue("c1.autodetectReferenceFrame", "Yes, but keep it simple");
var automaticTransientDetection = readSettingValue("c1.automaticTransientDetection", "Yes, but keep it simple");
var MPstartRange = readSettingValue("c1.MPstartRange", default_MPstartRange);
var MPendRange = readSettingValue("c1.MPendRange", default_MPendRange);
var autoDetectStart = readSettingValue("c1.autoDetectStart", default_autoDetectStart);
var autoDetectStop = readSettingValue("c1.autoDetectStop", default_autoDetectStop);
var lowValueN = readSettingValue("c1.lowValueN", default_lowValueN);
var unitySelectionN = readSettingValue("c1.unitySelectionN", default_unitySelectionN);
var PeakDetectionWindow = readSettingValue("c1.PeakDetectionWindow", default_PeakDetectionWindow);
var peakThreshold = readSettingValue("c1.peakThreshold", default_peakThreshold);
var baselineThreshold = readSettingValue("c1.baselineThreshold", default_baselineThreshold);
var baselineNumberOfPoints = readSettingValue("c1.baselineNumberOfPoints", default_baselineNumberOfPoints);
var highFreqBaselineDetection = readSettingValue("c1.highFreqBaselineDetection", default_highFreqBaselineDetection);
var binaryFormatPercentages = readSettingValue("c1.binaryFormatPercentages", default_binaryFormatPercentages);
var tiffImSequence = readSettingValue("c1.tiffImSequence", default_tiffImSequence);
var guassianBlur10 = readSettingValue("c1.guassianBlur10", default_guassianBlur10);
//get array from string save format
countOnes=0;
for(findOne=0;findOne<lengthOf(binaryFormatPercentages);findOne++){
if(substring(binaryFormatPercentages,findOne,findOne+1)=="1"){
countOnes=countOnes+1;
percentagesDefaults[findOne]=true;
}
else{
percentagesDefaults[findOne]=false;
}
}
percentages=newArray(countOnes);
countOnes=0;
for(findOne=0;findOne<lengthOf(binaryFormatPercentages);findOne++){
if(substring(binaryFormatPercentages,findOne,findOne+1)=="1"){
percentages[countOnes]=(findOne+1)*10;
countOnes=countOnes+1;
}
}
//Dialog #1
Dialog.create("Analysis parameter wizard");
Dialog.addRadioButtonGroup(" A. Do you want to analyze a directory containing multiple TIFFs or subdirectories (batch)?\n", simpleAnswers, 0, 2, batchAnalysis);
Dialog.addRadioButtonGroup(" B. Do you want to analyze a TIFF image sequence instead of a stack?\n", simpleAnswers, 0, 2, tiffImSequence);
Dialog.addRadioButtonGroup(" C. Do you want to add a Gaussian blur to cancel out repetitive patterns?\n", simpleAnswers, 0, 2, guassianBlur10);
Dialog.addMessage("D. What is the frame rate of your recording(s)?");
Dialog.addNumber(" ", recordedFramerate, 0, 5, "frames/second");
Dialog.addMessage("E. What speedWindow would you like to use?");
Dialog.addNumber(" ", speedWindow, 0, 5, "frames");
Dialog.addMessage("Please refer to the UserManual for an instruction how to choose the correct reference frame.");
Dialog.addRadioButtonGroup(" F. Do you want to decrease noise in your output?\n", complexAnswers, 0, 2, SNRimprovement);
Dialog.addMessage("Please refer to the UserManual for more information. Computational time will increase.");
Dialog.addRadioButtonGroup(" G. Do want MUSCLEMOTION to detect your reference frame?\n", complexAnswers, 0, 2, autodetectReferenceFrame);
Dialog.addMessage("The default is YES, but in some situations the program might fail to detect the correct reference \nframe. This is setup dependent, be careful to check your output carefully. Please refer to the \nUserManual for more information.");
Dialog.addRadioButtonGroup(" H. Do you want MUSCLEMOTION to analyze your transients?\n", complexAnswers, 0, 2, automaticTransientDetection);
Dialog.show();
//grab data
batchAnalysis = Dialog.getRadioButton();
tiffImSequence = Dialog.getRadioButton();
guassianBlur10 = Dialog.getRadioButton();
recordedFramerate = Dialog.getNumber();
speedWindow = Dialog.getNumber();
SNRimprovement = Dialog.getRadioButton();
autodetectReferenceFrame = Dialog.getRadioButton();
automaticTransientDetection = Dialog.getRadioButton();
//write data from dialog 1
writeSettingOption("c1.batchAnalysis", batchAnalysis);
writeSettingOption("c1.tiffImSequence", tiffImSequence);
writeSettingOption("c1.guassianBlur10", guassianBlur10);
writeSettingValue("c1.recordedFramerate", recordedFramerate, 0);
writeSettingValue("c1.speedWindow", speedWindow, 0);
writeSettingOption("c1.SNRimprovement", SNRimprovement);
writeSettingOption("c1.autodetectReferenceFrame", autodetectReferenceFrame);
writeSettingOption("c1.automaticTransientDetection", automaticTransientDetection);
//Do something with the values given. Load default settings if simple option is chosen
var samplingTime=(1/recordedFramerate)*1000;
secondDialogSNR = false;
secondDialogARF = false;
secondDialogTA = false;
if(batchAnalysis=="Yes"){
batchDirLoad=true;
}
else{
batchDirLoad=false;
}
if(SNRimprovement=="Yes & show me advanced options"){
secondDialogSNR = true;
var maxProject = true;
}
else if(SNRimprovement=="Yes, but keep it simple"){
var maxProject = true;
MPstartRange = default_MPstartRange;
MPendRange = default_MPendRange;
}
else{
var maxProject = false;
}
if(autodetectReferenceFrame=="Yes & show me advanced options"){
secondDialogARF = true;
autodetectReferenceFrame = true;
}
else if(autodetectReferenceFrame=="Yes, but keep it simple"){
autodetectReferenceFrame = true;
lowValueN=default_lowValueN;
unitySelectionN=default_unitySelectionN;
autoDetectStart=default_autoDetectStart;
autoDetectStop=default_autoDetectStop;
}
else{
autodetectReferenceFrame = false;
manualReferenceFrame = true;
}
if(automaticTransientDetection=="Yes & show me advanced options"){
secondDialogTA = true;
automaticTransientDetection = true;
}
else if(automaticTransientDetection=="Yes, but keep it simple"){
automaticTransientDetection = true;
PeakDetectionWindow=default_PeakDetectionWindow;
peakThreshold=default_peakThreshold;
percentages=percentages;
baselineThreshold=default_baselineThreshold;
baselineNumberOfPoints=default_baselineNumberOfPoints;
highFreqBaselineDetection=default_highFreqBaselineDetection;
}
else{
automaticTransientDetection = false;
}
//Dialog #2
if(secondDialogSNR || secondDialogARF){
Dialog.create("Analysis parameter wizard");
Dialog.addMessage("Please check the UserManual for detailed instructions per option.");
if(secondDialogSNR){
Dialog.addMessage("----------------------------- SNR -----------------------------");
Dialog.addMessage("What is the starting frame for SNR improvement?");
Dialog.addNumber(" ", MPstartRange, 0, 5, "(default = 1)");
Dialog.addMessage("What is the end frame for SNR improvement?");
Dialog.addNumber(" ", MPendRange, 0, 5, "(default = -1 = infinite)");
Dialog.addMessage(" ");
}
if(secondDialogARF){
Dialog.addMessage("----- Automatic Reference Frame (ARF) Detection ------");
Dialog.addMessage("What is the starting frame for ARF Detection?");
Dialog.addNumber(" ", autoDetectStart, 0, 5, "(default = 1)");
Dialog.addMessage("What is the end frame for ARF Detection?");
Dialog.addNumber(" ", autoDetectStop, 0, 5, "(default = 300)");
Dialog.addMessage("What is the number of low points for ARF Detection?");
Dialog.addNumber(" ", lowValueN, 0, 5, "frames (default = 20)");
Dialog.addMessage("What is the number of points near the unity line?");
Dialog.addNumber(" ", unitySelectionN, 0, 5, "frames (default = 10)");
}
Dialog.show();
if(secondDialogSNR){
MPstartRange = Dialog.getNumber();
MPendRange = Dialog.getNumber();
}
if(secondDialogARF){
autoDetectStart = Dialog.getNumber();
autoDetectStop = Dialog.getNumber();
lowValueN = Dialog.getNumber();
unitySelectionN = Dialog.getNumber();
}
}
if(secondDialogTA){
Dialog.create("Analysis parameter wizard");
Dialog.addMessage("Please check the UserManual for detailed instructions per option.");
Dialog.addMessage("--------- Automatic Transient Analysis ----------");
Dialog.addMessage("What do you estimate as peak width?");
Dialog.addNumber(" ", PeakDetectionWindow, 0, 5, "frames (~0.75*frames per period, default = 20)");
Dialog.addMessage("What is the minimum amplitude compared to all values in the plot to be considered a peak?");
Dialog.addNumber(" ", peakThreshold, 0, 5, "% (default = 30%)");
Dialog.addMessage("What percentages of the transient do you want in your output?");
Dialog.addCheckboxGroup(1, 9, percentageOptions, percentagesDefaults);
Dialog.addMessage("What is percentage around baseline that you consider noise?");
Dialog.addNumber(" ", baselineThreshold, 0, 5, "% (default = 2)");
Dialog.addMessage("What is number of points you would like to average in the baseline?");
Dialog.addNumber(" ", baselineNumberOfPoints, 0, 5, "frames (default = 5)");
Dialog.addRadioButtonGroup(" Would you like to optimize for high frequencies and select the minimum before each peak?\n", simpleAnswers, 0, 2, highFreqBaselineDetection);
Dialog.show();
PeakDetectionWindow = Dialog.getNumber();
peakThreshold = Dialog.getNumber();
baselineThreshold = Dialog.getNumber();
baselineNumberOfPoints = Dialog.getNumber();
highFreqBaselineDetection = Dialog.getRadioButton();
countNumberPercentages=0;
binaryFormatPercentages="";
for(opt=0;opt<percentageOptions.length;opt++){
if(Dialog.getCheckbox()==true){
binaryFormatPercentages=binaryFormatPercentages+"1";
countNumberPercentages=countNumberPercentages+1;
}
else{
binaryFormatPercentages=binaryFormatPercentages+"0";
}
}
percentages = newArray(countNumberPercentages);
countOnes=0;
for(findOne=0;findOne<lengthOf(binaryFormatPercentages);findOne++){
if(substring(binaryFormatPercentages,findOne,findOne+1)=="1"){
percentages[countOnes]=(findOne+1)*10;
countOnes=countOnes+1;
}
}
}
//write data from dialog 2 & 3
writeSettingValue("c1.MPstartRange", MPstartRange, 0);
writeSettingValue("c1.MPendRange", MPendRange, 0);
writeSettingValue("c1.autoDetectStart", autoDetectStart, 0);
writeSettingValue("c1.autoDetectStop", autoDetectStop, 0);
writeSettingValue("c1.lowValueN", lowValueN, 0);
writeSettingValue("c1.unitySelectionN", unitySelectionN, 0);
writeSettingValue("c1.PeakDetectionWindow", PeakDetectionWindow, 0);
writeSettingValue("c1.peakThreshold", peakThreshold, 0);
writeSettingValue("c1.baselineThreshold", baselineThreshold, 0);
writeSettingValue("c1.baselineNumberOfPoints", baselineNumberOfPoints, 0);
writeSettingOption("c1.highFreqBaselineDetection", highFreqBaselineDetection);
writeSettingValue("c1.binaryFormatPercentages", binaryFormatPercentages, 0);
//Convert some values
if(highFreqBaselineDetection=="Yes"){
highFreqBaselineDetection=true;
}
else{
highFreqBaselineDetection=false;
}
//Get user input for saveDir
saveDir = getDirectory("Select a directory to save your outputfiles");
//select folder or file
//batch mode
if(batchDirLoad==true){
startDir = getDirectory("Choose a directory to analyze");
dirList1=getDirsInDir(startDir);
fileList1=getFilesInDir(startDir);
for(cDir=0;cDir<fileList1.length;cDir++){
fileList1[cDir]=startDir+fileList1[cDir];
}
//Get dirs in startDir and subfolders deeper
if(dirList1[0]!=0){
for(addDir=0;addDir<dirList1.length;addDir++){
dirList2=getDirsInDir(startDir+dirList1[addDir]);
if(dirList2[0]!=0){
for(y=0;y<dirList2.length;y++){
dirList2[y]=dirList1[addDir]+dirList2[y];
}
dirList1=Array.concat(dirList1,dirList2);
}
}
}
//Get files in startDir en subfolders
for(y=0;y<dirList1.length;y++){
fileList2=getFilesInDir(startDir+dirList1[y]);
if(fileList2[0]!=0){
for(cDir=0;cDir<fileList2.length;cDir++){
fileList2[cDir]=startDir+dirList1[y]+fileList2[cDir];
}
if(fileList1[0]==0){
fileList1=fileList2;
}
else{
fileList1=Array.concat(fileList1,fileList2);
}
}
}
Array.sort(fileList1);
Array.print(fileList1);
fileList=newArray(1);
for(checkExt=0;checkExt<fileList1.length;checkExt++){
if(endsWith(fileList1[checkExt],"tif") || endsWith(fileList1[checkExt],"png") || endsWith(fileList1[checkExt],"avi")){
if(fileList[0]==0){
fileList[0]=fileList1[checkExt];
}
else{
fileList=Array.concat(fileList,fileList1[checkExt]);
}
}
}
Array.print(fileList);
if(fileList[0]==0){exit("No images found");}
numberOfFiles=fileList.length;
}
//single file mode
else{
path = File.openDialog("Choose a file to analyze");
numberOfFiles=1;
}
//loop through the files to analyze
for(fileCounter=0;fileCounter<numberOfFiles;fileCounter++){
//CLEANUP and start log
close("*");
run("Clear Results");
print("\\Clear");
print("Log started...");
getDateAndTime(year, month, week, day, hour, min, sec, msec);
print("Date: "+day+"-"+month+"-"+year);
print("Time: "+hour+":"+min+":"+sec);
print("***");
//Print parameters to Log
print("Algorithm tool version number: "+versionNumber);
print("recordedFramerate: "+recordedFramerate);
print("speedWindow: "+speedWindow);
print("referenceFrameSlice: "+referenceFrameSlice);
print("maxProject: "+maxProject);
if(maxProject==true){
print("MPstartRange: "+MPstartRange);
print("MPendRange: "+MPendRange);
}
print("hideIntermediateResults: "+hideIntermediateResults);
print("checkClip: "+checkClip);
print("checkSpeedlinearity: "+true);
print("autodetectReferenceFrame: "+autodetectReferenceFrame);
if(autodetectReferenceFrame==true){
print("***autodetectReferenceFrame parameters");
print("*lowValueN: "+lowValueN);
print("*unitySelectionN: "+unitySelectionN);
print("*autoDetectStart: "+autoDetectStart);
print("*autoDetectStop: "+autoDetectStop);
print("***");
}
print("manualReferenceFrame: "+manualReferenceFrame+ " NOTE:overruled if autodetectReferenceFrame is true");
print("automaticTransientDetection: "+automaticTransientDetection);
if(automaticTransientDetection==true){
print("***automaticTransientDetection parameters");
print("*PeakDetectionWindow: "+PeakDetectionWindow);
print("*peakThreshold: "+peakThreshold);
print("*drawPeaks: "+drawPeaks);
print("*percentages: ");Array.print(percentages);
print("*baselineThreshold: "+baselineThreshold);
print("*baselineNumberOfPoints: "+baselineNumberOfPoints);
print("*highFreqBaselineDetection: "+highFreqBaselineDetection);
print("*guassianBlur10: "+guassianBlur10);
print("*tiffImSequence: "+tiffImSequence);
print("***");
}
print("batchDirLoad: "+batchDirLoad);
if(batchDirLoad==true){
print("BatchDir path="+fileList[fileCounter]);
}
//specify path if batchDirLoad is turned on
if(batchDirLoad==true){
path=fileList[fileCounter];
}
fileDir=File.getParent(path);
//check what kind of file we are going to analyze and open it
var LoadingAvi=false;
var LoadingImageSequence=false;
if(endsWith(path, "avi")){
LoadingAvi=true;
run("AVI...", "select=["+path+"] use");
}
else if(endsWith(path, "png") || tiffImSequence=="Yes"){
LoadingImageSequence=getImageSequence(path);
}
else{
run("TIFF Virtual Stack...", "open=["+path+"]");
}
rename("orginal-stack");
print(" ");
print("----------------- Evaluating file:"+File.nameWithoutExtension+" -----------------");
showStatus("Analyzing stack...");
Stack.getDimensions(width, height, channels, slices, frames);
if(frames>slices){
slices=frames;
}
//Run some basic tests:
if(recordedFramerate<50){
print("WARNING: Recorded framerate is low");
}
//check if file is a stack or a sequence
if(slices<2){
LoadingImageSequence=getImageSequence(path);
}
//if it is still not a stack, stop the macro
if(slices<2){
close("*");
run("Clear Results");
exit("Image was not a stack. \nStack required for this macro, please try again.");
}
//some more checks regarding reference frame autodetection
if(autodetectReferenceFrame==true){
if(autoDetectStop<=autoDetectStart){
autoDetectStart=(autoDetectStop-1);
print("WARNING: autoDetectStart set to "+autoDetectStart+" since it should be smaller than autoDetectStop ("+autoDetectStop+").");
}
if(autoDetectStop>=slices){
autoDetectStop=(slices-speedWindow-1);
print("WARNING: autoDetectStop set to "+autoDetectStop+" since it should be smaller than stack number ("+slices+") minus speedWindow ("+speedWindow+") minus 1 (Reference frame).");
}
if(lowValueN>=autoDetectStop){
lowValueN=(autoDetectStop-1);
print("WARNING: lowValueN set to "+lowValueN+" since it should be smaller than autoDetectStop ("+autoDetectStop+").");
}
if(lowValueN<=unitySelectionN){
unitySelectionN=(lowValueN-1);
print("WARNING: unitySelectionN set to "+unitySelectionN+" since it should be smaller than lowValueN ("+lowValueN+").");
}
}
//Speed measurement
startTime=getTime();
//enable batchmode
if(hideIntermediateResults==true){
setBatchMode(true);
}
//preperation of names and output folders
showStatus("Preparing output folders and names...");
var outputName=File.getName(path);
outputName=replace(outputName, ".png", "");
outputName=replace(outputName, ".tif", "");
outputName=replace(outputName, ".avi", "");
dirMakeName=saveDir+File.separator+outputName+"-Contr-Results";
if (!File.isDirectory(dirMakeName)){
File.makeDirectory(dirMakeName);
}
else {
dirVersion=1;
dirMakeName=saveDir+File.separator+outputName+"-Contr-Results-"+dirVersion;
while (File.isDirectory(dirMakeName)){
dirMakeName=saveDir+File.separator+outputName+"-Contr-Results-"+dirVersion;
dirVersion=dirVersion+1;
}
File.makeDirectory(dirMakeName);
}
var savePath=dirMakeName;
resultFile=getFileName("Overview-results");
logFile=getFileName("Log_file");
//MAIN SCRIPT
showStatus("Reference frame selection...");
referenceFrameSlice=getReferenceFrame();
showStatus("Calculating contraction...");
//OPTIONAL: use maximum projection masking to improve SNR, var declared in initialization
if(maxProject==true){
pixelsOfInterest();
}
//Calculate contraction
lfhMeanArray=getContractionData();
customPlotZaxis("Contraction", lfhMeanArray);
//saving data
contractionFile=getFileName("contraction");
writeFile(contractionFile);
//calculate speed of contraction
lfhMeanArraySpeed=getSpeedData();
customPlotZaxis("Speed of contraction", lfhMeanArraySpeed);
//saving data
speedFile=getFileName("speed-of-contraction");
writeFile(speedFile);
//check whether the calculated speed and measured speed are similar in terms of ratio
if(checkSpeedlinearity==true){
speedLinCompare(lfhMeanArraySpeed, lfhMeanArray);
}
//save results
updateResults();
//REACHING END OF MACRO
//Show timing and save results
print("Elapsed time (ms): "+(getTime()-startTime));
print("----------------- Evaluation finished -----------------");
saveAs("Results", resultFile);
selectWindow("Log");
run("Text...", "save=["+logFile+"]");
setBatchMode(false);
} //end of for loop dirCounter
} //end of macro
//Function library
function getImageSequence(imPath){
countTrim=0;
close("orginal-stack");
run("Image Sequence...", "open=["+imPath+"] sort use");
rename("orginal-stack");
Stack.getDimensions(width, height, channels, slices, frames);
if(frames>slices){
slices=frames;
}
print(slices+" and name: "+imPath);
return true
}
function getDirsInDir(dir){
list = getFileList(dir);
var dirList=newArray(1);
for (i=0; i<list.length; i++) {
if (endsWith(list[i], "/")){
if (dirList[0]==0){
dirList[0]=list[i];
}
else{
dirList = Array.concat(dirList,list[i]);
}
}
}
return dirList;
}
function getFilesInDir(dir){
list = getFileList(dir);
fileListT=newArray(1);
for (i=0; i<list.length; i++) {
if (!endsWith(list[i], "/")){
if (fileListT[0]==0){
fileListT[0]=list[i];
}
else{
fileListT = Array.concat(fileListT,list[i]);
}
}
}
if(endsWith(fileListT[0], "png") || tiffImSequence=="Yes"){
fileListB=newArray(1);
fileListB[0]=fileListT[0];
}
else{
fileListB=fileListT;
}
return fileListB;
}
function openVirtualStack(VirtualStackName, deleteReferenceFrame){
if(hideIntermediateResults==true){
setBatchMode(true);
}
if(LoadingImageSequence){
run("Image Sequence...", "open=["+path+"] sort use");
}
else if(LoadingAvi){
run("AVI...", "select=["+path+"] use");
}
else{
run("TIFF Virtual Stack...", "open=["+path+"]");
}
rename(VirtualStackName);
if(deleteReferenceFrame==true){
setSlice(referenceFrameSlice);
run("Delete Slice");
setSlice(1);
}
}
function pixelsOfInterest() {
//identify pixels of interest in speed stack by masking with a threshold based on standard deviation
showStatus("Improving Signal to Noise Ratio (SNR)...");
openVirtualStack("original-stack-small", true);
newImage("maxProjectStack", "32-bit black", width, height, 1);
setBatchMode(true);
if(MPendRange==-1){MPendRange=slices;}
else if(MPendRange>slices){MPendRange=slices;}
for(lfhIndex=MPstartRange;lfhIndex<MPendRange;lfhIndex++){
selectWindow("original-stack-small");
setSlice(lfhIndex);
run("Duplicate...", "title=subtractTemp");
if(guassianBlur10=="Yes"){
run("Gaussian Blur...", "sigma=10");
}
imageCalculator("Difference create 32-bit stack", "subtractTemp","reference-frame");
run("Concatenate...", " title=[maxProjectStack] image1=maxProjectStack image2=[Result of subtractTemp] image3=[-- None --]");
selectWindow("maxProjectStack");
run("Z Project...", "projection=[Max Intensity]");
rename("maxProjectStackTemp");
close("maxProjectStack");
selectWindow("maxProjectStackTemp");
rename("maxProjectStack");
close("subtractTemp");
}
close("original-stack-small");
setBatchMode("show");
selectWindow("maxProjectStack");
getStatistics(nothing, mean, min, max, stdDev);
var lucaVar = (mean + stdDev);
setThreshold(lucaVar, max);
run("Make Binary");
}
function getContractionData(){
//routine to calculate image[i]-image[ref]
showStatus("Calculating contraction...");
if(hideIntermediateResults==true){
setBatchMode(true);
}
openVirtualStack("original-stack-small", true);
lfhMeanArray=newArray(slices-1);
setBatchMode(true);
for(lfhIndex=1;lfhIndex<slices;lfhIndex++){
selectWindow("original-stack-small");
setSlice(lfhIndex);
run("Duplicate...", "title=subtractTemp");
if(guassianBlur10=="Yes"){
run("Gaussian Blur...", "sigma=10");
}
imageCalculator("Difference create 32-bit stack", "subtractTemp","reference-frame");
if(maxProject==true){
imageCalculator("Multiply create 32-bit stack", "Result of subtractTemp","maxProjectStack");
}
getStatistics(LFHnothing, LFHmean, LFHmin, LFHmax, LFHstdDev);
lfhMeanArray[lfhIndex-1]=LFHmean;
close("Result of subtractTemp");
close("subtractTemp");
}
close("Result of Result of subtractTemp");
close("original-stack-small");
if(hideIntermediateResults==false){
setBatchMode(false);
}
return lfhMeanArray;
}
function getSpeedData(){
//routine to calculate image[i]-image[i-1]
showStatus("Calculating speed of contraction...");
if(hideIntermediateResults==true){
setBatchMode(true);
}
openVirtualStack("original-stack-small", true);
openVirtualStack("second-stack", true);
for(shift=0;shift<speedWindow;shift++){
run("Delete Slice"); //-1 because reference frame is removed
}
selectWindow("original-stack-small");
setSlice(slices-1);
for(shift=0;shift<speedWindow;shift++){
run("Delete Slice");
}
lfhMeanArraySpeed=newArray(slices-speedWindow-1);
setBatchMode(true);
for(lfhIndex=1;lfhIndex<(slices-speedWindow);lfhIndex++){
selectWindow("original-stack-small");
setSlice(lfhIndex);
run("Duplicate...", "title=OriginalSubtractTemp");
if(guassianBlur10=="Yes"){
run("Gaussian Blur...", "sigma=10");
}
selectWindow("second-stack");
setSlice(lfhIndex);
run("Duplicate...", "title=SecondSubtractTemp");
if(guassianBlur10=="Yes"){
run("Gaussian Blur...", "sigma=10");
}
imageCalculator("Difference create 32-bit stack", "OriginalSubtractTemp","SecondSubtractTemp");
if(maxProject==true){
imageCalculator("Multiply create 32-bit stack", "Result of OriginalSubtractTemp","maxProjectStack");
}
getStatistics(LFHnothing, LFHmean, LFHmin, LFHmax, LFHstdDev);
lfhMeanArraySpeed[lfhIndex-1]=LFHmean;
close("Result of OriginalSubtractTemp");
close("OriginalSubtractTemp");
close("SecondSubtractTemp");
}
close("Result of Result of OriginalSubtractTemp");
close("original-stack-small");
close("second-stack");
if(hideIntermediateResults==false){
setBatchMode(false);
}
return lfhMeanArraySpeed;
}
function customPlotZaxis(parameter, yArrayMean) {
//plot z-profile function that can cope with arrays that have only the same value
if(hideIntermediateResults==true){
setBatchMode(true);
}
Stack.getDimensions(Zwidth, Zheight, Zchannels, Zslices, Zframes);
yConstant=false;
sortedArray=Array.copy(yArrayMean);
Array.sort(sortedArray);
if(sortedArray[0]==sortedArray[sortedArray.length-1]){
yArrayMean[0]=yArrayMean[0]-0.01;
yConstant=true;
print("Warning: Array of "+parameter+" was constant. In order to plot, 0.01 has been removed from the first value");
}
//create the actual plot
arrayLength=yArrayMean.length;
xTimeArray=newArray(arrayLength);
xTimeArray[0]=0;
for(xTimeIndex=1;xTimeIndex<yArrayMean.length;xTimeIndex++){
xTimeArray[xTimeIndex]=xTimeArray[xTimeIndex-1]+samplingTime;
}
Plot.create("Z-Plot of "+parameter, "Time (ms)", parameter+ " (a.u.)", xTimeArray, yArrayMean);
if(automaticTransientDetection==true && parameter=="Contraction"){
transientAnalysis(yArrayMean);
}
Plot.setColor("black");
Plot.show();
rename(parameter+"-profileData");
if(hideIntermediateResults==true){
setBatchMode(false);
setBatchMode(true);
}
Plot.makeHighResolution(parameter+"-profile",4.0);
saveAs("Jpeg", savePath+File.separator+parameter);
if(hideIntermediateResults==true){
setBatchMode(false);
setBatchMode(true);
}
selectWindow(parameter+"-profileData");
//warning flag for clipping
if(checkClip==true){
if(sortedArray[sortedArray.length-1]==sortedArray[sortedArray.length-2] && sortedArray[sortedArray.length-1]==sortedArray[sortedArray.length-3]){
if (yConstant==false){
print("Warning: it seems like your "+parameter+" plot is clipping!");
}
}
}
return yArrayMean;
}
function getFileName(parameter) {
//check if file exists and else add/change version number
version=1;
fileName=savePath+File.separator+parameter+".txt";
while (File.exists(fileName)){
fileName=savePath+File.separator+parameter+version+".txt";
version=version+1;
}
return fileName;
}
function writeFile(filename) {
//save plot values
Plot.getValues(xvalues, yvalues);
f = File.open(filename);
for (i=0; i<xvalues.length; i++){
print(f, xvalues[i]+"\t"+yvalues[i]);
}
File.close(f);
}
function getReferenceFrame(){
if(autodetectReferenceFrame==true){
showStatus("Autodetecting reference frame...");
//prepare stacks
openVirtualStack("second-stack", false);
setSlice(1);
for(shift=0;shift<speedWindow;shift++){
run("Delete Slice");
}
openVirtualStack("original-stack-small", false);
setSlice(slices-1);
for(shift=0;shift<speedWindow;shift++){
run("Delete Slice");
}
speedY=newArray(autoDetectStop-autoDetectStart+1);
setBatchMode(true);
for(lfhIndex=1;lfhIndex<speedY.length+1;lfhIndex++){
selectWindow("original-stack-small");
setSlice(lfhIndex);
run("Duplicate...", "title=OriginalSubtractTemp");
if(guassianBlur10=="Yes"){
run("Gaussian Blur...", "sigma=10");
}
selectWindow("second-stack");
setSlice(lfhIndex);
run("Duplicate...", "title=SecondSubtractTemp");
if(guassianBlur10=="Yes"){
run("Gaussian Blur...", "sigma=10");
}
imageCalculator("Difference create 32-bit stack", "OriginalSubtractTemp","SecondSubtractTemp");
getStatistics(LFHnothing, LFHmean, LFHmin, LFHmax, LFHstdDev);
speedY[lfhIndex-1]=LFHmean;
close("Result of OriginalSubtractTemp");
close("OriginalSubtractTemp");
close("SecondSubtractTemp");
}
setBatchMode(false);
//close stacks
close("second-stack");
close("original-stack-small");
//prepare arrays
speedY=Array.slice(speedY,autoDetectStart,autoDetectStop);
speedYshift=Array.copy(speedY);
speedYshift=Array.slice(speedYshift,1);
speedY=Array.trim(speedY,speedY.length-1);
arrayLength=speedY.length;
radianPoints=newArray(arrayLength);
for(d=0;d<speedY.length;d++){
radianPoints[d]=sqrt((speedY[d]*speedY[d])+(speedYshift[d]*speedYshift[d]));
}
indicesVal=Array.rankPositions(radianPoints);
low=0;
unitySelection=newArray(lowValueN);
for(d=0;d<lowValueN-1;d++){
index=indicesVal[d];
unitySelection[d]=abs((speedY[index]/speedYshift[index])-1);
}
//check which [unitySelectionN] of the unitySelection is smallest
indicesUni=Array.rankPositions(unitySelection);
for(d=0;d<unitySelectionN-1;d++){
indexTrans=indicesUni[d];
index=indicesVal[indexTrans];
lowValue=(speedY[index]*speedYshift[index])*unitySelection[indexTrans];
if(d==0){
low=lowValue;
lowIndex=index;
}
else if(low>lowValue){
low=lowValue;
lowIndex=index;
}
}
selectWindow("orginal-stack");
setSlice((lowIndex+1));
run("Duplicate...", "title=reference-frame");
if(guassianBlur10=="Yes"){
run("Gaussian Blur...", "sigma=10");
}
print("Automatic detected reference frame: frame "+lowIndex+1);
referenceFrameSlice=lowIndex+1;
}
else if(manualReferenceFrame==true){
setSlice(1);
waitForUser( "Pause","Manual reference frame selection.\nSelect the reference frame and press 'OK'.");
getSliceNumber();
referenceFrameSlice=getSliceNumber();
print("Manual selected reference frame: frame "+getSliceNumber());
run("Duplicate...", "title=reference-frame");
if(guassianBlur10=="Yes"){
run("Gaussian Blur...", "sigma=10");
}
}
else {
//set frame 1 to be the reference frame
setSlice(1);
run("Duplicate...", "title=reference-frame");
if(guassianBlur10=="Yes"){
run("Gaussian Blur...", "sigma=10");
}
print("No selection reference frame: frame 1");
referenceFrameSlice=1;
}
selectWindow("orginal-stack");
run("Delete Slice");
return referenceFrameSlice;
}
function speedLinCompare(speedY, contractionY) {
arrayLength=speedY.length;
calculatedSpeed=newArray(arrayLength);
for(j=0;j<speedY.length;j++){
calculatedSpeed[j]=abs(contractionY[j+1]-contractionY[j]);
}
//normalize both speed arrays
arrayLength=speedY.length-1;
calculatedSpeedNorm=newArray(arrayLength);
measuredSpeedNorm=newArray(arrayLength);
Array.getStatistics(calculatedSpeed, calculatedSpeedMin, calculatedSpeedMax, calculatedSpeedMean, calculatedSpeedStd);
Array.getStatistics(speedY, speedYMin, speedYMax, speedYMean, speedYStd);
for(j=0;j<calculatedSpeedNorm.length-1;j++){
calculatedSpeedNorm[j]=(calculatedSpeed[j]-calculatedSpeedMin)/(calculatedSpeedMax-calculatedSpeedMin);
measuredSpeedNorm[j]=(speedY[j]-speedYMin)/(speedYMax-speedYMin);
}
xTimeArray=newArray(arrayLength);
xTimeArray[0]=0;
for(xTimeIndex=1;xTimeIndex<measuredSpeedNorm.length;xTimeIndex++){
xTimeArray[xTimeIndex]=xTimeArray[xTimeIndex-1]+samplingTime;
}
//create plot for visual inspection
Plot.create("Comparison calculated (red) and measured (black) speed-lowRes", "Time (ms)", "Normalized contraction speed (a.u.)", xTimeArray, measuredSpeedNorm);
Plot.setColor("red");
Plot.add("line", xTimeArray, calculatedSpeedNorm);
Plot.setColor("black");
Plot.show();
Plot.makeHighResolution("Comparison calculated (red) and measured (black) speed",4.0);
saveAs("Jpeg", savePath+File.separator+"Comparison calculated (red) and measured (black) speed.jpg");
if(hideIntermediateResults==true){
setBatchMode(false);
setBatchMode(true);
}
}
function transientAnalysis(yValues){