-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathXT_MJG_Filament_Analysis40.py
3278 lines (2878 loc) · 216 KB
/
XT_MJG_Filament_Analysis40.py
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
# Filament Analysis
#
# Written by Matthew J. Gastinger
#
# JUne 2023 - Imaris 10.
#
#
#<CustomTools>
#<Menu>
#<Submenu name="Filaments Functions">
#<Item name="Filament Analysis40" icon="Python3">
#<Command>Python3XT::XT_MJG_Filament_Analysis40(%i)</Command>
#</Item>
#</Submenu>
#</Menu>
#<SurpassTab>
#<SurpassComponent name="bpFilaments">
#<Item name="Filament Analysis40" icon="Python3">
#<Command>Python3XT::XT_MJG_Filament_Analysis40(%i)</Command>
#</SurpassComponent>
#</SurpassTab>
#</CustomTools>
# Description:
# This XTension will do several things:
# 2)Find synaptic bouton(varicosities) place a spot at that point
# Diameter of the bouton (spot diameter)
# 3)Find Spots Colocalized with Dendrite segements
# Number of Spots per dendrite segment
# Distance of Colocalizaed spots to Starting point (soma)
# Number of Spots per Filament
# 4)Intra Dendrite to Dendrite contacts
# Number of contacts per dendrtie
# Distance of contact to starting point (soma)
# Length of the contacts
# Number of contacts per Filament
# 5)Filament to Filament contacts
# Finds all contacts with current filament with a new filament Object
# 6)Generate NEW stats in the Filament object
# Bouton(varicosity) number per dendrite segment
# Bouton density
# Spot Colocalization within a certain distance of filament
# Spot Coloc Density per dendrite segment
# 7)Display Filament as a population of Spots
# Visualize diameter/intensity along segments
# 8)Regularity Index Per Filament
# based on the average nearest neighbor (NN) distance between
# branch points, termination points or input points of a given
# dendritic tree to random disdribution in convex hull space
# ---As R approaches "1" points are closer to a random (Poisson) distribution (as the values of rExperimental and rRandom are more similar).
# ---As R approaches "0" corresponds to dendrites with more clustering (rExperimental < rRandom).
# ---As R greater than '1", nearest neighbors are further apart than it would be expected for a random distribution (rExperimental > rRandom).
# 9)New Tortuosity statistic per dendrite segment
# measures the angle between adjacent points along the segment
# --The sum of angles divided the number of points * pi
# --better measure for the waviness of segment
# 10) Filament - Dendrite Complexity Index (DCI)
# --- DCI = (Sum Terminal branch tip brnach depth + Number Terminaal branches) * (Total Filament length(um)/Total Number of primary dendrites)
# --- Pillai et al. (2012). PLoS ONE 7(6): e38971. doi:10.1371/journal.pone.0038971
# ---
#Python Dependancies:
# numpy
# tkinter
# scipy
# operator
# itertools
# statistics import mean
# functools import reduce
import numpy as np
import time
import random
import statistics
import math
import os
import platform
# GUI imports
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tkinter import simpledialog
#import matplotlib.pyplot as plt
from scipy.signal import find_peaks, peak_prominences
from scipy.signal import peak_widths
from scipy.spatial.distance import cdist
from scipy.spatial.distance import pdist
from scipy.spatial import Delaunay
from scipy.spatial import ConvexHull
from operator import add
from operator import itemgetter
import operator
import itertools
from itertools import chain
from statistics import mean
from functools import reduce
import collections
import ImarisLib
aImarisId=0
def XT_MJG_Filament_Analysis40(aImarisId):
# Create an ImarisLib object
vImarisLib = ImarisLib.ImarisLib()
# Get an imaris object with id aImarisId
vImarisApplication = vImarisLib.GetApplication(aImarisId)
# Get the factory
vFactory = vImarisApplication.GetFactory()
# Get the currently loaded dataset
vImage = vImarisApplication.GetDataSet()
# Get the Surpass scene
vSurpassScene = vImarisApplication.GetSurpassScene()
vSurfaces = vFactory.ToSurfaces(vImarisApplication.GetSurpassSelection())
vSpots = vFactory.ToSpots(vImarisApplication.GetSurpassSelection())
vFilaments = vFactory.ToFilaments(vImarisApplication.GetSurpassSelection())
vCurrentFilamentsSurpassName=vFilaments.GetName()
#Get Imaris Version
aVersion = vImarisApplication.GetVersion()
# aVersionValue=float(aVersion[7:11])
aVersionValue = 10
vOptionMergePoints=1
############################################################################
global Entry2, NamesSurfaces, NamesSpots,NamesFilaments
NamesSurfaces=[]
NamesSpots=[]
NamesFilaments=[]
NamesFilamentIndex=[]
NamesSurfaceIndex=[]
NamesSpotsIndex=[]
vSurpassSurfaces = 0
vSurpassSpots = 0
vSurpassFilaments = 0
vNumberSurpassItems=vImarisApplication.GetSurpassScene().GetNumberOfChildren()
for vChildIndex in range(0,vNumberSurpassItems):
vDataItem=vSurpassScene.GetChild(vChildIndex)
IsSurface=vImarisApplication.GetFactory().IsSurfaces(vDataItem)
IsSpot=vImarisApplication.GetFactory().IsSpots(vDataItem)
IsFilament=vImarisApplication.GetFactory().IsFilaments(vDataItem)
if IsSurface:
vSurpassSurfaces = vSurpassSurfaces+1
NamesSurfaces.append(vDataItem.GetName())
NamesSurfaceIndex.append(vChildIndex)
elif IsSpot:
vSurpassSpots = vSurpassSpots+1
NamesSpots.append(vDataItem.GetName())
NamesSpotsIndex.append(vChildIndex)
elif IsFilament:
vSurpassFilaments = vSurpassFilaments+1
NamesFilamentIndex.append(vChildIndex)
NamesFilaments.append(vDataItem.GetName())
############################################################################
#Dialog window
############################################################################
window = tk.Tk()
window.title('Filament Analysis')
window.geometry('410x580')
window.attributes("-topmost", True)
##################################################################
#Set input in center on screen
# Gets the requested values of the height and widht.
windowWidth = window.winfo_reqwidth()
windowHeight = window.winfo_reqheight()
# Gets both half the screen width/height and window width/height
positionRight = int(window.winfo_screenwidth()/2 - windowWidth/2)
positionDown = int(window.winfo_screenheight()/2 - windowHeight/2)
# Positions the window in the center of the page.
window.geometry("+{}+{}".format(positionRight, positionDown))
##################################################################
def Filament_options():
global vOptionFilamentToSpots,vOptionFilamentToSpotsMerge,vOptionBoutonThreshold, vOptionBoutonHeight, vOptionSomaThreshold,vOptionSomaThresholdValue
global vOptionFilamentBoutonDetection, vOptionFilamentBoutoDetecionThreshold, vOptionFilamentCloseToSpots, vOptionFilamentToSpotsFill
global vOptionBranchPoints,vOptionTerminalPoints, vOptionConvexHull, vOptionMergePoints, vOptionConvexHullwithTerminal, vOptionTortuosity
global vOptionFilamentSpotThreshold, vOptionDendriteToDendriteContact, vOptionFilamentToFilamentContact, NamesSpots, NamesSurfaces, NamesFilaments
# if (var2.get() == 0) and (var4.get() == 0) and (var5.get() ==0) and (var7.get() ==0) and (var8.get()==0):
# messagebox.showerror(title='Filament Analysis menu',
# message='Please Select ONE Analysis')
# window.mainloop()
vOptionFilamentToSpots=var2.get()
vOptionFilamentToSpotsMerge=var3.get()
vOptionFilamentToSpotsFill=1#var6.get()
vOptionFilamentBoutonDetection=var4.get()
vOptionDendriteToDendriteContact=var7.get()
vOptionFilamentCloseToSpots=var5.get()
vOptionFilamentSpotThreshold=[float(Entry2.get())]
vOptionFilamentToFilamentContact=var8.get()
vOptionSomaThreshold=var9.get()
vOptionBranchPoints=var10.get()
vOptionTerminalPoints=var11.get()
vOptionConvexHull=var12.get()
vOptionMergePoints= var101.get()
vOptionConvexHullwithTerminal=var122.get()
vOptionTortuosity=var13.get()
if vOptionSomaThreshold==1:
vOptionSomaThresholdValue=[float(Entry3.get())]
else:
vOptionSomaThresholdValue=0
if NamesSpots==[] and vOptionFilamentCloseToSpots==1:
messagebox.showerror(title='Spot Selection',
message='Please Create Spots Object!!')
window.mainloop()
if NamesFilaments==[] and vOptionFilamentToFilamentContact==1:
messagebox.showerror(title='Filament Selection',
message='Please Create Filament Object!!')
window.mainloop()
if vOptionFilamentBoutonDetection==1 and (var4Low.get()+var4Med.get()+var4High.get())>1:
messagebox.showerror(title='Filament Analysis menu',
message='Choose one Sensitivity')
window.mainloop()
if (var4.get() == 1) and (var4Low.get() == 1):
vOptionBoutonThreshold=20
vOptionBoutonHeight=0.5
elif (var4.get() == 1) and (var4Med.get() == 1):
vOptionBoutonThreshold=15
vOptionBoutonHeight=.4
elif (var4.get() == 1) and (var4High.get() == 1):
vOptionBoutonThreshold=5
vOptionBoutonHeight=.25
if (var2.get() == 0) and (var3.get() == 1):
vOptionFilamentToSpots=1
window.destroy()
var2 = tk.IntVar(value=0)#Export Filament as a Spots object
var3 = tk.IntVar(value=0)#Filament as spotd-- merge
var4 = tk.IntVar(value=0)#Detect Boutons (varicosities)
var5 = tk.IntVar(value=0)#Find Spots Close to Filaments
var6 = tk.IntVar(value=0)#fill spots
var7 = tk.IntVar(value=0)#dendrite dendrite contact
var8 = tk.IntVar(value=0)#Filament filament contact
var9 = tk.IntVar(value=0)#soma filter
var10 = tk.IntVar(value=0)#Branch points
var11 = tk.IntVar(value=0)#Terminal points
var12 = tk.IntVar(value=0)#ConvexHull
var101 = tk.IntVar(value=1)#Merge points
var122 = tk.IntVar(value=0)#Use terminal points(starting point) for convex hull
var13 = tk.IntVar(value=0)#Tortuosity
var4Low=tk.IntVar(value=0)#bouton sensitivity
var4Med=tk.IntVar(value=1)#bouton sensitivity
var4High=tk.IntVar(value=0)#bouton sensitivity
tk.Label(window, font="bold", text='Choose Analysis Options!').grid(row=0,column=0, padx=75,sticky=W)
tk.Checkbutton(window, text='Export Filament as a Spots object',
variable=var2, onvalue=1, offvalue=0).grid(row=2, column=0, padx=40,sticky=W)
# tk.Checkbutton(window, text='Fill Spots',
# variable=var6, onvalue=1, offvalue=0).grid(row=4, column=0, padx=80,sticky=W)
tk.Checkbutton(window, text='Merge all Filaments',
variable=var3, onvalue=1, offvalue=0).grid(row=3, column=0, padx=80,sticky=W)
tk.Checkbutton(window, text='Detect Boutons (varicosities)',
variable=var4, onvalue=1, offvalue=0).grid(row=5, column=0, padx=40,sticky=W)
tk.Checkbutton(window, text='Low',
variable=var4Low, onvalue=1, offvalue=0).grid(row=6, column=0, padx=80,sticky=W)
tk.Checkbutton(window, text='Med',
variable=var4Med, onvalue=1, offvalue=0).grid(row=6, column=0, padx=130,sticky=W)
tk.Checkbutton(window, text='High (sensitivity)',
variable=var4High, onvalue=1, offvalue=0).grid(row=6, column=0, padx=180,sticky=W)
tk.Checkbutton(window, text='Find Spots Close to Filaments',
variable=var5, onvalue=1, offvalue=0).grid(row=7, column=0, padx=40,sticky=W)
Entry2=Entry(window,justify='center',width=8)
Entry2.grid(row=8, column=0, padx=80, sticky=W)
Entry2.insert(0, '0.5')
tk.Label(window, text='um (distance threshold)').grid(row=8,column=0, padx=130, sticky=W)
tk.Label(window, text='____________________________________').grid(row=9, column=0,sticky=W)
tk.Checkbutton(window, text='Find Intra-Dendrite Contacts',
variable=var7, onvalue=1, offvalue=0).grid(row=10, column=0, padx=40,sticky=W)
Entry3=Entry(window,justify='center',width=8)
Entry3.grid(row=11, column=0, padx=300, sticky=W)
Entry3.insert(0, '10')
tk.Label(window, text='um').grid(row=11,column=0, padx=350, sticky=W)
tk.Checkbutton(window, text='Remove Contacts near Starting Point',
variable=var9, onvalue=1, offvalue=0).grid(row=11, column=0, padx=65,sticky=W)
tk.Checkbutton(window, text='Find Filament-Filament Contacts',
variable=var8, onvalue=1, offvalue=0).grid(row=12, column=0, padx=40,sticky=W)
tk.Label(window, text='____________________________________').grid(row=13, column=0,sticky=W)
tk.Checkbutton(window, text='Create Branch Spots',
variable=var10, onvalue=1, offvalue=0).grid(row=14, column=0, padx=10,sticky=W)
tk.Checkbutton(window, text='Merge Spots',
variable=var101, onvalue=1, offvalue=0).grid(row=14, column=0, padx=175,sticky=W)
tk.Checkbutton(window, text='Create Terminal Spots',
variable=var11, onvalue=1, offvalue=0).grid(row=15, column=0, padx=10,sticky=W)
tk.Label(window, text='____________________________________').grid(row=16, column=0,sticky=W)
tk.Checkbutton(window, text='Create ConvexHull',
variable=var12, onvalue=1, offvalue=0).grid(row=17, column=0, padx=10,sticky=W)
tk.Checkbutton(window, text='Use Terminal Points',
variable=var122, onvalue=1, offvalue=0).grid(row=17, column=0, padx=175,sticky=W)
#Test if Mac
qWhatOS = platform.system()
if qWhatOS == 'Darwin':
btn = Button(window, text="Analyze Filament", command=Filament_options)
else:
btn = Button(window, text="Analyze Filament", bg='blue', fg='white', command=Filament_options)
btn.grid(column=0, row=18, sticky=W, padx=250)
tk.Label(window, text='************************************').grid(row=18, column=0,sticky=W)
tk.Checkbutton(window, text='Calculate Tortuosity',
variable=var13, onvalue=1, offvalue=0).grid(row=19, column=0, padx=0,sticky=W)
tk.Label(window, text='New Statistics created:').grid(row=20,column=0, sticky=W)
tk.Label(window, text='1) Regularity Index(BranchPoints)').grid(row=21,column=0, padx=40, sticky=W)
tk.Label(window, text='2) Regularity Index(TerminalPoints)').grid(row=22,column=0, padx=40, sticky=W)
tk.Label(window, text='3) Tortuosity (Filament & Segments)').grid(row=23,column=0, padx=40, sticky=W)
tk.Label(window, text='New Statistics for "Find Spots close to Filaments":').grid(row=24,column=0, sticky=W)
tk.Label(window, text='4) Number of Spots per dendrite segment').grid(row=25,column=0, padx=40, sticky=W)
tk.Label(window, text='5) Distance of Colocalizaed spots to Starting point (soma)').grid(row=26,column=0, padx=40, sticky=W)
tk.Label(window, text='6) Number Random Spots Coloc with filament/dendrites').grid(row=27,column=0, padx=40, sticky=W)
window.mainloop()
############################################################################
############################################################################
#Open Surpass menu to Select Spots Object
if vOptionFilamentCloseToSpots==1:
#####################################################
#Making the Listbox for the Surpass menu
main = tk.Tk()
main.title("Surpass menu")
main.geometry("+50+150")
frame = ttk.Frame(main, padding=(3, 3, 12, 12))
frame.grid(column=0, row=0, sticky=(N, S, E, W))
main.attributes("-topmost", True)
#################################################################
#Set input in center on screen
# Gets the requested values of the height and widht.
windowWidth = main.winfo_reqwidth()
windowHeight = main.winfo_reqheight()
# Gets both half the screen width/height and window width/height
positionRight = int(main.winfo_screenwidth()/2 - windowWidth/2)
positionDown = int(main.winfo_screenheight()/2 - windowHeight/2)
# Positions the window in the center of the page.
main.geometry("+{}+{}".format(positionRight, positionDown))
##################################################################
names = StringVar()
names.set(NamesSpots)
lstbox = Listbox(frame, listvariable=names, selectmode=MULTIPLE, width=20, height=10)
lstbox.grid(column=0, row=0, columnspan=2)
def select():
global ObjectSelection
ObjectSelection = list()
selection = lstbox.curselection()
for i in selection:
entrada = lstbox.get(i)
ObjectSelection.append(entrada)
#Test for the correct number selected
if len(ObjectSelection)!=1:
messagebox.showerror(title='Surface menu',
message='Please Choose 1 Spots')
main.mainloop()
else:
main.destroy()
btn = ttk.Button(frame, text="Choose Spots Object", command=select)
btn.grid(column=1, row=1)
#Selects the top items in the list
lstbox.selection_set(0)
main.mainloop()
####################################################################
# get the Selected Spots in Surpass Scene
vDataItem=vSurpassScene.GetChild(NamesSpotsIndex[(NamesSpots.index( ''.join(map(str, ObjectSelection[0]))))])
vSpots=vImarisApplication.GetFactory().ToSpots(vDataItem)
####################################################################
#Test if scene has Spots object
#get the spot coordinates
vSpotsColocPositionsXYZ = vSpots.GetPositionsXYZ()
vSpotsColocRadius = vSpots.GetRadiiXYZ()
vSpotsColocTimeIndices = vSpots.GetIndicesT()
vSpotsColocCount = len(vSpotsColocRadius)
vSpotsId = vSpots.GetIds()
####################################################################
####################################################################
#Open Surpass menu to Select Filament Object
if vOptionFilamentToFilamentContact==1:
#####################################################
#Making the Listbox for the Surpass menu
main = tk.Tk()
main.title("Surpass menu")
main.geometry("+50+150")
frame = ttk.Frame(main, padding=(3, 3, 12, 12))
frame.grid(column=0, row=0, sticky=(N, S, E, W))
main.attributes("-topmost", True)
#################################################################
#Set input in center on screen
# Gets the requested values of the height and widht.
windowWidth = main.winfo_reqwidth()
windowHeight = main.winfo_reqheight()
# Gets both half the screen width/height and window width/height
positionRight = int(main.winfo_screenwidth()/2 - windowWidth/2)
positionDown = int(main.winfo_screenheight()/2 - windowHeight/2)
# Positions the window in the center of the page.
main.geometry("+{}+{}".format(positionRight, positionDown))
##################################################################
names = StringVar()
names.set(NamesFilaments)
lstbox = Listbox(frame, listvariable=names, selectmode=MULTIPLE, width=20, height=10)
lstbox.grid(column=0, row=0, columnspan=2)
def select():
global ObjectSelection
ObjectSelection = list()
selection = lstbox.curselection()
for i in selection:
entrada = lstbox.get(i)
ObjectSelection.append(entrada)
#Test for the correct number selected
if len(ObjectSelection)!=1:
messagebox.showerror(title='Filament menu',
message='Please Choose ONE Filament Object!')
main.mainloop()
#Test if selected filament name is the same as current one
elif (''.join(map(str, ObjectSelection[0])))==vCurrentFilamentsSurpassName:
messagebox.showerror(title='Filament menu',
message='You CAN NOT use that Object\n'
'Please Choose a Different Filament Object!')
main.mainloop()
else:
main.destroy()
btn = ttk.Button(frame, text="Choose Filament Object", command=select)
btn.grid(column=1, row=1)
#Selects the top items in the list
# lstbox.selection_set(0)
main.mainloop()
####################################################################
# get the Selected Filaments in Surpass Scene
vDataItem=vSurpassScene.GetChild(NamesFilamentIndex[(NamesFilaments.index( ''.join(map(str, ObjectSelection[0]))))])
vFilamentColoc=vImarisApplication.GetFactory().ToFilaments(vDataItem)
####################################################################
#Test if scene has Spots object
#get the Filament Data
#Get the Current Filament Object
vNumberOfFilamentsColoc = vFilamentColoc.GetNumberOfFilaments()
vFilamentColocIds= vFilamentColoc.GetIds()
vFilamentsColocFilamentId=[]
vFilamentsColocIndexT=[]
vFilamentsColocXYZ=[]
vFilamentsColocRadius=[]
vFilamentsColcPointIndex=[]
vFilamentsColocEdgesSegmentId=[]
vFilamentsColocFilamentIdEdges=[]
vFilamentsColocEdges=[]
#Collate all Filament Point positions and segment IDs
for xFilamentColocIndex in range (vNumberOfFilamentsColoc):
vFilamentsColocIndexT.append([vFilamentColoc.GetTimeIndex(xFilamentColocIndex)] * len(vFilamentColoc.GetRadii(xFilamentColocIndex)))
vFilamentsColocXYZ.extend(vFilamentColoc.GetPositionsXYZ(xFilamentColocIndex))
vFilamentsColocRadius.extend(vFilamentColoc.GetRadii(xFilamentColocIndex))
vFilamentsColocFilamentId.append([vFilamentColocIds[xFilamentColocIndex]] * len(vFilamentColoc.GetRadii(xFilamentColocIndex)))
vFilamentsColocEdgesSegmentId.extend(vFilamentColoc.GetEdgesSegmentId(xFilamentColocIndex))
vFilamentsColocEdges.extend(vFilamentColoc.GetEdges(xFilamentColocIndex))
vFilamentsColocFilamentIdEdges.append([vFilamentColocIds[xFilamentColocIndex]] * len(vFilamentColoc.GetEdgesSegmentId(xFilamentColocIndex)))
####################################################################
####################################################################
#Get Image properties
vDataMin = (vImage.GetExtendMinX(),vImage.GetExtendMinY(),vImage.GetExtendMinZ())
vDataMax = (vImage.GetExtendMaxX(),vImage.GetExtendMaxY(),vImage.GetExtendMaxZ())
vDataSize = (vImage.GetSizeX(),vImage.GetSizeY(),vImage.GetSizeZ())
vSizeT = vImage.GetSizeT()
vSizeC = vImage.GetSizeC()
aXvoxelSpacing= (vDataMax[0]-vDataMin[0])/vDataSize[0]
aYvoxelSpacing= (vDataMax[1]-vDataMin[1])/vDataSize[1]
aZvoxelSpacing = round((vDataMax[2]-vDataMin[2])/vDataSize[2],3)
vSmoothingFactor=aXvoxelSpacing*2
vType = vImage.GetType()
#Get the Current Filament Object
vNumberOfFilaments=vFilaments.GetNumberOfFilaments()
vFilamentIds= vFilaments.GetIds()
#Generate Surpass Scene folder locations
#Create a new folder object for Filament to Spots
#Generate new Factory for Surpass Scene objects
vNewSpotsDendritesFolder = vImarisApplication.GetFactory().CreateDataContainer()
vNewSpotsSpinesFolder =vImarisApplication.GetFactory().CreateDataContainer()
vNewSpotsDendritesFolder.SetName('Filament to Spots (dendrite) -- ' + vFilaments.GetName())
vNewSpotsSpinesFolder.SetName('Spines to Spots -- ' + vFilaments.GetName())
#Create a new folder object for Bouton Spots
vNewSpotsBoutons = vImarisApplication.GetFactory().CreateSpots()
# vNewSpotsvNewSpotsAlongFilament = vImarisApplication.GetFactory().CreateSpots()
vNewSpotsAnalysisFolder =vImarisApplication.GetFactory().CreateDataContainer()
vNewSpotsAnalysisFolder.SetName('Filament Analysis -- ' + vFilaments.GetName())
vSpotFilamentPoints = vImarisApplication.GetFactory().CreateDataContainer()
vSpotFilamentPoints.SetName(' Terminal/Branch Point Analysis - '+ str(vFilaments.GetName()))
vSurfaceConvexHull = vImarisApplication.GetFactory().CreateDataContainer()
vSurfaceConvexHull.SetName(' Dendritic Field Analysis - '+ str(vFilaments.GetName()))
vSurfaceHull = vFactory.CreateSurfaces()
#Create a new folder object for Dendrite contacts
# vNewSpotsDendriteDendriteContacts = vImarisApplication.GetFactory().CreateSpots()
#Preset variable lists
vTotalSpotsDendrite=[]
vTotalSpotsDendriteTime=[]
vTotalSpotsDendriteRadius=[]
vTotalSpotsSpine=[]
vTotalSpotsSpineRadius=[]
vTotalSpotsSpineTime=[]
wAllSegmentIds=[]
TotalSegmentIndex=[]
wCompleteFilamentTimeIndex=[]
wCompleteDendriteTimeIndex=[]
wCompleteSpineTimeIndex=[]
vBoutonPositionAll=[]
vBoutonRadiusAll=[]
vStatisticFilamentBoutonsPerDendrite=[]
vStatisticFilamentDendriteDendriteContacts=[]
vStatisticFilamentDendriteDendriteContactsColoc=[]
xCompleteNumberofContactsperFilament=[]
xCompleteNumberofContactsperFilamentColoc=[]
wCompleteFilamentNumberBoutons=[]
vAllColocDensityPerDendrite=[]
vFilamentCountActual=0
wCompleteDendriteSegmentIds=[]
wCompleteSpineSegmentIds=[]
wCompleteDendriteBranchIntCenter=[]
wCompleteDendriteBranchIntMean=[]
wCompleteSpineBranchIntCenter=[]
wCompleteSpineBranchIntMean=[]
vStatisticDendriteBranchIntMean=[]
vStatisticDendriteBranchIntCenter=[]
vStatisticSpineBranchIntMean=[]
vStatisticSpineBranchIntCenter=[]
wNumberOfSpotsPerDendrite=[]
wNumberOfSpotsPerSpine=[]
wCompleteShortestDistanceToFilament=[]
wCompleteShortestDistanceToALLFilaments=[]
wCompleteShortestDistanceToSpine=[]
wNewSpotsOnFilamentAll=[]
wNewSpotsOnFilament=[]
wNewSpotsOnFilamentRadius=[]
wNewSpotsOnFilamentTime=[]
wCompleteSpotDistAlongFilamentStat=[]
wCompleteSpotDistAlongFilamentPosX=[]
wCompleteSpotDistAlongFilamentPosY=[]
wCompleteBoutonDistAlongFilamentStat=[]
wCompleteBoutonDistAlongFilamentPosX=[]
wCompleteBoutonDistAlongFilamentPosY=[]
wCompleteSpotsonSpine=[]
wCompleteSpotsonDendrite=[]
wCompleteSpotsonFilament=[]
wCompleteNumberSpotsPerFilament=[]
wCompleteNumberSpotsonSpinePerFilament=[]
wCompleteNumberSpotsonDendritePerFilament=[]
xContactBranchIndexId=[]
xContactSegmentId=[]
xContactSegmentIdColoc=[]
xCompleteSpotDistAlongFilamentStat=[]
xCompleteBoutonDistAlongFilamentStat=[]
xContactBranchIndexIdColoc=[]
xCompleteSpotDistAlongFilamentStatColoc=[]
zAllFilamentsRegularityIndexBP=[]
zAllFilamentsRegularityIndexTP=[]
vNewStatTortuosityPerFilament = []
vCompleteSegmentsAnglesPerFilamentSpot = []
vCompleteSegmentsAnglesPerFilamentSpotMean = []
vNewStatCompleteTortuosityPerSegment = []
vNewStatCompleteTortuosityPerSegmentSum = []
wNumberRandomSpotColocPerFilament = []
wNewStatRandomSpotColocPerFilament = []
wFilamentBranchPointsNEW = []
wFilamentTerminalPointsNEW =[]
vNewStatCompleteFilamentBranchPointDistToSomaMean = []
vNewStatCompleteFilamentTerminalPointDistToSomaMean = []
vNewStatCompleteFilamentTerminalPointDistToSomaMax = []
vNodeTypesComplete = []
vNodeFilamentIdsComplete = []
wNewStatConvexHullVolumePerFilament = []
wNewStatConvexHullAreaPerFilament = []
wCompleteTerminalPointsDistAlongFilamentStatALL = []
wCompleteBranchPointsDistAlongFilamentStatALL = []
wFilamentComplexityIndexComplete = []
wLabelListTerminalPoints = []
wLabelListBranchPoints = []
IsRealFilament=[]
wSpotsAllIndex=[]
xBranchSharingNodesALL=[]
xTerminalALL=[]
xAllDendriteSegmentsId=[]
SegmentCountALL=0
aFilamentIndex=0
qIsSpines=False
###############################################################################
###############################################################################
#Progress Bar for Dendrites
# Create the master object
master = tk.Tk()
# Create a progressbar widget
progress_bar = ttk.Progressbar(master, orient="horizontal",
mode="determinate", maximum=100, value=0)
progress_bar2 = ttk.Progressbar(master, orient="horizontal",
mode="determinate", maximum=100, value=0)
progress_bar3 = ttk.Progressbar(master, orient="horizontal",
mode="determinate", maximum=100, value=0)
# progress_bar4 = ttk.Progressbar(master, orient="horizontal",
# mode="determinate", maximum=100, value=0)
# And a label for it
label_1 = tk.Label(master, text="Dendrite Progress Bar ")
label_2 = tk.Label(master, text="Filament Progress Bar ")
if vOptionDendriteToDendriteContact == 1:
label_3 = tk.Label(master, text="Dendrite Contact Progress Bar ")
else:
label_3 = tk.Label(master, text="Working... ")
# label_4 = tk.Label(master, text="Distance to Soma Progress Bar ")
# Use the grid manager
label_1.grid(row=0, column=0,pady=10)
label_2.grid(row=1, column=0,pady=10)
label_3.grid(row=2, column=0,pady=10)
# label_4.grid(row=3, column=0,pady=10)
progress_bar.grid(row=0, column=1)
progress_bar2.grid(row=1, column=1)
progress_bar3.grid(row=2, column=1)
# progress_bar4.grid(row=3, column=1)
master.geometry('350x150')
master.attributes("-topmost", True)
#################################################################
#Set input in center on screen
# Gets the requested values of the height and widht.
windowWidth = master.winfo_reqwidth()
windowHeight = master.winfo_reqheight()
# Gets both half the screen width/height and window width/height
positionRight = int(master.winfo_screenwidth()/2 - windowWidth/2)
positionDown = int(master.winfo_screenheight()/2 - windowHeight/2)
# Positions the window in the center of the page.
master.geometry("+{}+{}".format(positionRight, positionDown))
##################################################################
# Necessary, as the master object needs to draw the progressbar widget
# Otherwise, it will not be visible on the screen
master.update()
progress_bar['value'] = 0
progress_bar3['value'] = 0
master.update()
#################################################################
# if vOptionDendriteToDendriteContact==0:
# progress_bar3['value'] = 100
# master.update()
###############################################################################
###############################################################################
if vNumberOfFilaments > 50:
qisVisible=messagebox.askquestion("Processing Warning - Large Number of Filaments",
'Do you wish to Hide Imaris Application?\n'
' This will increase processing speed\n''\n'
'Close Progress window to CANCEL script')
if qisVisible=='yes':
vImarisApplication.SetVisible(0)
###############################################################################
#If filament has no size skip and modify the main list VFilamentIds
zEmptyfilaments=[]
for aFilamentIndex in range(vNumberOfFilaments):
vFilamentsRadius = vFilaments.GetRadii(aFilamentIndex)
if len(vFilamentsRadius)==1:
zEmptyfilaments.append(int(aFilamentIndex))
vFilamentIds=[v for i,v in enumerate(vFilamentIds) if i not in zEmptyfilaments]
###############################################################################
###############################################################################
#Get Filament stats
vAllFilamentDendriteLengthSET = vFilaments.GetStatisticsByName('Segment Length')
vAllFilamentDendriteLength = vAllFilamentDendriteLengthSET.mValues
vAllFilamentDendriteLengthIds = vAllFilamentDendriteLengthSET.mIds
vAllFilamentLengthSum = vFilaments.GetStatisticsByName('Filament Length (sum)').mValues
vAllFilamentDendriteBranchDepthSET = vFilaments.GetStatisticsByName('Segment Branch Depth')
vAllFilamentDendriteBranchDepthIds = vAllFilamentDendriteBranchDepthSET.mIds
vAllFilamentDendriteBranchDepth = vAllFilamentDendriteBranchDepthSET.mValues
vAllFilamentSpineLengthSET = vFilaments.GetStatisticsByName('Spine Length')
vAllFilamentSpineLength = vAllFilamentSpineLengthSET.mValues
vAllFilamentSpineLengthIds = vAllFilamentSpineLengthSET.mIds
aVersionValue = 10
if not vAllFilamentDendriteLength:
aVersionValue = 9
vAllFilamentDendriteLengthSET = vFilaments.GetStatisticsByName('Dendrite Length')
vAllFilamentDendriteLength = vAllFilamentDendriteLengthSET.mValues
vAllFilamentDendriteLengthIds = vAllFilamentDendriteLengthSET.mIds
vAllFilamentDendriteBranchDepthSET = vFilaments.GetStatisticsByName('Dendrite Branch Depth')
vAllFilamentDendriteBranchDepthIds = vAllFilamentDendriteBranchDepthSET.mIds
vAllFilamentDendriteBranchDepth = vAllFilamentDendriteBranchDepthSET.mValues
vStatPtPositionXSet = vFilaments.GetStatisticsByName('Pt Position X')
vStatPtPositionYSet = vFilaments.GetStatisticsByName('Pt Position Y')
vStatPtPositionZSet = vFilaments.GetStatisticsByName('Pt Position Z')
vStatPtPosition = []
vStatPtPosition.append(vStatPtPositionXSet.mValues)
vStatPtPosition.append(vStatPtPositionYSet.mValues)
vStatPtPosition.append(vStatPtPositionZSet.mValues)
vStatPtPositionFactors = vStatPtPositionXSet.mFactors
vStatPtPositionIds = vStatPtPositionXSet.mIds
wFilamentTerminalPointsNEW = np.array(vStatPtPosition).T[np.where(np.array(vStatPtPositionFactors)[4]=='Segment Terminal')[0].tolist()]
wFilamentBranchPointsNEW = np.array(vStatPtPosition).T[np.where(np.array(vStatPtPositionFactors)[4]=='Segment Branch')[0].tolist()]
wFilamentStartingPointsNEW = np.array(vStatPtPosition).T[np.where(np.array(vStatPtPositionFactors)[4]=='Segment Beginning')[0].tolist()]
wSpineTerminalPtPositionNEW = np.array(vStatPtPosition).T[np.where(np.array(vStatPtPositionFactors)[4]=='Spine Terminal')[0].tolist()]
wSpineAttachmentPtPositionNEW = np.array(vStatPtPosition).T[np.where(np.array(vStatPtPositionFactors)[4]=='Spine Attachmentf')[0].tolist()]
if not wFilamentTerminalPointsNEW.any():# == []:
wFilamentTerminalPointsNEW = np.array(vStatPtPosition).T[np.where(np.array(vStatPtPositionFactors)[4]=='Dendrite Terminal')[0].tolist()]
wFilamentBranchPointsNEW = np.array(vStatPtPosition).T[np.where(np.array(vStatPtPositionFactors)[4]=='Dendrite Branch')[0].tolist()]
wFilamentStartingPointsNEW = np.array(vStatPtPosition).T[np.where(np.array(vStatPtPositionFactors)[4]=='Dendrite Beginning')[0].tolist()]
# wFilamentTerminalPointsNEWCurrentBranchDepth = np.array(vAllFilamentDendriteBranchDepth)[np.where((wFilamentTerminalPointsNEW[:, None] == np.array(vFilamentsXYZ)).all(-1).any(-1))[0].tolist()]
# wFilamentTerminalPointsNEWCurrentBranchLength = np.array(vAllFilamentDendriteLength)[np.where((wFilamentTerminalPointsNEW[:, None] == np.array(vFilamentsXYZ)).all(-1).any(-1))[0].tolist()]
# wFilamentComplexityNumberPrimaryDendrites = np.size(np.where(wFilamentTerminalPointsNEWCurrentBranchDepth==0))
# wFilamentComplexitySumTerminalBranchOrder = np.sum(wFilamentTerminalPointsNEWCurrentBranchDepth)
# wFilamentComplexityIndexComplete.append((wFilamentComplexitySumTerminalBranchOrder + np.size(wFilamentTerminalPointsNEWCurrent[:,0]))/vAllFilamentLengthSum[aFilamentIndex]/wFilamentComplexityNumberPrimaryDendrites)
###############################################################################
###############################################################################
aFilamentIndex=0
#Loop each Filament
for aFilamentIndex in range(vNumberOfFilaments):
vFilamentsIndexT = vFilaments.GetTimeIndex(aFilamentIndex)
vFilamentsXYZ = vFilaments.GetPositionsXYZ(aFilamentIndex)
vFilamentsRadius = vFilaments.GetRadii(aFilamentIndex)
vFilamentTimepoint = vImage.GetTimePoint(vFilamentsIndexT)
#Test if the time point has empty filament matrix or filament start
#point and nothing more
if len(vFilamentsRadius)==1:
continue
#count the filaments processed
vFilamentCountActual=vFilamentCountActual+1
vFilamentsEdgesSegmentId = vFilaments.GetEdgesSegmentId(aFilamentIndex)
#Find unique values of variable using set, the copnvert back to list
vSegmentIds=list(set(vFilamentsEdgesSegmentId))
vNumberOfSegmentsALL = len(vSegmentIds)#total number segments (dendrites and spines)
vNumberOfFilamentPoints= len(vFilamentsRadius)#including starting point
vFilamentTimeIndex=[vFilamentsIndexT]*len(vFilamentsRadius)#for filament spot creation
vFilamentsEdges = vFilaments.GetEdges(aFilamentIndex)
vTypes = vFilaments.GetTypes(aFilamentIndex)
vBeginningVertex = vFilaments.GetBeginningVertexIndex(aFilamentIndex)
if max(vTypes)==1:
qIsSpines=True
##############################################################################
###############################################################################
#Find in Branch, Terminal and starting point - in current filament
wFilamentBranchPointsNEWCurrent = np.array(wFilamentBranchPointsNEW)[np.where((wFilamentBranchPointsNEW[:, None] == np.array(vFilamentsXYZ)).all(-1).any(-1))[0].tolist()]
wFilamentTerminalPointsNEWCurrent = np.array(wFilamentTerminalPointsNEW)[np.where((wFilamentTerminalPointsNEW[:, None] == np.array(vFilamentsXYZ)).all(-1).any(-1))[0].tolist()]
wFilamentStartingPointsNEWCurrent = np.array(wFilamentStartingPointsNEW)[np.where((wFilamentStartingPointsNEW[:, None] == np.array(vFilamentsXYZ)).all(-1).any(-1))[0].tolist()]
wFilamentSpineTerminalPointsNEWCurrent = np.array(wSpineTerminalPtPositionNEW)[np.where((wSpineTerminalPtPositionNEW[:, None] == np.array(vFilamentsXYZ)).all(-1).any(-1))[0].tolist()]
wFilamentSpineAttachmentPointsNEWCurrent = np.array(wSpineAttachmentPtPositionNEW)[np.where((wSpineAttachmentPtPositionNEW[:, None] == np.array(vFilamentsXYZ)).all(-1).any(-1))[0].tolist()]
#Calculation of Mean Nearest Neighbor based on branch points and terminal points
#Create a set of Random Spots, same numebr of branch points or terminal points
#limit creation of random spot to be withint he MinMax of XYZ of the filament points
zArray=np.array(vFilamentsXYZ)
isFilament2D=False
zRandomLimitsMin=np.min(zArray, 0)
zRandomLimitsMax=np.max(zArray, 0)
zRandomSpotsTerminal=[]
zRandomSpotsNode=[]
if np.shape(wFilamentBranchPointsNEWCurrent)[0] >3:
zArrayNodes=cdist(wFilamentBranchPointsNEWCurrent,wFilamentBranchPointsNEWCurrent)
zArrayNodesMin=np.where(zArrayNodes>0, zArrayNodes, np.inf).min(axis=1)
zAverageNNBranchPoint=np.mean(zArrayNodesMin)
for i in range(3):
zRandomSpotsNode.append(np.random.uniform(low=zRandomLimitsMin[i], high=zRandomLimitsMax[i], size= np.shape(wFilamentBranchPointsNEW)[0]))
zRandomSpotsNode=np.transpose(np.array(zRandomSpotsNode))
#Find if set of Random Spots falls inside Convex hull on Filament
if (np.all(zArray[:,2] == zArray[0][2]))==True:
zArray=np.delete(zArray,2,1)
zRandomSpotsNode=np.delete(zRandomSpotsNode,2,1)
isFilament2D=True
zHullDelaunay = Delaunay(zArray)
#Create Boolean arguement to define if in Convex hull
zRandomSpotTestNode=np.array(zHullDelaunay.find_simplex(zRandomSpotsNode)>=0)
#Keep True, replace false with new random spot
if np.any(zRandomSpotTestNode):
#find indices that are True
zBrokenRandomSpots=np.where(zRandomSpotTestNode==False)
for i in range (len(zBrokenRandomSpots)):
#Create new random spot
zNEWRandomSpot=[]
for j in range(3):
zNEWRandomSpot.append(np.random.uniform(low=zRandomLimitsMin[j], high=zRandomLimitsMax[j], size= 1))
zNEWRandomSpot=np.transpose(np.array(zNEWRandomSpot))
if isFilament2D:
zNEWRandomSpot=np.delete(zNEWRandomSpot,2,1)
#Test if inConvex hull
while (zHullDelaunay.find_simplex(zNEWRandomSpot)>=0)==False:
#Create new random spot
zNEWRandomSpot=[]
for j in range(3):
zNEWRandomSpot.append(np.random.uniform(low=zRandomLimitsMin[j], high=zRandomLimitsMax[j], size= 1))
zNEWRandomSpot=np.transpose(np.array(zNEWRandomSpot))
if isFilament2D:
zNEWRandomSpot=np.delete(zNEWRandomSpot,2,1)
#Replace entire row with new positions
zRandomSpotsNode[zBrokenRandomSpots[0][i],:]=zNEWRandomSpot
#Calculation of Mean Nearest Neighbor based on branch points and terminal points
zArrayNodes=cdist(zRandomSpotsNode,zRandomSpotsNode)
zArrayNodesMin=np.where(zArrayNodes>0, zArrayNodes, np.inf).min(axis=1)
zAverageNNBranchPointRandom=np.mean(zArrayNodesMin)
#Calculation of Regulatiry Index
zAllFilamentsRegularityIndexBP.append(zAverageNNBranchPoint/zAverageNNBranchPointRandom)
else:
zAllFilamentsRegularityIndexBP.append(0)
###############################################################################
if np.shape(wFilamentTerminalPointsNEWCurrent)[0] >3:
zArrayTerminal=cdist(wFilamentTerminalPointsNEWCurrent,wFilamentTerminalPointsNEWCurrent)
zArrayTerminalMin=np.where(zArrayTerminal>0, zArrayTerminal, np.inf).min(axis=1)
zAverageNNTerminalPoint=np.mean(zArrayTerminalMin)
for i in range(3):
zRandomSpotsTerminal.append(np.random.uniform(low=zRandomLimitsMin[i], high=zRandomLimitsMax[i], size= np.shape(wFilamentTerminalPointsNEW)[0]))
zRandomSpotsTerminal=np.transpose(np.array(zRandomSpotsTerminal))
#Find if set of Random Spots falls inside Convex hull on Filament
if (np.all(zArray[:,2] == zArray[0][2]))==True:
zArray=np.delete(zArray,2,1)
zRandomSpotsTerminal=np.delete(zRandomSpotsTerminal,2,1)
isFilament2D=True
zHullDelaunay = Delaunay(zArray)
#Create Boolean arguement to define if in Convex hull
zRandomSpotTestTerminal=np.array(zHullDelaunay.find_simplex(zRandomSpotsTerminal)>=0)
if np.any(zRandomSpotTestTerminal):
#find indices that are True
zBrokenRandomSpots=np.where(zRandomSpotTestTerminal==False)
for i in range (len(zBrokenRandomSpots)):
#Create new random spot
zNEWRandomSpot=[]
for j in range(3):
zNEWRandomSpot.append(np.random.uniform(low=zRandomLimitsMin[j], high=zRandomLimitsMax[j], size= 1))
zNEWRandomSpot=np.transpose(np.array(zNEWRandomSpot))
if isFilament2D:
zNEWRandomSpot=np.delete(zNEWRandomSpot,2,1)
#Test if inConvex hull
while (zHullDelaunay.find_simplex(zNEWRandomSpot)>=0)==False:
#Create new random spot
zNEWRandomSpot=[]
for j in range(3):
zNEWRandomSpot.append(np.random.uniform(low=zRandomLimitsMin[j], high=zRandomLimitsMax[j], size= 1))
zNEWRandomSpot=np.transpose(np.array(zNEWRandomSpot))
if isFilament2D:
zNEWRandomSpot=np.delete(zNEWRandomSpot,2,1)
#Replace entire row with new positions
zRandomSpotsTerminal[zBrokenRandomSpots[0][i],:]=zNEWRandomSpot
#Calculation of Mean Nearest Neighbor based on branch points and terminal points
zArrayTerminal=cdist(zRandomSpotsTerminal,zRandomSpotsTerminal)
zArrayTerminalMin=np.where(zArrayTerminal>0, zArrayTerminal, np.inf).min(axis=1)
zAverageNNTerminaTPointRandom=np.mean(zArrayTerminalMin)
#Calculation of Regulatiry Index
zAllFilamentsRegularityIndexTP.append(zAverageNNTerminalPoint/zAverageNNTerminaTPointRandom)
else:
zAllFilamentsRegularityIndexTP.append(0)
###############################################################################
#Branch Point Classification
#Find Terminal segmentIds
wTerminalSegmentIDs=[]
for i in range(len(wFilamentTerminalPointsNEWCurrent)):
wTerminalSegmentIDcurrent = np.where(np.array(vFilamentsEdges) == np.where((np.array(vFilamentsXYZ)==wFilamentTerminalPointsNEWCurrent[i].tolist()).all(1))[0].tolist())[0].tolist()[0]
wTerminalSegmentIDs.append(vFilamentsEdgesSegmentId[wTerminalSegmentIDcurrent])
wNodeSegments = []
vNodeTypePerFilament = []
for i in range(len(wFilamentBranchPointsNEWCurrent)):
#Identify segment IDs that are attached to branch point
wNodeSegments.append(np.array(vFilamentsEdgesSegmentId)[np.where(np.array(vFilamentsEdges) == np.where(np.array(vFilamentsXYZ)[:,0] == wFilamentBranchPointsNEWCurrent[i][0])[0].tolist()[0])[0].tolist()].tolist())
#Identify if segments attached to node are a terminal segment
#count number per each node
# len(np.intersect1d(wTerminalSegmentIDs,wNodeSegments[i]))
vNodeTypePerFilament.append(len(np.intersect1d(wTerminalSegmentIDs,wNodeSegments[i])))
vNodeTypesComplete.append(len(np.intersect1d(wTerminalSegmentIDs,wNodeSegments[i])))
#list filamientID for each node
vNodeFilamentIdsComplete.extend([vFilamentIds[vFilamentCountActual-1]]*len(wFilamentBranchPointsNEWCurrent))
#categories. 1) Arborization, 2)Continuation, 3) Terminal
#1)Arborization (A) nodes have two bifurcating children.
#2)Continuation (C) nodes have one bifurcating and one terminating child.
#3)Termination (T) nodes have two terminating children.
#4)Other (T+) nodes more than 2 terminating children.
###############################################################################
#Calculate Filament Complexity Index
wFilamentTerminalPointsNEWCurrentBranchDepth = np.array(vAllFilamentDendriteBranchDepth)[np.where((wFilamentTerminalPointsNEW[:, None] == np.array(vFilamentsXYZ)).all(-1).any(-1))[0].tolist()]
wFilamentTerminalPointsNEWCurrentBranchLength = np.array(vAllFilamentDendriteLength)[np.where((wFilamentTerminalPointsNEW[:, None] == np.array(vFilamentsXYZ)).all(-1).any(-1))[0].tolist()]
wFilamentComplexityNumberPrimaryDendrites = np.size(np.where(wFilamentTerminalPointsNEWCurrentBranchDepth==0))
wFilamentComplexitySumTerminalBranchOrder = np.sum(wFilamentTerminalPointsNEWCurrentBranchDepth)
wFilamentComplexityIndexComplete.append((wFilamentComplexitySumTerminalBranchOrder + np.size(wFilamentTerminalPointsNEWCurrent[:,0]))/vAllFilamentLengthSum[aFilamentIndex]/wFilamentComplexityNumberPrimaryDendrites)
##############################################################################
##############################################################################
vAllSegmentsPerFilamentRadiusWorkingInserts=[]
vAllSegmentsPerFilamentPositionsWorkingInserts=[]
vAllSegmentsTypesPerFilamentWorkingInserts=[]
vAllSegmentIdsPerFilamentInserts=[]
vAllSegmentIdsPerFilamentDendriteIndex=[]
vAnglesPerCurrentSegment = []
vNewStatTortuosityPerSegment = []
vNewStatTortuosityPerSegmentSum = []
vAllNewSpotsBoutonsPositionXYZ=[]
vAllNewSpotsBoutonsRadius=[]
vSegmentBranchLength=[]
vStatisticBoutonWidth=[]
wDendriteSegmentIds=[]
wSpineSegmentIds=[]
wShortestDistanceToSegment=[]
zReOrderedFilamentPointIndex=[]
zReOrderedFilamentPositions=[]
zReOrderedFilamentRadius=[]
zReOrderedFilamentPointIndexWorking=[]
zReOrderedFilamentPositionsWorking=[]
zReOrderedFilamentRadiusWorking=[]
zReorderedvSegmentIds=[]
zReorderedvSegmentType=[]
wSpotsAllIndexPerFilament=[]
wCompleteColocSpotDistAlongFilamentStatWorking=[]
xCompleteSpotDistAlongFilamentStatWorking=[]
xCompleteBoutonDistAlongFilamentStatWorking=[]
wCompleteTerminalPointsDistAlongFilamentStatWorking=[]
wCompleteBranchPointsDistAlongFilamentStatWorking=[]
xCompleteDendriteDendriteContactSpotPositions=[]
xLengthContactsWorkingDendrite=[]