-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Neurons.jl
executable file
·2289 lines (2039 loc) · 86.1 KB
/
Neurons.jl
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
module Neurons
include("Segments.jl")
using .Segments
using ..NodeNets
using ..SWCs
using ..Utils.BoundingBoxes
using .Segments.Synapses
using LsqFit
using ImageFiltering
using OffsetArrays
using DataFrames
using SparseArrays
#import LinearAlgebra: norm, dot, normalize
using LinearAlgebra
using Serialization
using Statistics
using NearestNeighbors
const EXPANSION = (one(UInt32), one(UInt32), one(UInt32))
const VOXEL_SIZE = (500, 500, 500)
export Neuron
mutable struct Neuron{T}
# x,y,z,r, the coordinates should be in physical coordinates
segmentList ::Vector{Segment{T}}
connectivityMatrix ::SparseMatrixCSC{Bool, Int}
end
"""
Neuron
a neuron modeled by interconnected segments
"""
function Neuron(nodeNet::NodeNet{T}) where T
radii = NodeNets.get_radii(nodeNet)
# locate the root node with largest radius
# theoritically this should be the center of soma
_, rootNodeId = findmax(radii)
Neuron(nodeNet, rootNodeId; radii=radii)
end
function Neuron(nodeNet::NodeNet{T}, rootNodeId::Integer;
radii=NodeNets.get_radii(nodeNet)) where T
# the properties from nodeNet
nodes = NodeNets.get_node_list(nodeNet)
# flags labeling whether this node was collected to the net
collectedFlagVec = falses(length(nodes))
# connectivity matrix of nodes in nodeNet
nodesConnectivityMatrix = NodeNets.get_connectivity_matrix(nodeNet)
seedNodeIdList::Vector = [rootNodeId]
# grow the main net
neuron = Neuron!(rootNodeId, nodeNet, collectedFlagVec)
# println(sum(collectedFlagVec), " visited voxels in ", length(collectedFlagVec))
while !all(collectedFlagVec)
# println(sum(collectedFlagVec), " visited voxels in ", length(collectedFlagVec))
# there exist some uncollected nodes
# find the uncollected node that is closest to the terminal nodes as seed
# terminal node should have high priority than normal nodes.
seedNodeId2 = find_seed_node_id(neuron, nodeNet, collectedFlagVec)
mergingSegmentId1, mergingNodeIdInSegment1, weightedTerminalDistance =
find_merging_terminal_node_id(neuron, nodeNet[seedNodeId2])
# for some spine like structures, they should connect to nearest node
# rather than terminal point.
closestSegmentId1, closestNodeIdInSegment1, closestDistance =
find_closest_node(neuron, nodeNet[seedNodeId2][1:3])
if closestDistance < weightedTerminalDistance / T(2)
mergingSegmentId1 = closestSegmentId1
mergingNodeIdInSegment1 = closestNodeIdInSegment1
end
# grow a new net from seed, and mark the collected nodes
subnet = Neuron!(seedNodeId2, nodeNet, collectedFlagVec)
# merge the subnet to main net
#@show get_num_nodes(neuron)
#@show get_num_nodes(subnet)
totalNumNodes = get_num_nodes(neuron) + get_num_nodes(subnet)
neuron = merge( neuron, subnet,
mergingSegmentId1, mergingNodeIdInSegment1)
@assert totalNumNodes == get_num_nodes(neuron)
#@show get_num_nodes(neuron)
end
@assert length(nodeNet) == get_num_nodes(neuron)
"$(length(nodeNet)) !== $(get_num_nodes(neuron))"
neuron
end
"""
Neuron!(seedNodeId::Integer, nodeNet::NodeNet, collectedFlagVec::BitArray{1})
build a net from a seed node using connected component
mark the nodes in this new net as collected, so the collectedFlagVec was changed.
"""
function Neuron!(seedNodeId::Integer, nodeNet::NodeNet{T}, collectedFlagVec::BitArray{1}) where T
# initialization
segmentList = Vector{Segment{T}}()
parentSegmentIdList = Vector{Int}()
childSegmentIdList = Vector{Int}()
nodes = NodeNets.get_node_list(nodeNet)
nodeClassList = NodeNets.get_node_class_list(nodeNet)
nodesConnectivityMatrix = NodeNets.get_connectivity_matrix( nodeNet )
@assert length(collectedFlagVec) == length(nodes)
# the seed of segment should record both seed node index
# and the the parent segment index
# the parent segment index of root segment is -1
segmentSeedList = [(seedNodeId, -1)]
# depth first search
while !isempty(segmentSeedList)
seedNodeId, segmentParentId = pop!(segmentSeedList)
# grow a segment from seed
nodeListInSegment = Vector{NTuple{4, T}}()
seedNodeIdList = [seedNodeId]
#firstSeedNodeId = seedNodeId
#segmentClass = nodeClassList[seedNodeId]
while true
# construct this segment
seedNodeId = pop!(seedNodeIdList)
# make sure that all the node class is the same with the seed
#if segmentClass != nodeClassList[seedNodeId]
# @show firstSeedNodeId, segmentClass, seedNodeId, nodeClassList[seedNodeId]
#end
# Note that this assertion do not work, might be a bug somewhere!
#@assert segmentClass == nodeClassList[seedNodeId]
# push the seed node
push!(nodeListInSegment, nodes[seedNodeId])
# label this node index as collected
collectedFlagVec[ seedNodeId ] = true
# println(sum(collectedFlagVec), " visited voxels in ", length(collectedFlagVec))
# find the connected nodes
connectedNodeIdList,_ = findnz(nodesConnectivityMatrix[:, seedNodeId])
# exclude the collected nodes
connectedNodeIdList = connectedNodeIdList[ .!collectedFlagVec[connectedNodeIdList] ]
if length(connectedNodeIdList) == 1
# belong to the same segment
push!(seedNodeIdList, connectedNodeIdList[1])
else
# finish constructing this segment
# because this is the terminal branching point or multiple branching points
segmentClass = nodeClassList[seedNodeId]
segment = Segment(nodeListInSegment; class = segmentClass)
push!(segmentList, segment)
if segmentParentId != -1
# this is not the root segment, establish the segment connection
# @assert length(segment) > 1
push!(parentSegmentIdList, segmentParentId)
push!(childSegmentIdList, length(segmentList))
end
# seed new segments
# if this is terminal segment, no seed will be pushed
for connectedNodeId in connectedNodeIdList
# the length of segmentList will be the parent segment ID of the seeded segment
parentSegmentId = length(segmentList)
push!(segmentSeedList, (connectedNodeId, parentSegmentId))
end
break
end
end
end
for segment in segmentList
@assert !isempty(segment)
end
@assert length(parentSegmentIdList) == length(childSegmentIdList)
# note that the connectivity matrix should be a square matrix for easier use
connectivityMatrix = sparse(parentSegmentIdList, childSegmentIdList, true,
length(segmentList), length(segmentList))
for childSegmentId in 1:length(childSegmentIdList)
parentSegmentIdList,_ = findnz(connectivityMatrix[:, childSegmentId])
# segment should only have one parent
@assert length(parentSegmentIdList) <= 1
end
Neuron{T}(segmentList, connectivityMatrix)
end
function Neuron( seg::Array{ST,3}; obj_id::ST = convert(ST,1),
expansion::NTuple{3,UInt32}=EXPANSION ) where ST
nodeNet = NodeNet( seg; obj_id = obj_id, expansion = expansion )
Neuron( nodeNet )
end
function Neuron( swc::SWC )
nodeNet = NodeNet( swc )
# respect the point class
Neuron( nodeNet )
end
"""
Neuron( swcString::AbstractString )
transform string from swc content to Neuron
"""
function Neuron( swcString::AbstractString )
swc = SWC(swcString)
Neuron( swc )
end
######################### IO ################
function load(fileName::AbstractString)
if endswith(fileName, ".swc")
return load_swc(fileName)
elseif endswith(fileName, ".swc.bin")
return load_swc_bin(fileName)
elseif endswith(fileName, ".bin")
return load_bin(fileName)
else
error("only support .swc or .swc.bin file: $fileName")
end
end
function save(self::Neuron, fileName::AbstractString)
if endswith(fileName, ".swc")
save_swc(self, fileName)
elseif endswith(fileName, ".swc.bin")
save_swc_bin(self, fileName)
elseif endswith(fileName, ".bin")
save_bin(self, fileName)
else
error("unsupported format: $(fileName)")
end
end
function load_swc( fileName::AbstractString )
swcString = read( fileName , String)
Neuron( swcString )
end
function save_swc(self::Neuron, fileName::AbstractString)
swc = SWC(self)
SWCs.save( swc, fileName )
end
function load_swc_bin( fileName::AbstractString )
swc = SWCs.load_swc_bin( fileName )
Neuron( swc )
end
function save_swc_bin( self::Neuron, fileName::AbstractString )
SWCs.save_swc_bin( SWCs.SWC(self), fileName )
end
function load_bin(fileName::AbstractString)
open(fileName) do f
return Serialization.deserialize(f)
end
end
function save_bin(self::Neuron, fileName::AbstractString)
open(fileName, "w") do f
Serialization.serialize(f, self)
end
nothing
end
####################### properties ##############
"""
get_path_length_normalized_features(self::Neuron)
get feature vector, returned as NamedTuple
Notethat some features were normalized using total path length
"""
function get_path_length_normalized_features(self::Neuron)
totalPathLength = get_total_path_length(self)
return (
branchingAngle = mean(map(i->get_branching_angle(self,i), 1:length(self))),
tortuosity = mean(map(Segments.get_tortuosity, self)),
symmetry = get_asymmetry(self),
typicalRadius = get_typical_radius(self),
numBranchingPoints = get_num_branching_points(self) / totalPathLength,
medianBranchPathLength = median(get_segment_path_length_list(self)),
surfaceArea = get_surface_area(self) / totalPathLength,
volume = get_volume(self) / totalPathLength
)
end
"""
get_root_segment_id( self::Neuron )
the first segment should be the root segment, and the first node should be the root node
"""
@inline function get_root_segment_id(self::Neuron) 1 end
@inline function get_root_segment(self::Neuron)
get_segment_list(self)[get_root_segment_id(self)]
end
"""
get_root_node( self::Neuron )
the returned root node is a tuple of Float64, which represents x,y,z,r
"""
function get_root_node( self::Neuron )
rootSegmentId = get_root_segment_id(self)
rootSegment = get_segment_list(self)[ rootSegmentId ]
rootSegment[1]
end
"""
get_num_segments(self::Neuron)
"""
@inline function get_num_segments(self::Neuron) length(self.segmentList) end
"""
get_num_branching_points(self::Neuron)
"""
function get_num_branching_points(self::Neuron)
numSegmentingPoint = 0
for index in 1:get_num_segments(self)
childrenSegmentIdList = get_children_segment_id_list(self, index)
if length(childrenSegmentIdList) > 0
numSegmentingPoint += 1
end
end
numSegmentingPoint
end
@inline function get_segment_list(self::Neuron{T}) where T
self.segmentList::Vector{Segment{T}}
end
@inline function get_connectivity_matrix(self::Neuron)
self.connectivityMatrix
end
"""
get_segment_order_list( self::Neuron )
following the Julia indexing style, the root segment order is 1.
"""
function get_segment_order_list(self::Neuron)
segmentOrderList = Vector{Int}()
sizehint!(segmentOrderList, get_num_segments(self))
index2order = Dict{Int,Int}()
# the first one is segment index, the second one is segment order
seedSegmentIdOrderList = Vector{NTuple{2,Int}}([(1,1)])
while !isempty( seedSegmentIdOrderList )
segmentId, segmentOrder = pop!(seedSegmentIdOrderList)
index2order[segmentId] = segmentOrder
childrenSegmentIdList = get_children_segment_id_list(self, segmentId)
for childSegmentId in childrenSegmentIdList
push!(seedSegmentIdOrderList, (childSegmentId, segmentOrder+1))
end
end
for index in 1:get_num_segments( self )
push!(segmentOrderList, index2order[index])
end
segmentOrderList
end
"""
get_segment_length_list( self::Neuron )
get a vector of Integer, which represent the length of each segment
"""
@inline function get_segment_length_list( self::Neuron ) map(length, get_segment_list(self)) end
"""
get_node_num( self::Neuron )
get total number of nodes
"""
@inline function get_node_num( self::Neuron )
sum(map(length, get_segment_list(self)))
end
"""
get_node_list(self::Neuron)
get the node list. the first one is root node.
"""
function get_node_list( self::Neuron{T} ) where T
nodeList = Vector{NTuple{4, T}}(undef, get_node_num(self))
i = 0
for segment in get_segment_list(self)
for node in Segments.get_node_list(segment)
i += 1
nodeList[i] = node
end
end
nodeList
end
"""
get_node_class_list(self::Neuron)
the class defines the type of node, such as axon, dendrite and soma.
"""
function get_node_class_list( self::Neuron )
nodeClassList = Vector{UInt8}(undef, get_node_num(self))
i = 0
for segment in get_segment_list(self)
nodeNumInSegment = length(segment)
class = Segments.get_class(segment)
nodeClassList[i+1:i+nodeNumInSegment] .= class
i += nodeNumInSegment
end
nodeClassList
end
"""
get_edge_list( self::Neuron )
get the edges with type of Vector{NTuple{2, Int}}
"""
function get_edge_list( self::Neuron )
edgeList = Vector{NTuple{2,Int}}()
segmentStartNodeIdList = Vector{Int}()
segmentStopNodeIdList = Vector{Int}()
# total number of nodes
nodeNum = 0
for (segmentId, segment) in enumerate(get_segment_list(self))
push!(segmentStartNodeIdList, nodeNum+1)
# build the edges inside segment
for nodeId in nodeNum+1:nodeNum+length(segment)-1
push!(edgeList, (nodeId, nodeId+1))
end
# update node number
nodeNum += length(segment)
push!(segmentStopNodeIdList, nodeNum)
end
# add segment connections
parentSegmentIdList, childSegmentIdList, _ = findnz( get_connectivity_matrix(self) )
for (index, parentSegmentId) in enumerate( parentSegmentIdList )
childSegmentId = childSegmentIdList[ index ]
parentNodeId = segmentStopNodeIdList[ parentSegmentId ]
childNodeId = segmentStartNodeIdList[ childSegmentId ]
push!( edgeList, (parentNodeId, childNodeId) )
end
edgeList
end
function get_edge_num(self::Neuron)
length( get_edge_list(self) )
end
function get_path_to_soma_length(self::Neuron{T}, synapse::Synapse{T}) where T
mergingSegmentId, closestNodeId = find_closest_node( self, synapse )
get_path_to_soma_length( self, mergingSegmentId; nodeId=closestNodeId )
end
"""
get_path_to_soma_length(self::Neuron{T}, segmentId::Integer;
segmentList::Vector{Segment}=get_segment_list(self),
nodeId::Int = length(segmentList[segmentId]),
segmentPathLengthList::Vector{T} = get_segment_path_length_list(self)) where T
"""
function get_path_to_soma_length(self::Neuron{T}, segmentId::Integer;
segmentList::Vector{Segment{T}}=get_segment_list(self),
nodeId::Integer = length(segmentList[segmentId]),
segmentPathLengthList::Vector{T} = get_segment_path_length_list(self)) where T
path2RootLength = Segments.get_path_length( segmentList[segmentId]; nodeId=nodeId )
while true
parentSegmentId = get_parent_segment_id(self, segmentId )
if parentSegmentId < 1
# root segment do not have parent
break
else
path2RootLength += segmentPathLengthList[ parentSegmentId ]
segmentId = parentSegmentId
end
end
path2RootLength
end
get_path_to_root_length = get_path_to_soma_length
function get_pre_synapse_to_soma_path_length_list(self::Neuron{T};
segmentList::Vector{Segment{T}}=get_segment_list(self),
segmentPathLengthList::Vector{T}=get_segment_path_length_list(self)) where T
preSynapseToSomaPathLengthList = Vector{T}()
for (segmentId, segment) in enumerate( segmentList )
preSynapseList = Segments.get_pre_synapse_list( segment )
# get the node IDs with synapses attached
nodeIdList = Int[]
for (i,synapses) in enumerate(preSynapseList)
if !ismissing(synapses)
@assert !isempty(synapses)
push!(nodeIdList, i)
end
end
pathToSomaLengthList = map(nodeId->get_path_to_soma_length(self, segmentId;
segmentList=segmentList,
segmentPathLengthList=segmentPathLengthList,
nodeId=nodeId), nodeIdList)
append!(preSynapseToSomaPathLengthList, pathToSomaLengthList)
end
preSynapseToSomaPathLengthList
end
function get_post_synapse_to_soma_path_length_list(self::Neuron{T};
segmentList::Vector{Segment{T}}=get_segment_list(self),
segmentPathLengthList::Vector{T}=get_segment_path_length_list(self)) where T
postSynapseToSomaPathLengthList = Vector{T}()
for (segmentId, segment) in enumerate( segmentList )
postSynapseList = Segments.get_post_synapse_list( segment )
# get the node IDs with synapses attached
nodeIdList = Int[]
for (i,synapses) in enumerate(postSynapseList)
if !ismissing(synapses)
@assert !isempty(synapses)
push!(nodeIdList, i)
end
end
pathToSomaLengthList = map(nodeId->get_path_to_soma_length(self, segmentId;
segmentList=segmentList,
segmentPathLengthList=segmentPathLengthList,
nodeId=nodeId), nodeIdList)
append!(postSynapseToSomaPathLengthList, pathToSomaLengthList)
end
postSynapseToSomaPathLengthList
end
"""
get_segment_path_length_list(self::Neuron{T};
segmentList::Vector{Segment{T}}=get_segment_list(self),
class::{Nothing,UInt8}=nothing)
get euclidean path length of each segment
"""
function get_segment_path_length_list( self::Neuron{T};
segmentList::Vector{Segment{T}} = get_segment_list(self),
class::Union{Nothing,UInt8}=nothing ) where T
ret = Vector{T}()
for (index, segment) in enumerate( segmentList )
segmentPathLength = Segments.get_path_length( segment )
# add the edge length to parent node
parentSegmentId = get_parent_segment_id(self, index)
if parentSegmentId > 0
parentSegment = segmentList[ parentSegmentId ]
parentNode = parentSegment[ end ]
node = segment[1]
segmentPathLength += norm( [map((x,y)->x-y, node[1:3], parentNode[1:3])...] )
end
if class == nothing || class==Segments.get_class(segment)
# include all segment the class matches
push!(ret, segmentPathLength)
end
end
ret
end
function get_node_distance_list(neuron::Neuron{T}) where T
nodeList = Neurons.get_node_list(neuron)
edgeList = Neurons.get_edge_list(neuron)
nodeDistanceList = Vector{T}()
sizehint!(nodeDistanceList, length(edgeList))
for (src, dst) in edgeList
d = norm( [map(-, nodeList[src][1:3], nodeList[dst][1:3])...] )
push!(nodeDistanceList, d)
end
nodeDistanceList
end
"""
get_total_path_length(self::Neuron; class::Union{Nothing,UInt8}=nothing)
the default class=nothing will include all of the segments
"""
@inline function get_total_path_length(self::Neuron; class::Union{Nothing,UInt8}=nothing)
get_segment_path_length_list(self; class=class) |> sum
end
"""
get_segment_end_node_id_list( self::Neuron )
get a vector of integer, which represent the node index of segment end
"""
@inline function get_segment_end_node_id_list( self::Neuron ) cumsum( get_segment_length_list(self) ) end
"""
get_num_nodes(self::Neuron)
get number of nodes
"""
@inline function get_num_nodes( self::Neuron )
segmentList = get_segment_list(self)
sum(map(length, segmentList))
end
"""
get_furthest_terminal_node_pair_direction(self::Neurons)
Return:
vec::Vector{T}, the 3d vector representing the direction
maxNodeDistance::T, the maximum distance between terminal nodes
"""
@inline function get_furthest_terminal_node_pair_direction(self::Neuron{T}) where T
terminalNodeList = Neurons.get_terminal_node_list(self)
get_furthest_terminal_node_pair_direction(terminalNodeList)
end
function get_furthest_terminal_node_pair_direction(terminalNodeList::Vector{NTuple{4,T}}) where T
# find the farthest node pair
vec = zeros(T, 2)
maxNodeDistance = zero(T)
for i in 1:length(terminalNodeList)
node1 = terminalNodeList[i][1:3]
for j in i+1:length(terminalNodeList)
node2 = terminalNodeList[j][1:3]
v = [node1...] .- [node2...]
d = norm(v)
if d > maxNodeDistance
vec = v
maxNodeDistance = d
end
end
end
return vec, maxNodeDistance
end
"""
get_mass_center( self::Neuron )
mass center was computed simply as center of all nodes
"""
function get_mass_center( self::Neuron )
nodeList = get_node_list(self)
x = sum(map(n->n[1], nodeList)) / length(nodeList)
y = sum(map(n->n[2], nodeList)) / length(nodeList)
z = sum(map(n->n[3], nodeList)) / length(nodeList)
(x,y,z)
end
"""
get_typical_radius( self::Neuron )
Typical radius is the root-mean-square distance of dendritic arbor points to the center of mass (in nm)
"""
function get_typical_radius( self::Neuron )
massCenter = get_mass_center( self )
nodeList = get_node_list( self )
typicalRadius = 0.0
for node in nodeList
typicalRadius += norm([massCenter...] .- [node[1:3]...]) / length(nodeList)
end
typicalRadius
end
"""
get_asymmetry( self::Neuron )
asymmetry was measured by the euclidean distance between root node and mass center
"""
function get_asymmetry( self::Neuron )
massCenter = get_mass_center( self )
root = get_root_node( self )
norm( [massCenter...] .- [root[1:3]...] )
end
"""
get_children_segment_id_list(self::Neuron, parentSegmentId::Integer)
"""
@inline function get_children_segment_id_list(self::Neuron, parentSegmentId::Integer)
get_children_segment_id_list(self.connectivityMatrix, parentSegmentId)
end
@inline function get_children_segment_id_list(connectivityMatrix::SparseMatrixCSC,
parentSegmentId::Integer)
childrenSegmentIdList,_ = findnz(connectivityMatrix[parentSegmentId, :])
childrenSegmentIdList
end
@inline function get_parent_segment_id( self::Neuron, childSegmentId::Integer )
get_parent_segment_id(self.connectivityMatrix, childSegmentId)
end
function get_parent_segment_id( connectivityMatrix::SparseMatrixCSC, childSegmentId::Integer )
parentSegmentIdList,_ = findnz(connectivityMatrix[:, childSegmentId])
if isempty( parentSegmentIdList )
# no parent, this is a root segment
return 0
else
if length(parentSegmentIdList) > 1
@show parentSegmentIdList
error("the neuron is supposed to be a tree, can not have loop with multiple parent segments.")
end
return parentSegmentIdList[1]
end
end
"""
get_subtree_segment_id_list( self, segmentInde )
get the segment index list of subtree
"""
function get_subtree_segment_id_list( self::Neuron, segmentId::Integer )
@assert segmentId > 0 && segmentId <= get_num_segments(self)
subtreeSegmentIdList = Vector{Integer}()
seedSegmentIdList = [segmentId]
while !isempty( seedSegmentIdList )
seedSegmentId = pop!( seedSegmentIdList )
push!(subtreeSegmentIdList, seedSegmentId)
childrenSegmentIdList = get_children_segment_id_list( self, seedSegmentId )
append!(seedSegmentIdList, childrenSegmentIdList)
end
subtreeSegmentIdList
end
function get_terminal_segment_id_list( self::Neuron; startSegmentId::Integer = 1 )
terminalSegmentIdList = Vector{Int}()
for segmentId in startSegmentId:length(get_segment_list(self))
childrenSegmentIdList = get_children_segment_id_list(self, segmentId)
if isempty(childrenSegmentIdList)
push!(terminalSegmentIdList, segmentId)
end
end
terminalSegmentIdList
end
@inline function get_terminal_node_list( self::Neuron; startSegmentId::Integer = 1 )
terminalSegmentIdList = get_terminal_segment_id_list( self )
map( x -> Segments.get_node_list(x)[end], get_segment_list(self)[ terminalSegmentIdList ] )
end
"""
get_branching_angle( self::Neuron, segmentId::Integer; nodeDistance::AbstractFloat )
if the node is too close the angle might not be accurate. For example, if they are voxel neighbors, the angle will alwasys be 90 or 45 degree. Thus, we have nodeDistance here to help make the nodes farther away.
Note that the acos returns angle in the format of radiens.
"""
function get_branching_angle( self::Neuron, segmentId::Integer; nodeDistance::Real = 5000.0 )
segment = self[segmentId]
parentSegmentId = get_parent_segment_id(self, segmentId)
if parentSegmentId < 1
# this is root segment
return 0.0
end
parentSegment = self[ get_parent_segment_id(self, segmentId) ]
if length(parentSegment) == 1 || length(segment) == 1
return 0.0
end
branchingNode = parentSegment[end]
parentNode = parentSegment[end-1]
for node in parentSegment
if Segments.get_nodes_distance(node, branchingNode) < nodeDistance
parentNode = node
break
end
end
if parentNode == branchingNode
@warn("parent node is the same with branching node: $(branchingNode)")
return 0.0
end
childNode = segment[1]
for index in length(segment):1
node = segment[index]
if Segments.get_nodes_distance(node, branchingNode) < nodeDistance
childNode = node
break
end
end
if childNode == branchingNode
@warn("child node is the same with branching node: $(branchingNode)")
return 0.0
end
# compute the angle among the three nodes using the definition of dot product
# get the two vectors
v1 = map(-, parentNode[1:3], branchingNode[1:3] )
v2 = map(-, branchingNode[1:3], childNode[1:3] )
# normalize the vector
nv1 = normalize([v1...])
nv2 = normalize([v2...])
dotProduct = dot(nv1, nv2)
# tolerate some numerical varition. the dot product could go greater than 1.
@assert dotProduct < 1.001 "impossible dotProduct: $(dotProduct)"
return acos( min(1.0, dotProduct) )
end
"""
get_sholl_number(self::Neuron, shollRadius::AbstractFloat)
suppose there is a sphere centered on the root node. The sholl number is the number of contact points of the neuron and sphere.
"""
function get_sholl_number(self::Neuron, shollRadius::AbstractFloat)
root = get_root_node(self)
nodeList = get_node_list( self )
edgeList = get_edge_list( self )
get_sholl_number( root, nodeList, edgeList, shollRadius )
end
function get_sholl_number(root::NTuple{4, Float32}, nodeList::Vector{NTuple{4,Float32}},
edgeList::Vector{NTuple{2,Int}}, shollRadius::AbstractFloat)
shollNum = 0
for edge in edgeList
node1 = nodeList[ edge[1] ]
node2 = nodeList[ edge[2] ]
if (Segments.get_nodes_distance(root, node1) > shollRadius) != (Segments.get_nodes_distance(root, node2) > shollRadius)
shollNum += 1
end
end
shollNum
end
function get_sholl_number_list(self::Neuron, shollRadiusList::Vector)
root = get_root_node(self)
nodeList = get_node_list( self )
edgeList = get_edge_list( self )
shollNumList = zeros(Int, length(shollRadiusList))
for (index, shollRadius) in enumerate(shollRadiusList)
shollNumList[index] = get_sholl_number(root, nodeList, edgeList, shollRadius)
end
shollNumList
end
"""
get_sholl_number_list(self::Neuron, radiusStep::AbstractFloat; numStep::Integer=0)
if the number of steps is 0, we'll auto compute the step number according to the farthest terminal node.
"""
function get_sholl_number_list(self::Neuron, radiusStep::Real;
numStep::Integer=0)
shollNumList = Vector{Float64}()
if numStep==0
# automatically computing step number
root = get_root_node(self)
terminalNodeList = get_terminal_node_list(self)
terminal2RootDistanceList = map(n->Segments.get_nodes_distance(root,n), terminalNodeList)
maxDistance = maximum( terminal2RootDistanceList )
numStep = fld(maxDistance, radiusStep)
end
radius = 0.0
for n in 1:numStep
radius += n*radiusStep
shollNum = get_sholl_number( self, radius )
push!(shollNumList, shollNum)
end
shollNumList
end
"""
get_gyration_radius( self::Neuron )
The radius of gyration of an object is the square root of the sum of the squares of the radii from the center of mass to all the points on the object, divided by the square root of the number of points.
"""
function get_gyration_radius( self::Neuron; nodeList = get_node_list(self),
massCenter = get_mass_center(self) )
distance2MassCenterList = map( n -> norm([massCenter...].-[n[1:3]...]), nodeList )
sqrt( sum( distance2MassCenterList.^2 ) ) / sqrt(length(nodeList))
end
"""
get_surface_area(self::Neuron)
frustum-based
http://www.analyzemath.com/Geometry_calculators/surface_volume_frustum.html
"""
function get_surface_area(self::Neuron)
ret = zero(Float32)
segmentList = get_segment_list(self)
for (segmentId, segment) in enumerate(segmentList)
ret += Segments.get_surface_area(segment)
parentSegmentId = get_parent_segment_id(self, segmentId)
if parentSegmentId > 0
parentNode = segmentList[parentSegmentId][end]
h = Segments.euclidean_distance(parentNode[1:3], segment[1][1:3])
# average diameter
r1 = parentNode[4]
r2 = segment[1][4]
ret += pi * (r1+r2) * sqrt( h*h + (r1-r2)*(r1-r2) )
end
end
ret
end
"""
get_volume(self::Neuron)
frustum based volume:
http://jwilson.coe.uga.edu/emt725/Frustum/Frustum.cone.html
"""
function get_volume(self::Neuron)
ret = zero(Float32)
segmentList = get_segment_list(self)
for (segmentId, segment) in enumerate(segmentList)
ret += Segments.get_volume(segment)
parentSegmentId = get_parent_segment_id(
self, segmentId)
if parentSegmentId > 0
parentNode = segmentList[parentSegmentId][end]
node = segment[1]
r1 = node[4]
r2 = parentNode[4]
h = Segments.euclidean_distance(node[1:3], parentNode[1:3])
ret += pi * h * (r1*r1 + r1*r2 + r2*r2) / Float32(3)
end
end
ret
end
"""
get_fractal_dimension( self::Neuron )
compute fractal dimension using cumulative-mass method.
https://www.sciencedirect.com/science/article/pii/016502709400115W
Return:
fractalDimension::Int
radiusList::Float64 the scanning disk radii
averageMassList::Float64 the average mass inside the disk
"""
function get_fractal_dimension( self::Neuron )
nodeList = get_node_list( self )
massCenter = get_mass_center(self)
gyrationRadius = get_gyration_radius( self; nodeList=nodeList, massCenter=massCenter )
# find the nodes inside the gyration radius
diskCenterList = Vector{NTuple{4,Float32}}()
for node in nodeList
if Segments.get_nodes_distance( massCenter, node ) < gyrationRadius
push!(diskCenterList, node)
end
end
# radius list of a sequence of concentric disks
radiusNum = 10
radiusStep = 0.5*gyrationRadius/radiusNum
radiusList = zeros(radiusNum)
radius = 0.0
for i in 1:radiusNum
radius += i*radiusStep
radiusList[i] = radius
end
# iterate all the nodes inside gyration radius as the center of scanning disks
averageMassList = zeros( length(radiusList) )
for (centerId, center) in enumerate(diskCenterList)
for (radiusId, radius) in enumerate(radiusList)
for node in nodeList
if Segments.get_nodes_distance( center, node) < radius
averageMassList[radiusId] += 1.0 / length(diskCenterList)
end
end
end
end
# fit the curve and get slop as fractal dimension
model(x,p) = p[1]*x + p[2]
p0 = [1.0, 0]
fit = curve_fit(model, log(radiusList), log.(averageMassList), p0)
fractalDimension = fit.param[1]
return fractalDimension, radiusList, averageMassList
end
"""
get_mask(self::Neuron, voxelSize::Union{Tuple, Vector})
compute binary representation of the neuron skeleton
"""
function get_mask(self::Neuron, voxelSize::Union{Tuple, Vector})
nodeList = get_node_list(self)
voxelSet = Set{NTuple{3, Int}}()
for node in nodeList
voxelCoordinate = map((x,y)->round(Int, x/y), node[1:3], voxelSize)
push!(voxelSet, (voxelCoordinate...,))
end
boundingBox = Segments.BoundingBox( voxelSet )
range = BoundingBoxes.get_unit_range(boundingBox)
sz = size(boundingBox)
# initialize the map
mask = zeros(Bool, sz)
mask = OffsetArray(mask, range...)
@inbounds for voxel in voxelSet
# add a small number to make sure that there is no 0
mask[voxel...] = true
end
mask
end
function get_bounding_box(self::Neuron)
segmentList = get_segment_list(self)
bb = Segments.get_bounding_box( segmentList[1] )
for segment in segmentList[2:end]
bb = union(bb, Segments.get_bounding_box(segment))
end
return bb
end
function get_2d_binary_projection(self::Neuron; axis=3, voxelSize=VOXEL_SIZE)
nodeList = get_node_list(self)
voxelSet = Set{NTuple{3, Int}}()
for node in nodeList
voxelCoordinate = map((x,y)->round(Int, x/y), node[1:3], voxelSize)
push!(voxelSet, (voxelCoordinate...,))
end
boundingBox = Segments.BoundingBox( voxelSet )
range = Segments.BoundingBoxes.get_unit_range(boundingBox)[1:2]
sz = size(boundingBox)[1:2]
# initialize the map
mask = zeros(Bool, sz)
mask = OffsetArray(mask, range...)
@inbounds for voxel in voxelSet
# add a small number to make sure that there is no 0
mask[voxel[1:2]...] = true
end
mask