-
Notifications
You must be signed in to change notification settings - Fork 96
/
locations.py
664 lines (495 loc) · 20 KB
/
locations.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
"""Location classes"""
"""
Copyright (c) 2016-2020, EPFL/Blue Brain Project
This file is part of BluePyOpt <https://github.com/BlueBrain/BluePyOpt>
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License version 3.0 as published
by the Free Software Foundation.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
# pylint: disable=W0511
import itertools
from bluepyopt.ephys.base import BaseEPhys
from bluepyopt.ephys.serializer import DictMixin
from bluepyopt.ephys.parameterscalers import format_float
from bluepyopt.ephys.acc import ArbLabel
from bluepyopt.ephys.morphologies import ArbFileMorphology
import numpy as np
import logging
logger = logging.getLogger(__name__)
class Location(BaseEPhys):
"""Location"""
pass
# TODO make all these locations accept a cell name
# TODO instantiate should get the entire simulation environment
# TODO find better/more general name for this
# TODO specify in document abrevation comp=compartment, sec=section, ...
def _nth_isectionlist(isectionlist, index):
"""Get nth element of isectionlist
Sectionlists don't support direct indexing
"""
isection = next(
itertools.islice(
isectionlist,
index,
index + 1))
return isection
class NrnSeclistCompLocation(Location, DictMixin):
"""Compartment in a sectionlist"""
SERIALIZED_FIELDS = (
'name',
'comment',
'seclist_name',
'sec_index',
'comp_x',
)
def __init__(
self,
name,
seclist_name=None,
sec_index=None,
comp_x=None,
comment=''):
"""Constructor
Args:
name (str): name of the object
seclist_name (str): name of Neuron section list (ex: 'somatic')
sec_index (int): index of the section in the section list
comp_x (float): segx (0..1) of segment inside section
"""
super(NrnSeclistCompLocation, self).__init__(name, comment)
self.seclist_name = seclist_name
self.sec_index = sec_index
self.comp_x = comp_x
def instantiate(self, sim=None, icell=None): # pylint: disable=W0613
"""Find the instantiate compartment"""
iseclist = getattr(icell, self.seclist_name)
iseclist_size = len([x for x in iseclist])
if self.sec_index >= iseclist_size:
raise Exception(
'NrnSeclistCompLocation: section index %d falls out of '
'SectionList size of %d' %
(self.sec_index, iseclist_size))
isection = _nth_isectionlist(iseclist, self.sec_index)
icomp = isection(self.comp_x)
# The code above seems to add put a section on the stack
# TODO remove line below once we figure out where the section is pushed
sim.neuron.h.pop_section()
return icomp
def acc_label(self):
"""Arbor label"""
raise EPhysLocAccException(
'%s not supported in Arbor' % type(self).__name__ +
' (uses branches instead of NEURON sections).'
' Use ArbBranchRelLocation/ArbSegmentRelLocation/'
'ArbLocsetLocation instead (consider using the'
' Arbor GUI to identify the precise branch/segment index'
' and relative position).')
def __str__(self):
"""String representation"""
return '%s[%s](%s)' % (self.seclist_name, self.sec_index, self.comp_x)
class NrnSectionCompLocation(Location, DictMixin):
"""Compartment in a section"""
SERIALIZED_FIELDS = (
'name',
'comment',
'seclist_name',
'sec_index',
'comp_x',
)
def __init__(
self,
name,
sec_name=None,
comp_x=None,
comment=''):
"""Constructor
Args:
name (str): name of the object
sec_name (str): name of Neuron section (ex: 'soma[0]')
comp_x (float): segx (0..1) of segment inside section
"""
super(NrnSectionCompLocation, self).__init__(name, comment)
self.sec_name = sec_name
self.comp_x = comp_x
def instantiate(self, sim=None, icell=None): # pylint: disable=W0613
"""Find the instantiate compartment"""
# Dont see any other way but to use eval, apart from parsing the
# sec_name string which can be complicated
isection = eval('icell.%s' % self.sec_name) # pylint: disable=W0123
icomp = isection(self.comp_x)
return icomp
def acc_label(self):
"""Arbor label"""
raise EPhysLocAccException(
'%s not supported in Arbor' % type(self).__name__ +
' (uses branches instead of NEURON sections).'
' Use ArbBranchRelLocation/ArbSegmentRelLocation/'
'ArbLocsetLocation instead (consider using the'
' Arbor GUI to identify the precise branch/segment index'
' and relative position).')
def __str__(self):
return '%s(%s)' % (self.sec_name, self.comp_x)
class NrnPointProcessLocation(Location):
"""Point process location"""
def __init__(
self,
name,
pprocess_mech,
comment=''):
"""Constructor
Args:
name (str): name of the object
pprocess_mech (str): point process mechanism
"""
super(NrnPointProcessLocation, self).__init__(name, comment)
self.pprocess_mech = pprocess_mech
def instantiate(self, sim=None, icell=None): # pylint: disable=W0613
"""Find the instantiated point processes"""
return self.pprocess_mech.pprocesses
def acc_label(self):
"""Arbor label"""
return [loc.acc_label() for loc in self.pprocess_mech.locations]
def __str__(self):
"""String representation"""
return '%s' % (self.pprocess_mech.name)
class NrnSeclistLocation(Location, DictMixin):
"""Section in a sectionlist"""
SERIALIZED_FIELDS = ('name', 'comment', 'seclist_name', )
def __init__(
self,
name,
seclist_name=None,
comment=''):
"""Constructor
Args:
name (str): name of the object
seclist_name (str): name of NEURON section list (ex: 'somatic')
"""
super(NrnSeclistLocation, self).__init__(name, comment)
self.seclist_name = seclist_name
def instantiate(self, sim=None, icell=None): # pylint: disable=W0613
"""Find the instantiate compartment"""
isectionlist = getattr(icell, self.seclist_name)
return (isection for isection in isectionlist)
def acc_label(self):
"""Arbor label"""
return ArbFileMorphology.region_labels[self.seclist_name]
def __str__(self):
"""String representation"""
return '%s' % (self.seclist_name)
class NrnSeclistSecLocation(Location, DictMixin):
"""Section in a sectionlist"""
SERIALIZED_FIELDS = ('name', 'comment', 'seclist_name', 'sec_index', )
def __init__(
self,
name,
seclist_name=None,
sec_index=None,
comment=''):
"""Constructor
Args:
name (str): name of this object
seclist_name (str): name of Neuron section list (ex: 'somatic')
sec_index (int): index of the section
"""
super(NrnSeclistSecLocation, self).__init__(name, comment)
self.seclist_name = seclist_name
self.sec_index = sec_index
def instantiate(self, sim=None, icell=None): # pylint: disable=W0613
"""Find the instantiate compartment"""
isectionlist = getattr(icell, self.seclist_name)
isection = _nth_isectionlist(isectionlist, self.sec_index)
return isection
def acc_label(self):
"""Arbor label"""
raise EPhysLocAccException(
'%s not supported in Arbor' % type(self).__name__ +
' (uses branches instead of NEURON sections).'
' Use ArbBranchLocation/ArbSegmentLocation/ArbRegionLocation'
' instead (consider using the Arbor GUI to identify the'
' precise branch/segment index).')
def __str__(self):
"""String representation"""
return '%s[%s]' % (self.seclist_name, self.sec_index)
class NrnSomaDistanceCompLocation(Location, DictMixin):
"""Compartment at distance from soma"""
SERIALIZED_FIELDS = ('name', 'comment', 'soma_distance', 'seclist_name', )
def __init__(
self,
name,
soma_distance=None,
seclist_name=None,
comment=''):
"""Constructor
Args:
name (str): name of this object
soma_distance (float): distance from soma to this compartment
seclist_name (str): name of Neuron section list (ex: 'apical')
"""
super(NrnSomaDistanceCompLocation, self).__init__(name, comment)
self.soma_distance = soma_distance
self.seclist_name = seclist_name
# TODO this definitely has to be unit-tested
# TODO add ability to specify origin
def find_icomp(self, sim, iseclist):
"""Find the index of the compartment based on a list of isec
and a distance"""
icomp = None
for isec in iseclist:
start_distance = sim.neuron.h.distance(1, 0.0, sec=isec)
end_distance = sim.neuron.h.distance(1, 1.0, sec=isec)
min_distance = min(start_distance, end_distance)
max_distance = max(start_distance, end_distance)
if min_distance <= self.soma_distance <= max_distance:
comp_x = float(self.soma_distance - min_distance) / \
(max_distance - min_distance)
comp_diam = isec(comp_x).diam
if comp_diam > 0.0:
icomp = isec(comp_x)
if icomp is None:
raise EPhysLocInstantiateException(
'No comp found at %s distance from soma' %
self.soma_distance)
return icomp
def instantiate(self, sim=None, icell=None):
"""Find the instantiate compartment"""
soma = icell.soma[0]
sim.neuron.h.distance(0, 0.5, sec=soma)
iseclist = getattr(icell, self.seclist_name)
return self.find_icomp(sim, iseclist)
def acc_label(self):
"""Arbor label"""
# Potentially non-unique location - in that case to be refined in the
# Arbor GUI (create ArbLocsetLocation directly).
# Alternatives to (on-components 0.5 (region "soma")) are
# - '(segment <id>)'
# - '(proximal (region %s)))' % self.seclist_name
# If outer restrict results in non-unique location (cf. GUI) use
# specific branch or similar instead of seclist_name, e.g.
# - (proximal-interval (distal (branch <id>)))
# for a branch distally from the desired location
acc_label = ArbLabel(
'locset', self.name,
'(restrict (distal-translate (on-components 0.5 %s) %s) %s)' %
(ArbFileMorphology.region_labels['somatic'].ref,
format_float(self.soma_distance),
ArbFileMorphology.region_labels[self.seclist_name].ref))
logger.warning(
'Make sure that ACC label %s' % acc_label.loc +
' for NrnSomaDistanceCompLocation (%s) ' % str(self) +
' instantiates to a unique location on the morphology.'
' Use the Arbor GUI to validate/refine the location expression.')
return acc_label
def __str__(self):
"""String representation"""
return '%f micron from soma in %s' % (
self.soma_distance, self.seclist_name)
class NrnSecSomaDistanceCompLocation(NrnSomaDistanceCompLocation):
"""Compartment on a section defined both by a section index and distance
from the soma """
SERIALIZED_FIELDS = ('name', 'comment', 'soma_distance', 'seclist_name',
'sec_index', )
def __init__(
self,
name,
soma_distance=None,
sec_index=None,
seclist_name=None,
comment=""
):
"""Constructor
Args:
name (str): name of this object
soma_distance (float): distance from soma to this compartment
sec_index (int): index of the section to consider
seclist_name (str): name of Neuron sections (ex: 'apic')
"""
super(NrnSecSomaDistanceCompLocation, self).__init__(
name,
soma_distance=soma_distance,
seclist_name=seclist_name,
comment=comment,
)
self.sec_index = sec_index
def instantiate(self, sim=None, icell=None):
"""Find the instantiate compartment"""
if self.sec_index is None:
raise EPhysLocInstantiateException(
"No apical point was given")
sections = getattr(icell, self.seclist_name)
section = _nth_isectionlist(sections, self.sec_index)
branches = []
while True:
name = str(section.name()).split(".")[-1]
if name == "soma[0]":
break
branches.append(section)
if sim.neuron.h.SectionRef(sec=section).has_parent():
section = sim.neuron.h.SectionRef(sec=section).parent
else:
raise EPhysLocInstantiateException(
"soma[0] was not reached from isec point "
"%f" % self.sec_index
)
soma = icell.soma[0]
sim.neuron.h.distance(0, 0.5, sec=soma)
return self.find_icomp(sim, branches)
def acc_label(self):
"""Arbor label"""
raise EPhysLocAccException('%s not supported in Arbor.' %
type(self).__name__)
class NrnTrunkSomaDistanceCompLocation(NrnSecSomaDistanceCompLocation):
"""Location at a distance from soma along a main direction.
We search for the section that is the furthest away from some along
a direction, and pick a location at a given distance from soma along
the path to that section.
If direction == 'radial', the largest radial direction is used.
This is most useful to follow the trunk of an apical dendrite
without knowing the apical point, but only that apical trunk goes along y.
"""
def __init__(
self,
name,
soma_distance=None,
sec_index=None,
seclist_name=None,
direction=None,
comment=""
):
"""Constructor
Args:
name (str): name of this object
soma_distance (float): distance from soma to this compartment
sec_index (int): index of the section to consider
sec_name (str): name of Neuron sections (ex: 'apic')
direction (list of 3 elements): 3d vector representing direction,
if None, default is [0, 1, 0]
"""
super(NrnTrunkSomaDistanceCompLocation, self).__init__(
name,
soma_distance=soma_distance,
sec_index=sec_index,
seclist_name=seclist_name,
comment=comment
)
if direction is None:
direction = [0.0, 1.0, 0.0]
self.direction = direction
def set_sec_index(self, icell=None):
"""Search for the point furthest away along given direction."""
points = np.array(
[
[
section.x3d(section.n3d() - 1),
section.y3d(section.n3d() - 1),
section.z3d(section.n3d() - 1),
]
for section in getattr(icell, self.seclist_name)
]
)
if len(points) > 0:
if self.direction == 'radial':
self.sec_index = int(np.argmax(np.linalg.norm(points, axis=1)))
else:
self.sec_index = int(np.argmax(points.dot(self.direction)))
else:
raise EPhysLocInstantiateException(
"Empty seclist: %s" % self.seclist_name
)
def instantiate(self, sim=None, icell=None):
""" """
if self.sec_index is None:
self.set_sec_index(icell=icell)
return super().instantiate(sim=sim, icell=icell)
def acc_label(self):
"""Arbor label"""
raise EPhysLocAccException('%s not supported in Arbor.' %
type(self).__name__)
class ArbLocation(Location):
"""Arbor Location"""
def instantiate(self, sim=None, icell=None): # pylint: disable=W0613
"""Find the instantiate compartment (default implementation)"""
raise EPhysLocInstantiateException(
'%s not supported in NEURON.' % type(self).__name__)
def __str__(self):
"""String representation"""
return '%s \'%s\'' % (type(self).__name__, self.acc_label().defn)
class ArbSegmentLocation(ArbLocation):
"""Segment in an Arbor morphology.
"""
def __init__(self, name, segment, comment=''):
super().__init__(name, comment)
self.segment = segment
def acc_label(self):
"""Arbor label"""
return ArbLabel('region', self.name, '(segment %s)' % (self.segment))
class ArbBranchLocation(ArbLocation):
"""Branch in an Arbor morphology.
Arbor's counterpart of NrnSeclistSecLocation.
"""
def __init__(self, name, branch, comment=''):
super().__init__(name, comment)
self.branch = branch
def acc_label(self):
"""Arbor label"""
return ArbLabel('region', self.name, '(branch %s)' % (self.branch))
class ArbSegmentRelLocation(ArbLocation):
"""Relative position on a segment in an Arbor morphology.
"""
def __init__(self, name, segment, pos, comment=''):
super().__init__(name, comment)
self.segment = segment
self.pos = pos
def acc_label(self):
"""Arbor label"""
return ArbLabel('locset', self.name,
'(on-components %s (segment %s))' %
(format_float(self.pos), self.segment))
class ArbBranchRelLocation(ArbLocation):
"""Relative position on a branch in an Arbor morphology.
Arbor's counterpart of NrnSeclistCompLocation.
"""
def __init__(self, name, branch, pos, comment=''):
super().__init__(name, comment)
self.branch = branch
self.pos = pos
def acc_label(self):
"""Arbor label"""
return ArbLabel('locset', self.name,
'(location %s %s)' %
(self.branch, format_float(self.pos)))
class ArbLocsetLocation(ArbLocation):
"""Arbor location set defined by a user-supplied string (S-expression).
"""
def __init__(self, name, locset, comment=''):
super().__init__(name, comment)
self.locset = locset
def acc_label(self):
"""Arbor label"""
return ArbLabel('locset', self.name, self.locset)
class ArbRegionLocation(ArbLocation):
"""Arbor region defined by a user-supplied string (S-expression).
"""
def __init__(self, name, region, comment=''):
super().__init__(name, comment)
self.region = region
def acc_label(self):
"""Arbor label"""
return ArbLabel('region', self.name, self.region)
class EPhysLocInstantiateException(Exception):
"""All exceptions generated by location instantiation"""
def __init__(self, message):
"""Constructor"""
super(EPhysLocInstantiateException, self).__init__(message)
class EPhysLocAccException(Exception):
"""All exceptions generated by ACC label creation"""
def __init__(self, message):
"""Constructor"""
super(EPhysLocAccException, self).__init__(message)