-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNeuronGeometry.py
2676 lines (2276 loc) · 93.9 KB
/
NeuronGeometry.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
#!/usr/bin/python
_usageStr=\
"""usage: neuron_readExportedGeometry.py geoFile
get dictionary object describing neuron model geometry info by reading file
"""
import os
from scipy import special, mean, std
from collections import deque
import matplotlib.pyplot as pyplot
from math import log, sqrt, atan, isnan, pi, acos
from bisect import bisect_left
"""
Geometry class public methods: (self is always first argument)
setFileName(_fileName)
numCompartments()
readGeometry() pure virtual
displaySummary()
findBranches()
checkConnectivity()
shollAnalysis()
"""
terminalColors = {
'endColor' : '\033[0m',
'black' : '\033[0;30m',
'red' : '\033[0;31m',
'green' : '\033[0;32m',
'yellow' : '\033[0;33m',
'blue' : '\033[0;34m',
'purple' : '\033[0;35m',
'cyan' : '\033[0;36m',
'lightGray' : '\033[0;37m',
'darkGray' : '\033[1;30m',
'boldRed' : '\033[1;31m',
'boldGreen' : '\033[1;32m',
'boldYellow' : '\033[1;33m',
'boldBlue' : '\033[1;34m',
'boldPurple' : '\033[1;35m',
'boldCyan' : '\033[1;36m',
'white' : '\033[1;37m'
}
def warn(warnStr, extraInfo='', color='boldRed'):
if extraInfo:
print(terminalColors[color] + warnStr + terminalColors['endColor']
+ ': ' + extraInfo)
else:
print(terminalColors[color] + warnStr + terminalColors['endColor'])
def cumsum(values, start=0.0, yieldStart=True):
"""
Return generator to running cumulative sum of values
"""
if yieldStart:
yield start
for v in values:
start += v
yield start
"""
class PathDistanceFinder
Finds network distances from one segment/branch at specified position
Can report distance to another segment/branch at specified position via
.distanceTo()
Can report optimal path to another segment/branch at specified position va
.pathTo()
Can report tortuosity of optimal path via
.tortuosityTo()
Can compute electrotonic lengths from a list of voltages via
.getElectrotonicLengths()
"""
class PathDistanceFinder(object):
def __init__(self, geometry, segment, pos=0.5, warnLoops=False):
self.geometry = geometry
if type(segment) == int:
segment = geometry.segments[segment]
self.network = geometry.segments
elif segment in geometry.segments:
self.network = geometry.segments
elif segment in geometry.branches:
self.network = geometry.branches
else:
raise TypeError('Start segment must be an index to geometry.segments, or'
' an object from geometry.segments or geometry.branches')
self.warnLoops = warnLoops
self.startSegment = segment
self.startPos = pos
self.startCoord = segment.coordAt(pos)
self.distances, self.branchOrders = self._computeDistances()
def distanceTo(self, segment, pos=0.5):
# return distance to specified segment at the specified location
if type(segment) == int:
segment = self.network[segment]
if segment not in self.distances:
raise KeyError('%s is not reachable from the network' % segment.name)
return min(baseD + segment.length * abs(pos - startPos) for
baseD, startPos, pathDesc, path in self.distances[segment])
def pathTo(self, segment, pos=0.5):
# return optimal path to specified segment at specified location
return min(((baseD + segment.length * abs(pos - startPos), path) for
baseD, startPos, pathDesc, path in self.distances[segment]),
key=lambda x:x[0])[1]
def pathDescriptionTo(self, segment, pos=0.5):
# return optimal path to specified segment at specified location
return min(((baseD + segment.length * abs(pos - startPos), pathDesc) for
baseD, startPos, pathDesc, path in self.distances[segment]),
key=lambda x:x[0])[1]
def tortuosityTo(self, segment, pos=0.5):
stopCoord = segment.coordAt(pos)
euclideanD = sqrt(sum((r0-r1)**2 for r0,r1 in zip(self.startCoord,
stopCoord)))
pathD = self.distanceTo(segment, pos)
tortuosity = pathD / euclideanD
if tortuosity < 1.0:
warn('Tortuosity < 1',
self.pathDescriptionTo(segment, pos))
raise RuntimeError('Path to %s at %g has tortuosity < 1'
% (segment.name, pos))
return tortuosity
def branchOrder(self, segment):
return self.branchOrders[segment]
def getElectrotonicLengths(self, steadyVoltages):
# given a list of steady-state voltages, return electrotonic lengths of all
# segments
return [self._getElectrotonicLength(ind, seg, steadyVoltages)
for ind, seg in enumerate(self.network)]
def _getElectrotonicLength(self, index, segment, steadyVoltages):
# given list of steady-state voltages, compute the electrotonic length of a
# specific segment
dSeg = self.distanceTo(segment)
vSeg = steadyVoltages[index]
segOrder = self.branchOrders[segment]
# use only one other neighbor, pick the closest one that is of a different
# branch order
neighbor = min((s for s in segment.neighbors
if self.branchOrders[s] != segOrder),
key=lambda n: abs(self.distanceTo(n) - dSeg))
dNeighbor = self.distanceTo(neighbor)
vNeighbor = steadyVoltages[self.network.index(neighbor)]
eLength = (dNeighbor - dSeg) / log(vSeg / vNeighbor)
if eLength < 0:
nIndex = self.network.index(neighbor)
nOrder = self.branchOrders[neighbor]
print('eLength=%g: ind=%d, nInd=%d, d=%g, nd=%g, v=%g, nV=%g, '
% (eLength, index, nIndex, dSeg, dNeighbor, vSeg, vNeighbor)
+ 'order=%d, nOrder=%d' % (segOrder, nOrder))
return eLength
def _computeDistances(self):
# use Dijkstra's algorithm to find path distance from start to rest of
# neuron.
# Keep track of effect of startPos (starting position in startSegment)
# Also keep track of effect of pos of each final segment
segment, startPos = self.startSegment, self.startPos
# distances is a dict object, with segments as keys
# the values are a list of paths, each path described by a tuple
# (pathDistance, connecting location in the segment, path description,
# list of segments in path )
distances = { segment : [(0.0, startPos,
segment.name + '(%.1f)' % startPos, [segment])] }
branchOrders = { segment : 0 }
openSegments = { segment, }
while openSegments:
segment = openSegments.pop()
for currentD, startPos, segPathDesc, segPath in distances[segment]:
branchOrderInc = 1
if branchOrders[segment] > 0 and len(segment.neighbors) <= 2:
branchOrderInc = 0
#branchOrderInc = int(len(segment.neighbors) > 2)
for neighbor, (connectLoc, nConnectLoc, node) \
in zip(segment.neighbors, segment.neighborLocations):
pathD = currentD + segment.length * abs(startPos - connectLoc)
# check if neighbor in distances?
if neighbor not in distances:
# found path to new segment
nPath = segPath + [neighbor]
nPathDesc = segPathDesc + '->(%.1f)->' % connectLoc + \
neighbor.name + '(%.1f)' % nConnectLoc
distances[neighbor] = [(pathD, nConnectLoc, nPathDesc, nPath)]
openSegments.add(neighbor)
branchOrders[neighbor] = branchOrders[segment] + branchOrderInc
else:
# Either there is a loop involving this segment, or the path is
# backtracking
# Check if the current path is an efficient route to the loop
efficient = True
insertInd = None
loopDistances = distances[neighbor]
for ind, (loopD, loopPos, loopPathDesc, loopPath) in \
enumerate(loopDistances):
traverse = neighbor.length * abs(loopPos - nConnectLoc)
if pathD >= loopD + traverse:
# the new path to neighbor is too slow to ever be useful
efficient = False
break
elif pathD + traverse < loopD:
# the new path to neighbor renders an old one obsolete
loopDistances.pop(ind)
if insertInd is None and pathD < loopD:
insertInd = ind
if efficient:
nPath = segPath + [neighbor]
nPathDesc = segPathDesc + '->(%.1f)->' % connectLoc + \
neighbor.name + '(%.1f)' % nConnectLoc
pathInfo = (pathD, nConnectLoc, nPathDesc, nPath)
if insertInd is None:
loopDistances.append(pathInfo)
else:
loopDistances.insert(insertInd, pathInfo)
distances[neighbor] = loopDistances
openSegments.add(neighbor)
branchOrders[neighbor] = branchOrders[segment] + branchOrderInc
if self.warnLoops and len(loopDistances) > 1:
warn('%d efficient paths to %s.' % (len(loopDistances), neighbor.name))
for ind, loopPos, loopPath in loopDistances:
print(loopPath)
return distances, branchOrders
class Geometry:
def __init__(self, _fileName = None):
# who knows, do something?
self.path = None
self.fileName = None
self.name = None
# store the geometry info here
self.nodes = []
self.segments = []
self.branches = []
self.compartments = []
self.branchOrders = None
self.tags = {'*' : 0}
# helper sets for efficient deleting
self._removeNodes = set()
self._removeSegments = set()
# keep track of which objects have had connectivity checked
self._connectivityChecked = set()
self._soma = None
self._somaBranch = None
self._axons = None
self._axonsBranch = None
self.surfaceArea = 0.0 # mm^2
self.volume = 0.0 # mm^3
self.minRange = [float('nan'), float('nan'), float('nan')]
self.maxRange = [float('nan'), float('nan'), float('nan')]
if _fileName is not None:
self.setFileName(_fileName)
self.readGeometry()
def setFileName(self, fileName):
self.path = os.path.dirname(os.path.abspath(fileName))
self.fileName = fileName
self.name = os.path.basename(fileName).split('.')[0]
def numCompartments(self):
return len(self.compartments)
def readGeometry(self):
raise RuntimeError( \
'Geometry must be a subclass that knows how to read files')
def displaySummary(self):
"""
Display summary statistics of neuron geometry
"""
print("total number of nodes: %d" % len(self.nodes))
print("total number of compartments: %d" % len(self.compartments))
print("total number of segments: %d" % len(self.segments))
subGraphs = self.checkConnectivity(removeDisconnected=True, debugInfo=True)
print("number of connected nodes: %d" % len(self.nodes))
print("number of connected compartments: %d" % len(self.compartments))
print("number of connected segments: %d" % len(self.segments))
self.findBranches()
print("number of branches: %d" % len(self.branches))
soma = self.soma
somaArea = sum(c.surfaceArea for c in soma.compartments \
if 'Soma' in c.tags)
print('Soma Area = %g mm^2' % somaArea)
print('Found %d axon%s' % (len(self._axons), 's'*(len(self._axons)!=1)))
print("volume: %g mm^3" % self.volume)
print("surface area: %s mm^2" % self.surfaceArea)
self.calcBranchOrder(doPlot=False)
self.shollAnalysis(straightenNeurites=True)
self.mergeBranchesByDistanceToEdge()
pyplot.show()
#############################################################################
def getProperties(self, passiveFile="", display=True,
makePlots=False):
def _dispListStats(L, confidence = 0.05, display=True, printName=""):
# return median, lowBound, highBound
sortedL = sorted(L)
numL = len(L)
if numL % 2:
# odd number of elements
medianInd = (numL - 1) / 2
median = sortedL[medianInd]
else:
medianInd = numL / 2
median = (sortedL[medianInd] + sortedL[medianInd - 1]) / 2.0
lowInd = int(round( 0.5 * confidence * numL ))
highInd = int(round( (1.0 - 0.5 * confidence) * numL ))
low = sortedL[lowInd] ; high = sortedL[highInd]
if display and printName:
print('%s = %.2f +%.2f -%.2f'
% (printName, median, high - median, median - low))
def _plotTraces(timeTrace, vTraces):
from scipy import array
fig = pyplot.figure()
axes = fig.add_subplot(1,1,1)
y = array(vTraces.values()).transpose()
axes.plot(timeTrace, y)
pyplot.ylabel('Membrane Potential (mV)')
pyplot.xlabel('Time (ms)')
pyplot.title('Model Response to Step Current')
pyplot.tight_layout()
from scipy.optimize import brentq, fmin
def _rallLaw(p, *ratios):
try:
return sum(r**p for r in ratios) - 1.0
except OverflowError:
return float('inf')
def _rallLawTrouble(p, *ratios):
try:
return (sum(r**p for r in ratios) - 1.0)**2
except OverflowError:
return float('inf')
def _getRallPow(parentR, daughterRs):
ratios = tuple(d / parentR for d in daughterRs)
checkPows = [-log(len(ratios)) / log(r) for r in ratios if r != 1.0]
try:
return brentq(_rallLaw, min(checkPows), max(checkPows), args=ratios)
except ValueError:
print('Rall-incompatible branch ratios: %s'
% ' '.join('%.2f' % r for r in ratios))
return fmin(_rallLawTrouble, 0.0, args=ratios, disp=False)[0]
def _overallRall(p, ratiosList):
return sum(_rallLawTrouble(p, *ratios) for ratios in ratiosList)
def _getOverallRallPow(ratiosList):
return fmin(_overallRall, 0.0, args=(ratiosList,), disp=False)[0]
# check connectivity
self.checkConnectivity(removeDisconnected=True, removeLoops=True)
self.findBranches()
if display:
print("number of connected nodes: %d" % len(self.nodes))
print("number of connected compartments: %d" % len(self.compartments))
print("number of connected segments: %d" % len(self.segments))
print("number of branches: %d" % len(self.branches))
print('Surface area = %g mm^2' % self.surfaceArea)
print('Volume = %g mm^3' % self.volume)
print('Surface to volume ratio = %g mm^-1'
% (self.surfaceArea/self.volume))
# make a path distance finder centered at the soma
pDF = PathDistanceFinder(self, self.soma)
# find all the neuron tips
tips, tipPositions = self.getTips()
# measure path lengths from Soma to tips
pathLengths = [pDF.distanceTo(tip, pos)
for tip, pos in zip(tips, tipPositions)]
_dispListStats(pathLengths, display=display,
printName='Path length from Soma to tips')
# measure tortuosities from Soma to tips
tortuosities = [pDF.tortuosityTo(tip, pos)
for tip, pos in zip(tips, tipPositions)]
_dispListStats(tortuosities, display=display,
printName='Tortuosity of path from Soma to tips')
# measure branch tortuosities
bTortuosities = [branch.tortuosity for branch in self.branches
if branch.tortuosity < float('inf')]
_dispListStats(bTortuosities, display=display,
printName='Tortuosity of neuron branches')
if self.soma.branchOrder is None:
self.calcBranchOrder(doPlot=False)
self.mergeBranchesByDistanceToEdge(makePlots=makePlots)
branchAngles = [getBranchAngle(branch, neighbor, segLoc, nLoc, node)
for branch in self.branches
for neighbor, (segLoc, nLoc, node)
in zip(branch.neighbors, branch.neighborLocations)
if neighbor.branchOrder > branch.branchOrder]
_dispListStats(branchAngles, display=display,
printName='For neuron branches, branch angle')
rallRatios = []
daughterRatios = []
rallPowers = []
ratiosList = []
for segment in self.branches:
#if segment.branchOrder < 4:
# continue
daughters = [n for n in segment.neighbors
if n.branchOrder > segment.branchOrder]
if daughters:
rallRatio = \
sum(n.avgRadius**1.5 for n in daughters) / segment.avgRadius**1.5
rallRatios.append(rallRatio)
daughterRatios.extend(n.avgRadius / segment.avgRadius
for n in daughters)
rallPowers.append(_getRallPow(segment.avgRadius,
[n.avgRadius for n in daughters]))
ratiosList.append([n.avgRadius / segment.avgRadius for n in daughters])
_dispListStats(rallRatios, display=display,
printName='For neuron branches, Rall ratio')
_dispListStats(daughterRatios, display=display,
printName='For neuron branches, daughter branch ratio')
_dispListStats(rallPowers, display=display,
printName='For neuron branches, Rall power')
properties = {
'Num Nodes' : len(self.nodes),
'Num Compartments' : len(self.compartments),
'Num Segments' : len(self.segments),
'Num Branches' : len(self.branches),
'Surface Area' : self.surfaceArea,
'Volume' : self.volume,
'Area-To-Volume Ratio' : self.surfaceArea / self.volume,
'Path Length' : pathLengths,
'Tortuosity' : tortuosities,
'Branch Tortuosity' : bTortuosities,
'Branch Angles' : branchAngles,
'Rall Ratio' : rallRatios,
'Daughter/Parent Radius' : daughterRatios,
'Overall Rall Power' : _getOverallRallPow(ratiosList)
}
units = {
'Num Nodes' : '',
'Num Compartments' : '',
'Num Segments' : '',
'Num Branches' : '',
'Surface Area' : 'mm^2',
'Volume' : 'mm^3',
'Area-To-Volume Ratio' : 'mm^-1',
'Path Length' : 'um',
'Tortuosity' : '',
'Branch Tortuosity' : '',
'Branch Angles' : 'degrees',
'Rall Ratio' : '',
'Daughter/Parent Radius' : '',
'Overall Rall Power' : ''
}
if passiveFile:
from neuron_simulateGeometry import makeModel, simulateModel
import peelLength
import json
# get the properties
with open(passiveFile, 'r') as fIn:
passiveProperties = json.load(fIn)
# make a demo model
model = makeModel(self, passiveProperties)
# simulation model on specified geometry
timeTrace, vTraces, textOutput = simulateModel(self, model)
if makePlots:
_plotTraces(timeTrace, vTraces)
somaV = max(vTraces[self.soma.name])
rIn = somaV / model['stimulus']['amplitude']
properties['Input resistance'] = rIn
units['Input resistance'] = 'MOhm'
if display:
print('Input resistance = %g MOhm' % rIn)
tipsV = [max(vTraces[segment.name]) for segment in self.segments
if 'Soma' not in segment.tags and segment.isTerminal]
tipsTransfer = [tipV / somaV for tipV in tipsV]
_dispListStats(tipsTransfer, display=display,
printName='Coupling coefficient from soma to tips')
properties['Coupling Coefficient'] = tipsTransfer
units['Coupling Coefficient'] = ''
model, vErr, vResid = \
peelLength.modelResponse(timeTrace, vTraces[self.soma.name],
verbose=False, findStepWindow=True,
plotFit=False, debugPlots=False,
displayModel=display)
tauM = model[0][0]
if display:
print('membrane tau = %6.2f ms' % tauM)
properties['Membrane Time Constant'] = tauM
units['Membrane Time Constant'] = 'ms'
if makePlots:
self.shollAnalysis()
return properties, units
def findBranches(self):
"""
Break up geometry into segments defined by branch points, starting at the
soma
"""
if self.branches:
return
self.checkConnectivity(removeDisconnected=True)
if not self._somaBranch:
self._findSoma()
somaBranch, somaNeighbors0, somaNeighbors1 = self._somaBranch
# This can cause weird errors if not fixed:
if somaBranch.neighbors:
warn('Some routine cleared self.branches without removing '
+ 'somaBranch.neighbors')
somaBranch.neighbors = []
self.branches = [somaBranch]
openBranches = [(somaBranch, 0, somaNeighbors0), \
(somaBranch, 1, somaNeighbors1)]
openCompartments = set(self.compartments).difference(
somaBranch.compartments)
while openBranches:
# check an open branch to see if it has any neighbors branching off
checkBranch, side, neighbors = openBranches.pop()
# find neighbors on specified side of checkBranch
commonNeighbors = { (checkBranch, side), }
checkNode = checkBranch.nodes[-side]
for segment, pos, compartment in neighbors:
if compartment not in openCompartments:
continue
# for each neighboring segment, find the branch it's in, based on
# compartment (ignore segment and pos)
branch, neighbors0, neighbors1 = self._getBranch(compartment)
# add that branch to geometry
self.branches.append(branch)
# remove the compartments in branch from openCompartments
openCompartments.difference_update(branch.compartments)
# add branch to dict of common neighbors, at appropriate side
# and add to openBranches with appropriate neighbors
if branch.nodes[-1] == checkNode:
if branch.nodes[0] == checkNode:
# branch is a loop with both ends connected to _check
commonNeighbors.add( (branch, 0) )
commonNeighbors.add( (branch, 1) )
else:
# side 1 of branch connects to checkBranch at checkNode
if branch.nodes[-1] != checkNode:
checkTags = ' '.join(checkBranch.tags)
checkNodeInd = self.nodes.index(checkNode)
branchTags = ' '.join(branch.tags)
branchNodes =str(tuple(self.nodes.index(n) for n in branch.nodes))
raise AssertionError(('Node mismatch. %s (with tags %s) should'
+ ' connects to %s (with tags %s) at node %d, but %s has '
+ 'nodes %s') % (checkBranch.name, checkTags, branch.name,
branchTags, checkNodeInd, branch.name,
branchNodes))
commonNeighbors.add( (branch, 1) )
# side 0 is still open
openBranches.append((branch, 0, neighbors0))
else:
# side 0 of branch connects to checkBranch at checkNode
if branch.nodes[0] != checkNode:
checkTags = ' '.join(checkBranch.tags)
checkNodeInd = self.nodes.index(checkNode)
branchTags = ' '.join(branch.tags)
branchNodes = str(tuple(self.nodes.index(n) for n in branch.nodes))
raise AssertionError(('Node mismatch. %s (with tags %s) should'
+ ' connects to %s (with tags %s) at node %d, but %s has '
+ 'nodes %s') % (checkBranch.name, checkTags, branch.name,
branchTags, checkNodeInd, branch.name,
branchNodes))
commonNeighbors.add( (branch, 0) )
# side 1 is still open
openBranches.append((branch, 1, neighbors1))
# update the neighbors of _check and all the new branches
while commonNeighbors:
n1, n1Side = commonNeighbors.pop()
for n2, n2Side in commonNeighbors:
_makeNeighbors(n1, n2, n1Side, n2Side, checkNode)
def _plotBranchStat(self, branchStat, yLabel, title, \
fontSize=22, barWidth=0.25):
### plot collected statistic along with number of branches
### branchStat should be a dictionary with:
### -each key is a branch order (an integer)
### -each item is a list of y-values (the list for all branches with
### that branch order)
order = branchStat.keys()
order.sort()
y = [branchStat[o] for o in order]
x = list(range(len(order)))
orderStr = [str(o) for o in order]
numBranches = [len(y_n) for y_n in y]
# make new figure
fig = pyplot.figure()
# plot number of branches as bar plot
ax1 = pyplot.gca()
pyplot.bar(x, numBranches, width=barWidth, color='g')
pyplot.ylabel('# branches', fontsize=fontSize)
pyplot.xlabel('Branch Order', fontsize=fontSize)
pyplot.xticks(x, orderStr)
# plot y statistics as a box and whisker plot
positions = [x_n - barWidth/2.0 for x_n in x]
ax2 = pyplot.twinx()
pyplot.boxplot(y, positions=positions, widths=barWidth)
pyplot.title(title, fontsize=fontSize)
pyplot.ylabel(yLabel, fontsize=fontSize)
pyplot.xlabel('Branch Order', fontsize=fontSize)
pyplot.xticks(x, orderStr)
# set the numBranches y-axis and labels on right, main on left
ax1.yaxis.tick_right()
ax1.yaxis.set_label_position('right')
ax2.yaxis.tick_left()
ax2.yaxis.set_label_position('left')
pyplot.tight_layout()
return fig
def _plotBranchOrderStatistics(self):
### Visualize various statistics dependent upon branch order
# collect data
branchRadius = {}
branchLength = {}
for branch in self.mergedBranches:
order = branch.centripetalOrder
if order not in branchRadius:
branchRadius[order] = [branch.maxRadius]
branchLength[order] = [branch.length]
else:
branchRadius[order].append(branch.maxRadius)
branchLength[order].append(branch.length)
self._plotBranchStat(branchRadius, \
'Radius (um)', 'Branch Order vs. Radius')
self._plotBranchStat(branchLength, \
'Length (um)', 'Branch Order vs Length')
def calcBranchOrder(self, doPlot=True):
self.calcForewardBranchOrder(doPlot=False, printAxonInfo=False)
self.calcCentripetalOrder(doPlot=doPlot, network=self.branches)
self.calcCentripetalOrder(doPlot=doPlot, network=self.segments)
def calcForewardBranchOrder(self, doPlot=True, printAxonInfo=False):
somaPos = self.soma.centroidPosition(mandateTag='Soma')
pDF = PathDistanceFinder(self, self.soma, somaPos)
for segment in self.segments:
segment.branchOrder = pDF.branchOrder(segment)
self.findBranches()
somaPos = self.somaBranch.centroidPosition(mandateTag='Soma')
pDF = PathDistanceFinder(self, self.somaBranch, somaPos)
for branch in self.branches:
branch.branchOrder = pDF.branchOrder(branch)
def calcCentripetalOrder(self, doPlot=True, network=None):
"""
Define neurite "ends" to be segments that have locally maximal branchOrder
(ends are terminal segments unless there are loops).
Label each end with centripetal order 0.
Every other segment is labeled with centripetal order equal to the length
of the longest path from an end to that segment, provided that allowable
paths ALWAYS move towards the soma.
geometry.calcCentripetalOrder() sets segment.centripetalOrder set to this
value for all segments in network
"""
if network is None or not network:
self.findBranches()
network = self.branches
def _isEnd(segment):
return all(segment.branchOrder >= n.branchOrder
for n in segment.neighbors)
ends = [segment for segment in network if _isEnd(segment)]
for segment in ends:
if 'Soma' in segment.tags:
print('FUCK')
print(segment.branchOrder)
print([n.branchOrder for n in segment.neighbors])
print(all(segment.branchOrder >= n.branchOrder
for n in segment.neighbors))
for segment in network:
segment.centripetalOrder = -1
for segment in ends:
# mark each end as having centripetal order 0
segment.centripetalOrder = 0
# now find paths from each end towards the soma. Each segment's
# centripetal order is the length of the longest path from an end to the
# segment, PROVIDED that the path ALWAYS moves towards the soma
openSegs = [segment]
while openSegs:
currentSeg = openSegs.pop()
neighborCentripOrder = currentSeg.centripetalOrder + 1
for neighbor in currentSeg.neighbors:
# look for new paths to soma, insisting that:
# 1. The path ALWAYS moves closer to soma
# 2. There isn't already a longer path through this area
if neighbor.branchOrder < currentSeg.branchOrder and \
neighbor.centripetalOrder < neighborCentripOrder:
# this is a new (good) path, so mark the centripetal order and
# continue it
neighbor.centripetalOrder = neighborCentripOrder
openSegs.append(neighbor)
def checkConnectivity(self, removeDisconnected=False, checkObjects=None,
debugInfo=True, removeLoops=False):
"""
Compute the connectivity of the network:
-The number/members of connected subgraphs
-The presence of any loops
if removeDisconnected is True, remove all but largest subgraph from network
Return the list of subgraphs
"""
if checkObjects is None:
checkObjects = self.segments
checkHash = hash(str(checkObjects)+str(removeDisconnected))
if checkHash in self._connectivityChecked:
# don't need to check again
return
# check to be sure that neighborhood at a location/node is transitive
for segment in checkObjects:
for neighbor, (pos, nPos, node) in zip(segment.neighbors,
segment.neighborLocations):
assert segment in node.segments, \
"%s should be in node %d's list of segments, but is not" \
% (segment.name, self.nodes.index(node))
assert neighbor in node.segments, \
"%s should be in node %d's list of segments, but is not" \
% (neighbor.name, self.nodes.index(node))
for n2, (pos2, nPos2, node2) in zip(neighbor.neighbors,
neighbor.neighborLocations):
if node2 != node:
continue
assert n2 == segment or n2 in segment.neighbors, \
"%s and %s are neighbors at node %d, and so are %s and %s,"\
" but %s and %s are not" % (segment.name, neighbor.name,
self.nodes.index(node), neighbor.name, n2.name,
segment.name, n2.name)
subGraphs = []
checkObjs = {obj for obj in checkObjects}
while checkObjs:
# start checking new subgraph
start = checkObjs.pop()
connected = { (start, None) }
subGraph = { start }
pathSegNames = { start : [start.name] }
paths = {start : []}
while connected:
# find all the elements connected to this subgraph
segment, startNode = connected.pop()
for neighbor, (pos, nPos, node) in zip(segment.neighbors,
segment.neighborLocations):
if node == startNode and neighbor != segment:
# this is just backtracking
continue
if neighbor in checkObjs:
connected.add((neighbor, node))
subGraph.add(neighbor)
checkObjs.remove(neighbor)
pathSegNames[neighbor] = pathSegNames[segment] + [neighbor.name]
paths[neighbor] = paths[segment] + [(segment, node, neighbor)]
else:
# there is a loop!
names1 = pathSegNames[segment]
try:
names2 = pathSegNames[neighbor]
except KeyError as err:
print(segment.name, neighbor.name, neighbor in self.segments,
neighbor in checkObjs, neighbor in subGraph,
neighbor in pathSegNames)
print([neighbor in s for s in subGraphs])
raise err
ind = 0
for name1, name2 in zip(names1, names2):
if name1 != name2:
ind -= 1
break
ind += 1
loopSegNames = names1[ind:] + names2[:ind-1:-1]
if removeLoops:
#loops.append(loopSegNames)
warn('Have not implement loop removal.\nLoop detected',
'->'.join(loopSegNames))
else:
warn('Loop detected', '->'.join(loopSegNames))
subGraphs.append(subGraph)
# sort the subgraphs so that the largest is first
if isinstance(checkObjects[0], Segment):
checkType = 'Segment'
subGraphs.sort(key=lambda x: sum([len(y.compartments) for y in x]))
elif isinstance(checkObjects[0], Compartment):
checkType = 'Compartment'
subGraphs.sort(key=lambda x: len(x))
else:
raise RuntimeError("Can't sort type: %s" % str(type(checkObjects[0])))
if debugInfo:
print('Number of subgraphs = %d / size of graphs: %s'
% (len(subGraphs), str([len(graph) for graph in subGraphs])))
if removeDisconnected and len(subGraphs) > 1:
badGraphs, subGraphs = subGraphs[:-1], subGraphs[-1]
badSegs = set()
badComps = set()
badNodes = set()
if checkType == 'Segment':
while badGraphs:
subGraph = badGraphs.pop()
# find unwanted objects in the subgraph
badSegs.update(subGraph)
for seg in subGraph:
badComps.update(seg.compartments)
badNodes.update(seg.nodes)
else:
while badGraphs:
subGraph = badGraphs.pop()
# find unwanted objects in the subgraph
badComps.update(subGraph)
for comp in subGraph:
badNodes.update(comp.nodes)
badSegs.add(comp.segment)
self.segments[:] = \
[seg for seg in self.segments if seg not in badSegs]
self.compartments[:] = \
[comp for comp in self.compartments if comp not in badComps]
self.nodes[:] = [node for node in self.nodes if node not in badNodes]
self.branches = []
if self._somaBranch is not None:
self._somaBranch[0].neighbors = []
checkHash = hash(str(checkObjects)+str(removeDisconnected))
print("Removed all but largest subgraphs")
# record that the connectivity is already checked
self._connectivityChecked.add(checkHash)
return subGraphs
def _plotShollGraph(self, distances):
"""
Plot the number of neurites at a given distance
"""
# neuriteDistance starts at zero, and has two data points for each
# distance: one with the previous (running) number of compartments, and one
# with the change added in (running +1 or -1)
runningNum = 0
neuriteDistance = [0.0]
numIntersections = [0]
lastNeuriteDistance = 0.0
for d in distances:
if d[0] > lastNeuriteDistance:
neuriteDistance.append(lastNeuriteDistance)
numIntersections.append(runningNum)
neuriteDistance.append(d[0])
numIntersections.append(runningNum)
lastNeuriteDistance = d[0]
runningNum += d[1]
neuriteDistance.append(lastNeuriteDistance)
numIntersections.append(runningNum)
fig = pyplot.figure()
pyplot.plot(neuriteDistance, numIntersections, 'k-')
pyplot.title('Sholl Analysis', fontsize=22)
pyplot.xlabel('Distance from soma', fontsize=22)
pyplot.ylabel('Number of compartments', fontsize=22)
ax = pyplot.gca()
for tick in ax.xaxis.get_major_ticks():
tick.label1.set_fontsize(16)
for tick in ax.yaxis.get_major_ticks():
tick.label1.set_fontsize(16)
pyplot.tight_layout()
def shollAnalysis(self, straightenNeurites=True):
"""
Find the number of neurites that intersect a sphere of a given radius
"""
# get the centroid of the soma, weighting each compartment's contribution
# by volume
# define how distance from centroid to compartment is measured
if straightenNeurites:
# get distance traveled along neurites (e.g. as though neuron was
# straightened out
centroid = self.soma.centroidPosition(mandateTag='Soma')
# compute distance from soma to each segment
somaPaths = PathDistanceFinder(self, self.soma, centroid)
# store results in an array
distances = []
for s in self.segments:
d0, d1 = somaPaths.distanceTo(s, 0.0), somaPaths.distanceTo(s, 1.0)
if d1 < d0:
d0, d1 = d1, d0
distances.append((d0, 1))
distances.append((d1, -1))
else:
# get euclidean distance from soma centroid to each compartment
# (must be done compartment by compartment, because segments curve)
centroid = self.soma.centroid(mandateTag='Soma')
# define distance from centroid to compartment
def _centroidDist(c):
def _tupleDist(_t1, _t2):
return sqrt( (_t1[0] - _t2[0])**2 + \
(_t1[1] - _t2[1])**2 + \
(_t1[2] - _t2[2])**2 )
d0 = _tupleDist(centroid, (c.x0, c.y0, c.z0))
d1 = _tupleDist(centroid, (c.x1, c.y1, c.z1))
if d0 <= d1:
return d0, d1