-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseven.js
2422 lines (2117 loc) · 82.7 KB
/
seven.js
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
importPackage(Packages.ij);
importPackage(Packages.java.io);
importPackage(Packages.java.awt);
importPackage(Packages.ij.measure);
importClass(Packages.ij.gui.GenericDialog);
load(IJ.getDirectory("ImageJ")+"complex.js");
//// seven.js
//// a library to analyze filopodia using tip markers
////
//// ImageJ API documentation:
//// http://rsb.info.nih.gov/ij/developer/api/
////
//// Java API documentation:
//// http://docs.oracle.com/javase/7/docs/api/overview-summary.html
////
//// JavaScript documentation for the Rhino interpreter:
//// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
// Useful constants
var newline = "\n";
var sep = File.separator;
var WATER_AUTO = -2;
var LOCAL_AUTO = -1;
var GLOBAL_AUTO = 0;
var digits = 6; // number of significant digits for logging
var DEBUG = false;
var dt = 0.793; // default timestep in seconds if not available from logfile
var boxwidth_um = 0.8; // height in microns of linescan
var minarea_um2 = 30; // minimum area in um^2; prevents glitches caused by very small ROIs
var interpolation = 0.5; // scaling factor <= 1 for interpolation of the cell perimeter ROI
var MEASUREMENTS = Measurements.AREA + Measurements.MEAN +
Measurements.MEDIAN + Measurements.MIN_MAX + Measurements.MODE +
Measurements.SHAPE_DESCRIPTORS + Measurements.PERIMETER +
Measurements.SKEWNESS + Measurements.KURTOSIS;
// Assay-specific options: check these before running!
var format = "tif"; // file extension
var maskformat = "zip"; // file extension for mask file, if different
var resultsformat = "csv"; // file extension for results files
var linescantag = "newzeroscan";
var anaversion = "7";
var frame = 1; // frame of the raw data to analyze (starting with 1)
var minfp = 1; // set to 1 unless you know what this does
var banded = true; // Whether to look at cell perimeter band
var thresholdcode = LOCAL_AUTO; // see list above
var skiptips = false; // skip filopod tip search
var semi = false; // set to true to wait for manual corrections - recommended with local thresholds
var editlinescans = false; // manual editing of manual ROIs after they are loaded
var onlyreviewlinescans = false; // manual review of linescans but don't overwrite
// Threshold images to determine cell boundaries
// generates two images: the binary mask and the mask applied to the original image
function ThresholdCells(anadir, acqname, thresholds, prefix) {
var acqlen = acqname.length;
var sublist = anadir.list();
var imagefile = null;
var subname = "";
// Preliminary step - copy any images in subdirectories to the root
for (var i=0; i < sublist.length; i++) {
IJ.log(sublist[i]);
var subdir = new File(anadir.getCanonicalPath(), sublist[i]);
if (subdir.isDirectory() && acqlen > 0) {
var imagelist = subdir.list();
for (var j=0; j < imagelist.length; j++) {
var imagename = imagelist[j];
var imagefile = new File(subdir.getCanonicalPath(), imagename);
if (Packages.java.lang.Integer.parseInt(imagename.length()) > acqlen) {
if (imagename.substring(0,acqlen) == acqname) {
CopyFile(imagefile, anadir, imagename);
}
}
}
}
}
// Apply thresholds to create a mask:
// loop over the list of thresholds, then over the images
// Masks are stored in subdirectories named with the form prefix_a_i
for (var a = 0; a < thresholds.length; a++) {
var th = thresholds[a];
for (var i = 0; i < sublist.length; i++) {
var imagefile = new File(anadir.getCanonicalPath(), sublist[i]);
var imagename = sublist[i];
// Raw images are identified by numeric ID in the original file name
// Because the ID is handled as a string, first count the characters (digits)
var digits = 0;
for (var j = acqlen; j < imagename.length(); j++) {
var testchar = imagename.substring(j,j+1);
if (testchar == "_" || testchar == ".") {
break;
}
digits++;
}
// Read the image ID from the file name and create the analysis subdirectory
var imagename_character_length = Packages.java.lang.Integer.parseInt(imagename.length());
//IJ.showMessage("is "+IJ.d2s(imagename_character_length,0)+" > "+IJ.d2s(acqlen+digits,0)+"?");
if (imagename_character_length > acqlen+digits && !imagefile.isDirectory()) {
if (imagename.substring(0,acqlen) == acqname && getExt(imagename) != resultsformat) {
// number subdirectories using the number following the acqname prefix
subdir_index = imagename.substring(acqlen,acqlen+digits);
if (filterInt(subdir_index) > 0) {
subname = prefix+IJ.d2s(th,0)+"_"+subdir_index;
} else {
subname = prefix+IJ.d2s(th,0)+"_"+
IJ.d2s(i+1,0); // in case image file names are not numbered
}
var subdir = new File(root.getCanonicalPath(), subname);
if (!subdir.isDirectory()) {
subdir.mkdir();
}
// Subdirectory contains a hint to the original file name
hint = subdir.getCanonicalPath() + sep + "hint.txt";
// Save the hint as a text file
saveText(hint, imagename, false);
// If the mask file already exists, skip processing
var f = new File(subdir.getCanonicalPath(),
"Capture-mask-"+anaversion+"."+maskformat);
if (!f.exists()) {
// Process image
var mask = IJ.openImage(imagefile);
if (mask.getNSlices() >= frame)
mask.setSlice(frame);
var img = mask.duplicate();
if (img.getNSlices() >= frame)
img.setSlice(frame);
// Read the pixel size, converting cm->um
var cal = mask.getCalibration();
cm2um(cal);
var dx = cal.getX(1);
// Cell boundaries are determined by median filter followed by thresholding.
// Length scale for the filter is approx. 2 um (originally 10 pixels @ 63X mag.)
var mask_width_um = 1;
var radius_med = Math.ceil(mask_width_um/dx);
IJ.run(mask, "Median...", "radius="+IJ.d2s(radius_med,0)+" slice stack");
// Input image is 16-bit, but some methods need 8-bit image,
// so the image lookup table must be normalized before processing
IJ.run(mask, "Enhance Contrast", "saturated=0.35");
// Apply threshold to create the mask
switch(th) {
case GLOBAL_AUTO: // Global threshold (calculated using entire XY image)
IJ.run(mask, "8-bit", "stack");
IJ.setAutoThreshold(mask, "Moments stack");
IJ.run(mask, "Convert to Mask", "method=Moments background=Light stack");
break;
case WATER_AUTO:
case LOCAL_AUTO: // Local threshold (Bernsen algorithm)
IJ.run(mask, "8-bit", "stack");
// Length scale for local thresholds = 2x the mask radius
var bernsen_width_um = 4;
var radius_th = Math.ceil(bernsen_width_um/dx);
IJ.run(mask, "Auto Local Threshold", "method=Bernsen radius="+
IJ.d2s(radius_th,0)+" parameter_1=0 parameter_2=0 white stack");
IJ.run(mask, "Convert to Mask", "method=Moments background=Light stack");
if (th == WATER_AUTO) {
// Use watershed to separate neighboring cells
IJ.run(mask, "Watershed", "stack");
}
// cleanup for local thresholding artifacts
IJ.run(mask, "Fill Holes", "stack"); // fills holes in nuclei unless they are on the edge of the field
IJ.run(mask, "Open", "stack"); // zaps 1-pixel wide features
invertImage(mask);
break;
default: // Global threshold, using a manually specified value
if (th < 0)
IJ.showMessage("Invalid image threshold!");
IJ.setThreshold(mask, 0, th);
IJ.run(mask, "8-bit", "stack");
IJ.run(mask, "Convert to Mask", "method=Moments background=Light stack");
}
//Return to the original image and normalize
IJ.run(img, "Enhance Contrast", "saturated=0.35");
// Let the user manually correct the mask file
img.show();
if (img.getNSlices() >= frame) // reset image position due to potential side effects
img.setSlice(frame);
mask.show();
if (mask.getNSlices() >= frame) // reset image position due to potential side effects
mask.setSlice(frame);
if (semi) {
new Packages.ij.gui.WaitForUserDialog(
"Manual Corrections", "Please press OK when done.").show();
}
saveImage(mask, maskformat, anadir, subname+"/Capture-mask", Packages.java.lang.Integer.parseInt(anaversion));
// Apply the mask to the image (not required, but useful for visual inspection)
ic = new Packages.ij.plugin.ImageCalculator();
img2 = ic.run("Min stack create", mask, img);
if (img2.getNSlices() >= frame)
img2.setSlice(frame);
invertImage(img2);
saveImage(img2, format, anadir, subname+"/Capture-threshold", Packages.java.lang.Integer.parseInt(anaversion));
//Clean up
mask.changes = false;
img.changes = false;
img2.changes = false;
if (!DEBUG) {
mask.close();
img.close();
img2.close();
}
}
}
}
}
}
}
// Analyze cells using the mask to calculate ROIs, cell area and mean intensity
function AnalyzeCells(img1, anadir, depth, resultname, intensities, areas, cell_xs, cell_ys) {
if (img1.getNSlices() >= frame)
img1.setSlice(frame);
var img3 = img1.duplicate();
if (img3.getNSlices() >= frame)
img3.setSlice(frame);
var h = img1.getHeight();
var w = img1.getWidth();
// set image scale cm->um
var cal = img1.getCalibration();
cm2um(cal);
var stats = img1.getStatistics(MEASUREMENTS);
var fullarea = stats.area;
var bgval = stats.dmode;
//Open mask file
var maskfile = anadir + "Capture-mask-"+anaversion+"." + maskformat;
var mask = openIf(maskfile, maskformat);
setMask(mask, depth, false);
// get ROI of cell body
var rs = new RoiSet();
var rsname = anadir+"analysis-RoiSet"+anaversion+".zip";
var rsfile = new File(rsname);
// if rsfile does not exist, can still use the rsmanager window
if (rsfile.exists())
rs.runCommand("Open", rsname);
if (rs.getName(1) != "Cells") {
IJ.showMessage("Error", "ROI Manager not populated");
exit;
}
// get xy coordinates to identify cells with wand tool
var rois = rs.getRoisAsArray(); // returns Java array of ij.gui.Roi[]
var xs = rois[1].getPolygon().xpoints; // returns Java array of int[]
var ys = rois[1].getPolygon().ypoints; // returns Java array of int[]
// invert image
invertImage(img1);
var ic = new Packages.ij.plugin.ImageCalculator();
var img2 = ic.run("Max create stack", img1, mask);
if (img2.getNSlices() >= frame)
img2.setSlice(frame);
// invert image
invertImage(img2);
// return to original image for quantitation
var rs = new RoiSet();
// set image scale cm->um
var maskcal = mask.getCalibration();
cm2um(maskcal);
var maskstats = mask.getStatistics(MEASUREMENTS);
// this is where the cell outlines are stored as ROIs
for (var i = 0; i < xs.length; i++) {
IJ.doWand(mask, xs[i], ys[i], 0, "4-connected");
StoreRoi(mask, mask.getRoi(), resultname+" "+IJ.d2s(i,0), rs);
}
// save mask
saveImage(img2, format, anadir, "Capture-mask-"+resultname+anaversion, 0);
// save rois
rs.runCommand("Select All");
rs.runCommand("Save", anadir + "cell-"+resultname+"-RoiSet"+anaversion+".zip");
var rois = rs.getRoisAsArray();
// set image scale cm->um
var cal = img3.getCalibration();
cm2um(cal);
// Measure mean intensity in original unmodified image
for (var i = 0; i < rois.length; i++) {
img3.setRoi(rois[i]);
rs.select(img3, i);
var cellstats = img3.getStatistics(MEASUREMENTS);
// copy cell intensity and xy position to global data arrays
intensities[i] = cellstats.mean - bgval; // mean background-corrected cell intensity
if (xs[i] > 0 && ys[i] > 0) {
cell_xs[i] = xs[i];
cell_ys[i] = ys[i];
}
// Measure cell area and copy to global data array
areas[i] = 0;
if (cellstats.area < fullarea) // Incorrectly drawn ROIs will cover the full frame
areas[i] = cellstats.area;
IJ.log(IJ.d2s(intensities[i], 0));
}
if (!DEBUG) {
img1.close();
img2.close();
img3.close();
mask.close();
}
}
// Analysis of filopod line scans
function AnalyzeScans(img1, imagefile, anadir, boxwidth_um) {
if (img1.getNSlices() >= frame)
img1.setSlice(frame);
var h = img1.getHeight();
var w = img1.getWidth();
// set image scale cm->um
var cal = img1.getCalibration();
cm2um(cal);
var stats = img1.getStatistics(MEASUREMENTS);
var fullarea = stats.area;
var timestep = dt;
var kymodir = new File(anadir+sep+"Kymograph");
var paramtab = new Packages.ij.measure.ResultsTable();
paramtab.setPrecision(digits);
// get ROI of cell body
var rs = new RoiSet();
var roifile = new File(anadir+"scan.zip");
if (!roifile.exists() || !roifile.isFile()) {
roifile = new File(anadir+"scan.roi");
}
if (roifile.exists() && roifile.isFile()) {
if (!kymodir.isDirectory()) {
kymodir.mkdir();
}
timestep = getTimingFromLogfile(img1, imagefile, timestep);
LoadRois(rs, roifile, "");
if (editlinescans || onlyreviewlinescans) {
new Packages.ij.gui.WaitForUserDialog(
"Manual Corrections to ROI", "Please press OK when done.").show();
if (editlinescans) {
rs.runCommand("Select All");
rs.runCommand("Save",roifile.getCanonicalPath());
}
}
// Read pixel size, convert cm->um
var cal = img1.getCalibration();
cm2um(cal);
var dx = cal.getX(1);
kymograph(img1, rs, timestep, boxwidth_um, paramtab, kymodir);
// Measure intensity in the masked image
var masked = new File(anadir+sep+"Capture-mask-body"+anaversion+"-0."+format);
if (masked.isFile()) {
var img2 = IJ.openImage(masked);
if (img2.getNSlices() >= frame)
img2.setSlice(frame);
var rois = rs.getRoisAsArray();
for (var i = 0; i < rois.length; i++) {
rois[i].setStrokeWidth(1);
img2.setRoi(rois[i]);
rs.select(img2, i);
ScanLine(img2, anadir, "linescan", dx, i);
}
img2.changes = false;
if (!DEBUG) { img2.close(); }
} else {
IJ.showMessage("Could not file masked file to match "+imagefile);
}
}
// Save the results table as a delimited text file
paramtab.save(kymodir.getPath()+sep+"kymograph_results."+resultsformat);
img1.changes = false;
if (!DEBUG) { img1.close(); }
}
function ScanLine(img, dir, name, pixelwidth, index) {
var profileplot = new Packages.ij.gui.ProfilePlot(img);
var linescan = profileplot.getProfile();
//var text = "Distance (um)\tIntensity (A.U.)"+newline;
var text = "";
if (linescan != null) {
for (var j = 0; j < linescan.length; j++) {
text += IJ.d2s(j*pixelwidth, digits)+"\t"+IJ.d2s(linescan[j],0)+newline;
//IJ.log(IJ.d2s(j*pixelwidth, digits)+"\t"+IJ.d2s(linescan[j],0));
}
var textfile = dir+name+"-"+IJ.d2s(index,0)+"-"+anaversion+".txt";
//var text = IJ.getLog();
// Save the linescan as text file
saveText(textfile, text, false);
}
}
// Analysis for counting filopodia tips and registering to cells
function AnalyzeTips(img1, imagefile, anadir, imagetab, boxwidth_um, firstpass) {
if (img1.getNSlices() >= frame)
img1.setSlice(frame);
// local array for filopodia
var fparray = new Array();
// get raw image stats
var stats = img1.getStatistics(MEASUREMENTS);
var bgval = stats.dmode; // use instead of minval - this is black level of whole image
var minSNR = 3;
var noise = noiseThreshold(stats, minSNR);
// pixel size, convert cm->um
var cal = img1.getCalibration();
cm2um(cal);
var dx = cal.getX(1);
var boxheight = Math.ceil(boxwidth_um/dx); // height in pixels of linescan
var pixelsize = IJ.d2s(dx, digits);
//Open mask file
var maskfile = anadir + "Capture-mask-"+anaversion+"."+maskformat;
var mask = openIf(maskfile, maskformat);
setMask(mask, 0, true);
// get image dimensions
var h = img1.getHeight();
var w = img1.getWidth();
var nFrames = img1.getNSlices(); // ImageJ parses images as XYZ by default (treat as XYT)
var timestep = getTimingFromLogfile(img1, imagefile, dt);
// invert mask
var ic = new Packages.ij.plugin.ImageCalculator();
IJ.run(img1, "Subtract...", "value=1 stack"); // subtract 1 from raw image to avoid white pixels
var img2 = ic.run("Max create stack", img1, mask);
if (img2.getNSlices() >= frame)
img2.setSlice(frame);
var ip2 = img2.getProcessor();
// Save an intermediate image with cells masked in white; this gets used in "linescanonly" mode
saveImage(img2, format, anadir, "Capture-mask-body"+anaversion, 0);
IJ.run(img2, "Find Maxima...",
"noise="+IJ.d2s(noise,0)+" output=[Point Selection]");
var rRaw = img2.getRoi();
var rois = new RoiSet();
StoreRoi(img2, rRaw, "Raw", rois);
var nCells = 0;
var nRawTips = 0;
var tipx = rRaw.getPolygon().xpoints;
var tipy = rRaw.getPolygon().ypoints;
var nPoints = rRaw.getNCoordinates();
var maxval = Math.pow(2, 16)-1;
// Count cells
var pCells = new Polygon();
var pRawTips = new Polygon();
var pTips = new Polygon();
for (var i=0; i<nPoints; i++) {
val = getValue(img2, tipx[i], tipy[i]);
IJ.doWand(mask, tipx[i], tipy[i], 0, "4-connected");
var roi_stats = mask.getStatistics();
var maskp = mask.getProcessor();
maskp.setColor(Color.GRAY);
if (val == maxval) {
if (roi_stats.area >= minarea_um2) {
nCells++;
pCells.addPoint(tipx[i],tipy[i]);
} else {
maskp.fill(mask.getRoi()); // blackout the current ROI - indicates these ROIs are ignored
}
} else {
nRawTips++;
pRawTips.addPoint(tipx[i],tipy[i]);
}
}
// Save mask
invertImage(mask);
saveImage(mask, maskformat, anadir, "Capture-mask-cells"+anaversion, 0);
mask.changes = false;
// Clean up from masking
if (!DEBUG) { mask.close(); }
// Copy cell position to global array
var cell_xpos = new Array(nCells);
var cell_ypos = new Array(nCells);
for (var i=0; i<nCells; i++) {
cell_xpos[i] = pCells.xpoints[i];
cell_ypos[i] = pCells.ypoints[i];
}
if (pCells.npoints > 0) { // only write if populated
var rCells = new Packages.ij.gui.PointRoi(pCells);
rCells.setPosition(1, frame, 1); // specify which frame (slice) to analyze
StoreRoi(img2, rCells, "Cells", rois);
}
if (pRawTips.npoints > 0) { // only write if populated
var rRawTips = new Packages.ij.gui.PointRoi(pRawTips);
rRawTips.setPosition(1, frame, 1); // specify which frame (slice) to analyze
StoreRoi(img2, rRawTips, "RawTips", rois);
}
if (!skiptips) {
//Calculate radial distribution
var tipdata = "";
var sampletab = new Packages.ij.measure.ResultsTable();
var mpp = 0.21164;
sampletab.setPrecision(digits);
img2.setColor(Color.WHITE);
// Scan in radial pattern (approx 5 um diameter; original radius 12 px at 63X)
var scan_width = 5;
var radius_scan = Packages.java.lang.Integer.parseInt(Math.floor(scan_width/(dx*2)));
var fp = 0;
tipx = pRawTips.xpoints;
tipy = pRawTips.ypoints;
// Black out tips to improve radial search (approx 1 um square; originally 3x3 at 63X)
var blackout_width = 1;
var radius_black = Math.floor(blackout_width/(dx*2));
for (var i=0; i < nRawTips; i++) {
var x = tipx[i];
var y = tipy[i];
var xlo = x - radius_black;
var xhi = x + radius_black;
var ylo = y - radius_black;
var yhi = y + radius_black;
if (xlo < 0) { xlo = 0; }
if (ylo < 0) { ylo = 0; }
if (xhi > (w-1)) { xhi = w-1; }
if (yhi > (h-1)) { yhi = h-1; }
for (var u=xlo; u<=xhi; u++) {
for (var v=ylo; v<=yhi; v++) {
ip2.putPixel(u, v, stats.mean); // mean value of image instead of bgval or black = 0
}
}
}
// Scan tips to see if they are connected to cells
var pTips = new Polygon();
for (var a=0; a<nRawTips; a++) {
if (tipx[a] >= radius_scan && tipx[a] < (w-radius_scan) &&
tipy[a] >= radius_scan && tipy[a] < (h-radius_scan)) {
var radius_scanroi = new Packages.ij.gui.Line(
tipx[a], tipy[a], Packages.java.lang.Integer.parseInt(tipx[a]+radius_scan), tipy[a]);
radius_scanroi.setPosition(1, frame, 1); // specify which frame (slice) to analyze
img2.setRoi(radius_scanroi);
var thetastep = 3;
var nSteps = Math.ceil(360/thetastep);
img2.hide();
IJ.run(img2, "Set Scale...", "distance=1 known="+pixelsize+" pixel=1 unit=um");
IJ.run(img2, "Radial Reslice", "angle=360 degrees_per_slice="+
IJ.d2s(thetastep, 0)+" direction=Clockwise");
var radial_3d = IJ.getImage();
radial_3d.setRoi(new Packages.ij.gui.Line(0, 0, Packages.java.lang.Integer.parseInt(radius_scan-1), 0));
IJ.run(radial_3d, "Reslice [/]...", "output="+pixelsize+" slice_count=1 avoid");
var radial_2d = IJ.getImage();
IJ.run(radial_2d, "Rotate 90 Degrees Right", "");
radial_2d.setRoi(new Rectangle(0, 0, nSteps, Packages.java.lang.Integer.parseInt(radius_scan-1)));
var radial_dist = new Array(nSteps);
for (var u = 0; u < nSteps; u++) {
radial_dist[u] = 0;
for (var v = 0; v < radius_scan; v++) {
radial_dist[u] += getValue(radial_2d, u, v);
}
radial_dist[u] /= radius_scan;
}
if (!DEBUG) {
radial_3d.close();
radial_2d.close();
}
var skew = skewness(radial_dist);
if (skew > 1) {
pTips.addPoint(tipx[a],tipy[a]);
fp++; // increment filo count
}
}
}
if (pTips.npoints > 0) { // only write if populated
var rTips = new Packages.ij.gui.PointRoi(pTips);
rTips.setPosition(1, frame, 1); // specify which frame (slice) to analyze
StoreRoi(img2, rTips, "Tips", rois);
}
// Register FP to cells
var maxdistance_um = 20; // maximum distance from cell center in microns
var maxpixeldist = maxdistance_um/dx;
var regfp = fp;
var regcross = 0;
var cells_with_fp = nCells;
var fp_per_cell = new Array(nCells); // create local array for bookkeeping
// initialize to zero - probably not necessary?
for (var q=0; q<nCells; q++)
fp_per_cell[q] = 0;
// assign global array dimensions - probably not necessary (JavaScript very forgiving)
cell_per_fp = new Array(fp); // reassign dimensions of this global array
intensity_per_fp = new Array(fp); // reassign dimensions of this global array
xpos_per_fp = new Array(fp); // reassign dimensions of this global array
ypos_per_fp = new Array(fp); // reassign dimensions of this global array
for (var u=0; u<fp; u++) {
var score = 1e6;
var reg = -1;
for (var v=0; v<nCells; v++) {
var disp_x = pCells.xpoints[v] - pTips.xpoints[u];
var disp_y = pCells.ypoints[v] - pTips.ypoints[u];
var disp = Math.sqrt(Math.pow(disp_x,2)+Math.pow(disp_y,2));
if (score > disp && maxpixeldist > disp) {
score = Math.sqrt(Math.pow(disp_x,2)+Math.pow(disp_y,2));
reg = v;
}
}
if (reg >= 0) {
// Select the line connecting tip to cell center-of-area
var tiproi = new Packages.ij.gui.Line(pTips.xpoints[u],pTips.ypoints[u],
pCells.xpoints[reg],pCells.ypoints[reg]);
tiproi.setPosition(1, frame, 1); // specify which frame (slice) to analyze
img2.setRoi(tiproi);
// Update the count of registered filopodia
fp_per_cell[reg]++;
// update global data array for intensity using the unmasked img1
intensity_per_fp[u] = getValue(img1, pTips.xpoints[u], pTips.ypoints[u])
- bgval; // background-corrected peak intensity at tip
// update global data arrays for cell registration and xy position
cell_per_fp[u] = reg;
xpos_per_fp[u] = pTips.xpoints[u];
ypos_per_fp[u] = pTips.ypoints[u];
} else {
// the tip cannot be registered to a cell, i.e., it is a false positive detection event.
intensity_per_fp[u] = 0;
cell_per_fp[u] = -1;
xpos_per_fp[u] = -1;
ypos_per_fp[u] = -1;
regfp--;
}
//IJ.showMessage("index "+IJ.d2s(u,0)+", cell_per_fp = "+IJ.d2s(cell_per_fp[u],0));
}
// local array for filopodia
fparray = new Array(regfp);
var v = 0;
for (var u = 0; u < fp; u++) {
if (cell_per_fp[u] >= 0) {
fparray[v] = new Filopod(xpos_per_fp[u]*dx, ypos_per_fp[u]*dx,
pCells.xpoints[cell_per_fp[u]]*dx, pCells.ypoints[cell_per_fp[u]]*dx,
cell_per_fp[u], intensity_per_fp[u]);
if (fparray[v] == null)
IJ.error("Seven.js", "could not initialize filopod "+IJ.d2s(v,0));
v++;
}
}
if (v != regfp)
IJ.error("Seven.js", "Failed to initialize Filopod array");
// need to set line color here for contrast with white mask in img2
img2.setColor(Color.GRAY);
// Second pass to save zeroscans of filopod length
for (var u=0; u<fp; u++) {
index = cell_per_fp[u];
// IJ.log("Cell index count =" + index + "Number of filopod attached =" + fp_per_cell[index]);
//IJ.log("Filopodia u count =" + u);
if (index >= 0 && fp_per_cell[index] >= minfp) {
var scanroi = new Packages.ij.gui.Line(pTips.xpoints[u],pTips.ypoints[u],
pCells.xpoints[index],pCells.ypoints[index]);
//var angle = scanroi.getAngle();
//IJ.log("Angle value = "+ angle);
scanroi.setPosition(1, frame, 1); // specify which frame (slice) to analyze
scanroi.setStrokeWidth(1);
img2.setRoi(scanroi);
// Calculate line scan using the masked img2
ScanLine(img2, anadir, linescantag, dx, u);
// Mark with a line on the masked img2
ip2.draw(scanroi);
}
}
// Trim the count of cells
for (var z=0;z<nCells;z++) {
if (fp_per_cell[z] == 0) { cells_with_fp--; }
}
}
// Save ROIs on first pass
rois.runCommand("Select All");
rois.runCommand("Save",anadir+"analysis-RoiSet"+anaversion+".zip");
// Save ROIs on first pass, on second pass save log as well
if (!firstpass) {
// table for reporting results
var celltab = new Packages.ij.measure.ResultsTable();
celltab.setPrecision(digits);
var spacingtab = new Packages.ij.measure.ResultsTable();
spacingtab.setPrecision(digits);
var crossingtab = new Packages.ij.measure.ResultsTable();
crossingtab.setPrecision(digits);
// Spacing analysis of cell perimeter band
// Load ROIs for cells
var rs = new RoiSet();
var roifile = new File(anadir+"cell-body-RoiSet"+anaversion+".zip");
if (!roifile.exists()) {
roifile = new File(anadir+"cell-body-RoiSet"+anaversion+"+.roi");
}
// begin perimeter band analysis
if (banded && roifile.exists()) {
rs.runCommand("Open",roifile.getCanonicalPath());
var rois = rs.getRoisAsArray();
if (rs.getCount() != cell_xpos.length)
IJ.error("seven.js", "ROIs != nCells: "+IJ.d2s(rs.getCount(),0)+" != "+
IJ.d2s(cell_xpos.length,0));
// iterate over cells
for (var i = 0; i < rs.getCount(); i++) {
// begin reporting
celltab.incrementCounter();
celltab.addValue("Cell ID+1", i+1);
celltab.addValue("Cell Intensity", cell_body[i]);
celltab.addValue("Cell Area (um^2)", cell_area_body[i]);
//if (fp_per_cell[i] > 0) { // optionally only look at cells with fp
spacingtab.incrementCounter();
// analyze cells by ROI
img1.setRoi(rois[i]);
rs.select(img1, i);
if (cell_area_body[i] >= minarea_um2) {
// convert magic wand ROI to line ROI
//IJ.run(img1, "Area to Line", ""); // this leaves a gap at end
//var interp_polygon = img1.getRoi().getPolygon();
var interp_polygon = img1.getRoi().getInterpolatedPolygon(interpolation, true);
var outline_points = interp_polygon.xpoints.length;
var contour = new Array(outline_points);
var startroi = new Packages.ij.gui.Arrow(interp_polygon.xpoints[0],
interp_polygon.ypoints[0],interp_polygon.xpoints[0]+1,
interp_polygon.ypoints[0]+1);
startroi.setPosition(1, frame, 1); // specify which frame (slice) to analyze
img2.setRoi(startroi);
// Draw a 1px line on the masked img2
ip2.draw(startroi);
var narrow = new Packages.ij.plugin.Straightener();
var outline_roi = outliner(interp_polygon, outline_points, frame);
var band = new ImagePlus();
// initialize contour for lookup of u-coordinate from outline point index
for (var j = 0; j<outline_points; j++) {
if (j>1) {
var this_outline_roi = outliner(interp_polygon, j, frame);
img1.setRoi(this_outline_roi);
bandp = narrow.straighten(img1, this_outline_roi, 1);
//if (j==2)
// IJ.showMessage(IJ.d2s(this_outline_roi.getLength(),3)+"/"+IJ.d2s(outline_points,3));
contour[j] = this_outline_roi.getLength();
} else {
contour[j] = 0;
}
}
// store crossing xy point and outline point index in filopod data
for (var j = 0; j<outline_points; j++) {
var outline_x = interp_polygon.xpoints[j]*dx;
var outline_y = interp_polygon.ypoints[j]*dx;
// iterate over filopodia
for (var k = 0; k < fparray.length; k++) {
//IJ.showMessage("Index "+IJ.d2s(i,0)+" ? "+IJ.d2s(fparray[k].outline_index,0));
if (i == fparray[k].cell_index && colinear(
fparray[k].x, fparray[k].y,
fparray[k].cell_x, fparray[k].cell_y,
outline_x, outline_y)) {
var old_cross_x = fparray[k].cross_x;
var old_cross_y = fparray[k].cross_y;
var old_extension = fparray[k].extension();
fparray[k].cross_x = outline_x;
fparray[k].cross_y = outline_y;
//if (fparray[k].outline_index >= 0)
// IJ.showMessage(IJ.d2s(fparray[k].extension(),digits)+" vs "+
// IJ.d2s(old_extension,digits)+" at k="+IJ.d2s(k,0));
if (fparray[k].outline_index < 0) {
fparray[k].outline_index = j; // set the index for the first time
regcross++; // only count once per fp
} else if (fparray[k].extension() < old_extension) {
fparray[k].outline_index = j; // save the new index
} else {
// revert to previously detected crossing point and index
fparray[k].cross_x = old_cross_x;
fparray[k].cross_y = old_cross_y;
}
if (!fparray[k].colinear())
IJ.error("Seven.js", "Failed to register filopod #"+IJ.d2s(k,0));
}
}
}
// check for filopodia without crossing assignments
var noncrossing = 0;
for (var k = 0; k < fparray.length; k++) {
if (i == fparray[k].cell_index && fparray[k].outline_index <0) {
// IJ.showMessage("Cell ("+IJ.d2s(fparray[k].cell_x,2)+", "+
// IJ.d2s(fparray[k].cell_y,2)+"); Tip ("+IJ.d2s(fparray[k].x,2)+
// ", "+IJ.d2s(fparray[k].y,2)+")");
noncrossing++;
}
}
if (DEBUG && noncrossing > 0)
IJ.showMessage("missing assignments: "+IJ.d2s(noncrossing,0));
// Generate banded image from original
img1.setRoi(outline_roi);
bandp = narrow.straighten(img1, outline_roi, boxheight);
band = new ImagePlus("Perimeter band", bandp);
var bandperimeter = outline_roi.getLength(); // maximum perimeter distance in um
//var bandperimeter = band.getWidth()*dx; // alternate definition
// Set intensity threshold
var bandnoise = noise; // defined above based on whole image
var bandx = new Array(); // points of interest on the band (1-D position in um)
var filo_spacing = true;
var fps = 0;
if (filo_spacing) {
// set up for the main action found after the end of this block
bandx = new Array(fp);
for (var k = 0; k < fp; k++)
bandx[fp] = -1; // initialize array to -1
for (var k = 0; k < fparray.length; k++) {
// parametric crossing position in pixels
if (i == fparray[k].cell_index) {
bandx[fps] = contour[fparray[k].outline_index];
fps++;
}
}
} else {
// Find maxima
var bandoptions = "noise="+IJ.d2s(bandnoise,0)+" output=[Point Selection] exclude";
IJ.run(band, "Find Maxima...", bandoptions);
var bandpoints = band.getRoi();
if (bandpoints != null && bandpoints.getPolygon() != null)
bandx = bandpoints.getPolygon().xpoints;
if (bandx != null && bandx.length > 0) {
var radstep = 2*Math.PI/bandperimeter*interpolation*dx; // parametric distance of one pixel in radians
var skewx = skewness(bandx);
var neighborx = neighbor(bandx, bandperimeter, 1, true);
var leftneighborx = neighbor(bandx, bandperimeter, 1, false);
var neighbormeanx = 0;
var meanx = bandperimeter/bandx.length; // perimeter in um divided by # detection events
for (var j = 0;j<neighborx.length; j++) {
crossingtab.incrementCounter();
// report data to table
crossingtab.addValue("Spacing (Delta um)", neighborx[j]);
crossingtab.addValue("Left Spacing (Delta um)", leftneighborx[j]);
//crossingtab.addValue("Crossing angle (deg)", cross_angle.deg);
// accumulate values for averaging
neighbormeanx += neighborx[j];
}
// calculate average
neighbormeanx /= neighborx.length;
}
}
// main filo analysis
if (bandx != null && bandx.length > 0) {
// start of neighbor analysis
var radstep = 2*Math.PI/bandperimeter*interpolation*dx; // parametric distance of one pixel in radians
if (DEBUG) {
// report the mapping from raw pixel (xy, before interpolation) to contour (parametric)
for (var k = 0; k < fparray.length; k++) {
if (i == fparray[k].cell_index) {
// Load the parametric crossing position in um from the fparray
//temparray[fps] = contour[fparray[k].outline_index]; fps++;
// ----> already done in previous block
IJ.showMessage("mapping x (real px) -> u (contour px): \n"+
IJ.d2s(fparray[k].outline_index*interpolation,0)+
" -> "+IJ.d2s(contour[fparray[k].outline_index]/dx,0));
}
}
}
// Copy to java array for compatibility with neighbor()
if (IJ.isJava17()) {
var FloatArray = Java.type("float[]");
var fp_u = new FloatArray(fps);
} else {
var fp_u = new Packages.java.lang.reflect.Array.newInstance(java.lang.Float, fps);
}
for (var k = 0; k < fps; k++) {
fp_u[k] = (bandx[k] != null) ? bandx[k] : -1;
}
var skewx = null;
var neighborx = null;
var leftneighborx = null;
var neighbormeanx = 0;
var meanx = 0;
if (fps > 0) {
skewx = skewness(fp_u);
neighborx = neighbor(fp_u, bandperimeter, 1, true);
leftneighborx = neighbor(fp_u, bandperimeter, 1, false);
meanx = bandperimeter/fp_u.length; // perimeter in um divided by # detection events
//IJ.showMessage(IJ.d2s(neighborx.length,0)+" neighbors found in this cell");
for (var k = 0;k<neighborx.length; k++)
neighbormeanx += neighborx[k];
// calculate average
neighbormeanx /= neighborx.length;
}
// reset fp counter
var fps = 0;
for (var k = 0; k < fparray.length; k++) {
if (i == fparray[k].cell_index) {
var complex_pos = new Complex(
Math.cos(fparray[k].outline_index*radstep),
Math.sin(fparray[k].outline_index*radstep));
// parametric crossing angle in range [0..2PI] radians
var cross_angle = new Angle(complex_pos.Arg(), bandperimeter, 1);
fparray[k].cell_perimeter = rois[fparray[k].cell_index].getLength();
fparray[k].cross_u = cross_angle.dist;
fparray[k].cross_rad = cross_angle.rad;
fparray[k].cross_deg = cross_angle.deg;
if (neighborx != null) {
fparray[k].neighbor_near_u = neighborx[fps];
fparray[k].neighbor_left_u = leftneighborx[fps];
fps++;
}
if (DEBUG && i == 0)
IJ.showMessage("Compare cross_u = "+IJ.d2s(cross_angle.dist,3)+
" vs contour coordinate = "+IJ.d2s(contour[fparray[k].outline_index],3));
}
}
// Cui .. Rice, J Chem Phys, 2002
// expected probability density = 2n exp(-n * 2R) where n is number density
// mean = integrated density = integral of -exp(-2nR) 0->inf = 1/2n
var expected = meanx/2; // distance in um
// generate exponential random data
var simpoints = 1000;
var expdata = new Array(simpoints);
var sumdata = 0;
for (var j = 0; j<simpoints; j++) {
var expvar = 0;
// y = -exp(-2/meanx*R)
// ln (-y) = 2/meanx*R
// ----> R = meanx/2*ln (-y)
// let y = [-1, 0]; -y = [0, 1] = random variable
do {
expvar = Math.random();
expdata[j] = -expected*Math.log(expvar); // distance in um
}
while (expdata[j] > bandperimeter/2); // enforce circularity
sumdata += expdata[j];
}
// can calculate expected value from simulation -
// however this is not reliable at low density (n < 5 or so)
var simexpected = sumdata / simpoints;
var skew_neighbor = null;
if (neighborx != null)