Debian Codegraph @

brian2/spatialneuron/morphology.py

raw
1 """
2 Neuronal morphology module.
3 This module defines classes to load and build neuronal morphologies.
4 """
5
6 import abc
7 import numbers
8 import os
9 from abc import abstractmethod
10 from collections import OrderedDict, defaultdict, namedtuple
11
12 from brian2 import numpy as np
13 from brian2.units.allunits import meter
14 from brian2.units.fundamentalunits import Quantity, check_units, have_same_dimensions
15 from brian2.units.stdunits import um
16 from brian2.utils.logger import get_logger
17
18 logger = get_logger(__name__)
19
20 __all__ = ["Morphology", "Section", "Cylinder", "Soma"]
21
22
23 Node = namedtuple("Node", field_names="index,comp_name,x,y,z,diameter,parent,children")
24
25
26 def _to_meters(value):
27 """
28 Helper function to convert a floating point value (or array) to a `Quantity`
29 in units of "meter", but also allow for ``None`` and return it as it is.
30 """
31 if value is None:
32 return None
33 else:
34 return Quantity(value, dim=meter.dim)
35
36
37 def _from_morphology(variable, i, j):
38 """
39 Helper function to return coordinates from a main morphology (used by
40 `SubMorphology`), dealing with ``None``.
41 """
42 if variable is None:
43 return None
44 return variable[i:j]
45
46
47 class MorphologyIndexWrapper:
48 """
49 A simpler version of `~brian2.groups.group.IndexWrapper`, not allowing for
50 string indexing (`Morphology` is not a `Group`). It allows to use
51 ``morphology.indices[...]`` instead of ``morphology[...]._indices()``.
52 """
53
54 def __init__(self, morphology):
55 self.morphology = morphology
56
57 def __getitem__(self, item):
58 if isinstance(item, str):
59 raise NotImplementedError("Morphologies do not support string indexing")
60 assert isinstance(self.morphology, (SubMorphology, Morphology))
61 return self.morphology._indices(item)
62
63
64 def _calc_start_idx(section):
65 """
66 Calculate the absolute start index that will be used by a flattened
67 representation.
68 """
69 # calculate the absolute start index of this section
70 # 1. find the root of the tree
71 root = section
72 while root._parent is not None:
73 root = root._parent
74 # 2. go down from the root and advance the indices until we find
75 # the current section
76 start_idx, found = _find_start_index(root, section)
77 assert found
78 return start_idx
79
80
81 def _find_start_index(current, target_section, index=0):
82 if current == target_section:
83 return index, True
84 index += current.n
85 for child in current.children:
86 if child == target_section:
87 return index, True
88 else:
89 index, found = _find_start_index(child, target_section, index)
90 if found:
91 return index, True
92 return index, False
93
94
95 class Topology:
96 """
97 A representation of the topology of a `Morphology`. Has a useful string
98 representation, inspired by NEURON's ``topology`` function.
99 """
100
101 def __init__(self, morphology):
102 self.morphology = morphology
103
104 def __str__(self):
105 # TODO: Make sure that the shown compartments do not get out of hand
106 divisor = 1
107 return Topology._str_topology(self.morphology, compartments_divisor=divisor)
108
109 @staticmethod
110 def _str_topology(
111 morphology, indent=0, named_path="", compartments_divisor=1, parent=None
112 ):
113 """
114 A simple string-based representation of a morphology. Inspired by
115 NEURON's ``topology`` function.
116 """
117 description = " " * indent
118 length = max([1, morphology.n // compartments_divisor])
119 if parent is not None:
120 description += "`"
121 if isinstance(morphology, Soma):
122 description += "( )"
123 else:
124 description += "-" * length
125 description += "|"
126 if len(named_path) == 0:
127 description += " [root] \n"
128 else:
129 description += f" {named_path}\n"
130 for child in morphology.children:
131 name = morphology.children.name(child)
132 description += Topology._str_topology(
133 child,
134 indent=indent + 2 + length,
135 named_path=f"{named_path}.{name}",
136 compartments_divisor=compartments_divisor,
137 parent=morphology,
138 )
139 return description
140
141 __repr__ = __str__
142
143
144 def _rotate(vec, axis, angle):
145 """
146 Rotate a vector around an arbitrary axis.
147
148 Parameters
149 ----------
150 vec : `ndarray`
151 The vector to rotate.
152 axis : `ndarray`
153 The axis around which the vector should be rotated.
154 angle : float
155 The rotation angle (in radians).
156
157 Returns
158 -------
159 rotated : `ndarray`
160 The rotated vector.
161 """
162 return (
163 vec * np.cos(angle)
164 - np.cross(axis, vec) * np.sin(angle)
165 + axis * np.dot(axis, vec) * (1 - np.cos(angle))
166 )
167
168
169 def _perturb(vec, sigma):
170 if sigma == 0:
171 return vec
172 # Get an arbitrary orthogonal vector
173 if vec[1] != 0 or vec[0] != 0:
174 orthogonal = np.hstack([vec[1], vec[0], 0])
175 else: # special case for the [0, 0, 1] vector
176 orthogonal = np.array([1, 0, 0])
177
178 # Rotate the orthogonal vector
179 orthogonal = _rotate(orthogonal, vec, np.random.rand() * np.pi * 2)
180
181 # Use an exponentially distributed angle for the perturbation
182 perturbation = np.random.exponential(sigma, 1)
183 return _rotate(vec, orthogonal, perturbation)
184
185
186 def _add_coordinates(
187 orig_morphology,
188 root=None,
189 parent=None,
190 name=None,
191 section_randomness=0.0,
192 compartment_randomness=0.0,
193 n_th_child=0,
194 total_children=0,
195 overwrite_existing=False,
196 ):
197 # Note that in the following, all values are without physical units
198
199 # The new direction is based on the direction of the parent section
200 if parent is None:
201 section_dir = np.array([0, 0, 0])
202 else:
203 section_dir = np.hstack(
204 [
205 np.asarray(parent.end_x[-1] - parent.start_x[0]),
206 np.asarray(parent.end_y[-1] - parent.start_y[0]),
207 np.asarray(parent.end_z[-1] - parent.start_z[0]),
208 ]
209 )
210 parent_dir_norm = np.sqrt(np.sum(section_dir**2))
211 if parent_dir_norm != 0:
212 section_dir /= parent_dir_norm
213 else:
214 section_dir = np.array([0, 0, 0])
215 if not overwrite_existing and orig_morphology.x is not None:
216 section = orig_morphology.copy_section()
217 elif isinstance(orig_morphology, Soma):
218 # No perturbation for the soma
219 section = Soma(
220 diameter=orig_morphology.diameter,
221 x=section_dir[0] * meter,
222 y=section_dir[1] * meter,
223 z=section_dir[2] * meter,
224 )
225 else:
226 if np.sum(section_dir**2) == 0:
227 # We don't have any direction to base this section on (most common
228 # case is that the root section is a soma)
229 # We stay in the x-y plane and distribute all children in a 360 degree
230 # circle around (0, 0, 0)
231 section_dir = np.array([1, 0, 0])
232 rotation_axis = np.array([0, 0, 1])
233 angle_increment = 2 * np.pi / total_children
234 rotation_angle = np.pi / 2 + angle_increment * n_th_child
235 section_dir = _rotate(section_dir, rotation_axis, rotation_angle)
236 else:
237 if (
238 section_randomness == 0 and section_dir[2] == 0
239 ): # If we are in the x-y plane, stay there
240 rotation_axis = np.array([0, 0, 1])
241 else:
242 rotation_axis = np.array([-section_dir[1], section_dir[2], 0])
243 if section_randomness == 0:
244 angle_increment = np.pi / (total_children + 1)
245 rotation_angle = -np.pi / 2 + angle_increment * (n_th_child + 1)
246 section_dir = _rotate(section_dir, rotation_axis, rotation_angle)
247 if section_randomness > 0:
248 # Rotate randomly
249 section_dir = _perturb(section_dir, section_randomness)
250
251 section_dir_norm = np.sqrt(np.sum(section_dir**2))
252 section_dir /= section_dir_norm
253
254 # For a soma, we let child sections begin at the surface of the sphere
255 if isinstance(parent, Soma):
256 origin = parent.diameter / 2 * section_dir
257 else:
258 origin = (0, 0, 0) * um
259 coordinates = np.zeros((orig_morphology.n + 1, 3)) * meter
260 start_coords = origin
261 coordinates[0, :] = origin
262 # Perturb individual compartments as well
263 for idx, length in enumerate(orig_morphology.length):
264 compartment_dir = _perturb(section_dir, compartment_randomness)
265 compartment_dir_norm = np.sqrt(np.sum(compartment_dir**2))
266 compartment_dir /= compartment_dir_norm
267 current_coords = start_coords + length * compartment_dir
268 coordinates[idx + 1, :] = current_coords
269 start_coords = current_coords
270
271 if isinstance(orig_morphology, Cylinder) and compartment_randomness == 0:
272 section = Cylinder(
273 n=orig_morphology.n,
274 diameter=orig_morphology.diameter[0],
275 x=coordinates[[0, -1], 0],
276 y=coordinates[[0, -1], 1],
277 z=coordinates[[0, -1], 2],
278 type=orig_morphology.type,
279 )
280 elif isinstance(orig_morphology, Section):
281 section = Section(
282 n=orig_morphology.n,
283 diameter=np.hstack(
284 [orig_morphology.start_diameter[0], orig_morphology.end_diameter]
285 )
286 * meter,
287 x=coordinates[:, 0],
288 y=coordinates[:, 1],
289 z=coordinates[:, 2],
290 type=orig_morphology.type,
291 )
292 else:
293 raise NotImplementedError(
294 f"Do not know how to deal with section of type {type(orig_morphology)}."
295 )
296 if parent is None:
297 root = section
298 else:
299 parent.children.add(name, section)
300
301 for idx, child in enumerate(orig_morphology.children):
302 _add_coordinates(
303 child,
304 root=root,
305 parent=section,
306 name=orig_morphology.children.name(child),
307 n_th_child=idx,
308 total_children=len(orig_morphology.children),
309 section_randomness=section_randomness,
310 compartment_randomness=compartment_randomness,
311 overwrite_existing=overwrite_existing,
312 )
313 return section
314
315
316 class Children:
317 """
318 Helper class to represent the children (sub trees) of a section. Can be
319 used like a dictionary (mapping names to `Morphology` objects), but iterates
320 over the values (sub trees) instead of over the keys (names).
321 """
322
323 def __init__(self, owner):
324 self._owner = owner
325 self._counter = 0
326 self._children = []
327 self._named_children = {}
328 self._given_name = defaultdict(lambda: None)
329
330 def __iter__(self):
331 return iter(self._children)
332
333 def __len__(self):
334 return len(self._children)
335
336 def __contains__(self, item):
337 return item in self._named_children
338
339 def name(self, child):
340 """
341 Return the given name (i.e. not the automatic name such as ``1``) for a
342 child subtree.
343
344 Parameters
345 ----------
346 child : `Morphology`
347
348 Returns
349 -------
350 name : str
351 The given name for the ``child``.
352 """
353 return self._given_name[child]
354
355 def __getitem__(self, item):
356 if isinstance(item, str):
357 return self._named_children[item]
358 else:
359 raise TypeError("Index has to be an integer or a string.")
360
361 def add(self, name, subtree, automatic_name=False):
362 """
363 Add a new child to the morphology.
364
365 Parameters
366 ----------
367 name : str
368 The name (e.g. ``"axon"``, ``"soma"``) to use for this sub tree.
369 subtree : `Morphology`
370 The subtree to link as a child.
371 automatic_name : bool, optional
372 Whether to chose a new name automatically, if a subtree of the same
373 name already exists (uses e.g. ``"dend2"`` instead ``"dend"``).
374 Defaults to ``False`` and will raise an error instead.
375 """
376 if name in self._named_children and self._named_children[name] is not subtree:
377 if automatic_name:
378 basename = name
379 counter = 1
380 while name in self._named_children:
381 counter += 1
382 name = basename + str(counter)
383 else:
384 raise AttributeError(f"The name {name} is already used for a subtree.")
385
386 if subtree not in self._children:
387 self._counter += 1
388 self._children.append(subtree)
389 self._named_children[str(self._counter)] = subtree
390 self._given_name[subtree] = name
391
392 if name is not None:
393 self._named_children[name] = subtree
394
395 subtree._parent = self._owner
396
397 def remove(self, name):
398 """
399 Remove a subtree from this morphology.
400
401 Parameters
402 ----------
403 name : str
404 The name of the sub tree to remove.
405 """
406 if name not in self:
407 raise AttributeError(f"The subtree {name} does not exist")
408 subtree = self._named_children[name]
409 del self._named_children[name]
410 self._children.remove(subtree)
411 subtree._parent = None
412
413 def __repr__(self):
414 n = len(self._children)
415 s = f"<{int(n)} children"
416 if n > 0:
417 name_dict = {self.name(sec): sec for sec in self._children}
418 s += f": {name_dict!r}"
419 return f"{s}>"
420
421
422 class Morphology(metaclass=abc.ABCMeta):
423 """
424 Neuronal morphology (tree structure).
425
426 The data structure is a tree where each node is an un-branched section
427 consisting of a number of connected compartments, each one defined by its
428 geometrical properties (length, area, diameter, position).
429
430 Notes
431 -----
432 You cannot create objects of this class, create a `Soma`, a `Section`, or
433 a `Cylinder` instead.
434 """
435
436 @check_units(n=1)
437 def __init__(self, n, type=None):
438 if isinstance(n, str):
439 raise TypeError(
440 "Need the number of compartments, not a string. "
441 "If you want to load a morphology from a file, "
442 "use 'Morphology.from_file' instead."
443 )
444 self._n = int(n)
445 if self._n != n:
446 raise TypeError("The number of compartments n has to be an integer value.")
447 if n <= 0:
448 raise ValueError("The number of compartments n has to be at least 1.")
449 self.type = type
450 self._children = Children(self)
451 self._parent = None
452 self.indices = MorphologyIndexWrapper(self)
453
454 def __getitem__(self, item):
455 """
456 Return the subtree with the given name/index.
457
458 Ex.: ```neuron['axon']``` or ```neuron['11213']```
459 ```neuron[10*um:20*um]``` returns the subbranch from 10 um to 20 um.
460 ```neuron[10*um]``` returns one compartment.
461 ```neuron[5]``` returns compartment number 5.
462 """
463 if isinstance(item, slice): # neuron[10*um:20*um] or neuron[1:3]
464 using_lengths = all(
465 [
466 arg is None or have_same_dimensions(arg, meter)
467 for arg in [item.start, item.stop]
468 ]
469 )
470 using_ints = all(
471 [
472 arg is None or int(arg) == float(arg)
473 for arg in [item.start, item.stop]
474 ]
475 )
476 if not (using_lengths or using_ints):
477 raise TypeError("Index slice has to use lengths or integers")
478
479 if using_lengths:
480 if item.step is not None:
481 raise TypeError(
482 "Cannot provide a step argument when slicing with lengths"
483 )
484 pos = np.cumsum(np.asarray(self.length)) # coordinate on the section
485 # We use a special handling for values very close to the points
486 # between the compartments to avoid non-intuitive rounding
487 # effects: a point closer than 1e-12*length of section will be
488 # considered to be within the following section (for a start
489 # index), respectively within the previous section (for an end
490 # index)
491 if item.start is None:
492 i = 0
493 else:
494 diff = np.abs(float(item.start) - pos)
495 if min(diff) < 1e-12 * pos[-1]:
496 i = np.argmin(diff) + 1
497 else:
498 i = np.searchsorted(pos, item.start)
499 if item.stop is None:
500 j = len(pos)
501 else:
502 diff = np.abs(float(item.stop) - pos)
503 if min(diff) < 1e-12 * pos[-1]:
504 j = np.argmin(diff) + 1
505 else:
506 j = np.searchsorted(pos, item.stop) + 1
507 else: # integers
508 i, j, step = item.indices(self.n)
509 if step != 1:
510 raise TypeError("Can only slice a contiguous segment")
511 elif isinstance(item, Quantity) and have_same_dimensions(item, meter):
512 pos = np.hstack(
513 [0, np.cumsum(np.asarray(self.length))]
514 ) # coordinate on the section
515 if float(item) < 0 or float(item) > (1 + 1e-12) * pos[-1]:
516 raise IndexError(
517 f"Invalid index {item}, has to be in the interval "
518 f"[{0 * meter!s}, {pos[-1] * meter!s}]."
519 )
520 diff = np.abs(float(item) - pos)
521 if min(diff) < 1e-12 * pos[-1]:
522 i = np.argmin(diff)
523 else:
524 i = np.searchsorted(pos, item) - 1
525 j = i + 1
526 elif isinstance(item, numbers.Integral): # int: returns one compartment
527 if item < 0: # allows e.g. to use -1 to get the last compartment
528 item += self.n
529 if item >= self.n:
530 raise IndexError(f"Invalid index {item} for {self.n} compartments")
531 i = item
532 j = i + 1
533 elif isinstance(item, str):
534 item = str(item) # convert int to string
535 if (len(item) > 1) and all(
536 [c in "LR123456789" for c in item]
537 ): # binary string of the form LLLRLR or 1213 (or mixed)
538 return self._children[item[0]][item[1:]]
539 elif item in self._children:
540 return self._children[item]
541 else:
542 raise AttributeError(f"The subtree {item} does not exist")
543 else:
544 raise TypeError(f"Index of type {type(item)} not understood")
545
546 return SubMorphology(self, i, j)
547
548 def __setitem__(self, item, child):
549 """
550 Inserts the subtree and name it ``item``.
551 Ex.: ``neuron['axon']`` or ``neuron['11213']``
552 """
553 item = str(item) # convert int to string
554 if (len(item) > 1) and all([c in "LR123456789" for c in item]):
555 # binary string of the form LLLRLR or 1213 (or mixed)
556 self.children[item[0]][item[1:]] = child
557 else:
558 self.children.add(item, child)
559
560 def __delitem__(self, item):
561 """
562 Remove the subtree ``item``.
563 """
564 item = str(item) # convert int to string
565 if (len(item) > 1) and all([c in "LR123456789" for c in item]):
566 # binary string of the form LLLRLR or 1213 (or mixed)
567 del self._children[item[0]][item[1:]]
568 else:
569 self._children.remove(item)
570
571 def __getattr__(self, item):
572 """
573 Return the subtree named ``item``.
574
575 Ex.: ``axon = neuron.axon``
576 """
577 if item.startswith("_"):
578 return super(object, self).__getattr__(item)
579 else:
580 return self[item]
581
582 def __setattr__(self, item, child):
583 """
584 Attach a subtree and name it ``item``.
585
586 Ex.: ``neuron.axon = Soma(diameter=10*um)``
587 """
588 if isinstance(child, Morphology) and not item.startswith("_"):
589 self[item] = child
590 else: # If it is not a subtree, then it's a normal class attribute
591 object.__setattr__(self, item, child)
592
593 def __delattr__(self, item):
594 """
595 Remove the subtree ``item``.
596 """
597 del self[item]
598
599 def _indices(self, item=None, index_var="_idx"):
600 """
601 Return compartment indices for the main section, relative to the
602 original morphology.
603 """
604 if index_var != "_idx":
605 raise AssertionError(f"Unexpected index {index_var}")
606 if not (item is None or item == slice(None)):
607 if isinstance(item, slice):
608 # So that this always returns an array of values, even if it is
609 # just a single value
610 return self[item]._indices(slice(None))
611 else:
612 return self[item]._indices(None)
613 else:
614 start_idx = _calc_start_idx(self)
615 if self.n == 1 and item is None:
616 return start_idx
617 else:
618 return np.arange(start_idx, start_idx + self.n)
619
620 def topology(self):
621 """
622 Return a representation of the topology
623
624 Returns
625 -------
626 topology : `Topology`
627 An object representing the topology (can be converted to a string
628 by using ``str(...)`` or simply by printing it with `print`.)
629 """
630 return Topology(self)
631
632 def generate_coordinates(
633 self,
634 section_randomness=0.0,
635 compartment_randomness=0.0,
636 overwrite_existing=False,
637 ):
638 r"""
639 Create a new `Morphology`, with coordinates filled in place where the
640 previous morphology did not have any. This is mostly useful for
641 plotting a morphology, it does not affect its electrical properties.
642
643 Parameters
644 ----------
645 section_randomness : float, optional
646 The randomness when deciding the direction vector for each new
647 section. The given number is the :math:`\beta` parameter of an
648 exponential distribution (in degrees) which will be used to
649 determine the deviation from the direction of the parent section.
650 If the given value equals 0 (the default), then a deterministic
651 algorithm will be used instead.
652 compartment_randomness : float, optional
653 The randomness when deciding the direction vector for each
654 compartment within a section. The given number is the :math:`\beta`
655 parameter of an exponential distribution (in degrees) which will be
656 used to determine the deviation from the main direction of the
657 current section. If the given value equals 0 (the default), then all
658 compartments will be along a straight line.
659 overwrite_existing : bool, optional
660 Whether to overwrite existing coordinates in the morphology. This
661 is by default set to ``False``, meaning that only sections that do
662 not currently have any coordinates set will get new coordinates.
663 This allows to conveniently generate a morphology that can be
664 plotted for a morphology that is based on points but also has
665 artificially added sections (the most common case: an axon added
666 to a reconstructed morphology). If set to ``True``, all sections
667 will get new coordinates. This can be useful to either get a
668 schematic representation of the morphology (with
669 ``section_randomness`` and ``compartment_randomness`` both 0) or to
670 simply generate a new random variation of a morphology (which will
671 still be electrically equivalent, of course).
672
673 Returns
674 -------
675 morpho_with_coordinates : `Morphology`
676 The same morphology, but with coordinates
677 """
678 # Convert to radians
679 section_randomness *= np.pi / 180
680 compartment_randomness *= np.pi / 180
681 return _add_coordinates(
682 self,
683 section_randomness=section_randomness,
684 compartment_randomness=compartment_randomness,
685 overwrite_existing=overwrite_existing,
686 )
687
688 @abstractmethod
689 def copy_section(self):
690 """
691 Create a copy of the current section (attributes of this section only,
692 not re-creating the parent/children relation)
693
694 Returns
695 -------
696 copy : `Morphology`
697 A copy of this section (without the links to the parent/children)
698 """
699 raise NotImplementedError()
700
701 @property
702 def n(self):
703 """
704 The number of compartments in this section.
705 """
706 return self._n
707
708 def __len__(self):
709 """
710 This is not well-defined, use `Morphology.n` or
711 `Morphology.total_compartments` instead.
712 """
713 raise TypeError(
714 "The 'length' of a Morphology is ambiguous, use its "
715 "'n' attribute for the number of compartments in this "
716 "section or the 'total_compartments' attribute for the "
717 "total number of compartments in the whole sub-tree."
718 )
719
720 @property
721 def total_compartments(self):
722 """
723 The total number of compartments in this subtree (i.e. the number of
724 compartments in this section plus all the compartments in the sections
725 deeper in the tree).
726 """
727 return self.n + sum(c.total_compartments for c in self.children)
728
729 @property
730 def total_sections(self):
731 """
732 The total number of sections in this subtree.
733 """
734 return 1 + sum(c.total_sections for c in self.children)
735
736 @property
737 def parent(self):
738 """
739 The parent section of this section.
740 """
741 return self._parent
742
743 @property
744 def children(self):
745 """
746 The children (as a `Children` object) of this section.
747 """
748 return self._children
749
750 @property
751 @abc.abstractmethod
752 def end_distance(self):
753 """
754 The distance to the root of the morphology at the end of this section.
755 """
756 raise NotImplementedError()
757
758 # Per-compartment attributes
759 @property
760 @abc.abstractmethod
761 def area(self):
762 """
763 The membrane surface area of each compartment in this section.
764 """
765 raise NotImplementedError()
766
767 @property
768 @abc.abstractmethod
769 def volume(self):
770 """
771 The volume of each compartment in this section.
772 """
773 raise NotImplementedError()
774
775 @property
776 @abc.abstractmethod
777 def length(self):
778 """
779 The length of each compartment in this section.
780 """
781 raise NotImplementedError()
782
783 @property
784 @abc.abstractmethod
785 def r_length_1(self):
786 """
787 The geometry-dependent term to calculate the conductance between the
788 start and the midpoint of each compartment. Dividing this value by the
789 Intracellular resistivity gives the conductance.
790 """
791 raise NotImplementedError()
792
793 @property
794 @abc.abstractmethod
795 def r_length_2(self):
796 """
797 The geometry-dependent term to calculate the conductance between the
798 midpoint and the end of each compartment. Dividing this value by the
799 Intracellular resistivity gives the conductance.
800 """
801 raise NotImplementedError()
802
803 # At-midpoint attributes
804 @property
805 @abc.abstractmethod
806 def diameter(self):
807 """
808 The diameter at the middle of each compartment in this section.
809 """
810 raise NotImplementedError()
811
812 @property
813 @abc.abstractmethod
814 def distance(self):
815 """
816 The total distance between the midpoint of each compartment and the root
817 of the morphology.
818 """
819 raise NotImplementedError()
820
821 @property
822 def start_x(self):
823 """
824 The x coordinate at the beginning of each compartment. Returns ``None``
825 for morphologies without coordinates.
826 """
827 return _to_meters(self.start_x_)
828
829 @property
830 def start_y(self):
831 """
832 The y coordinate at the beginning of each compartment. Returns ``None``
833 for morphologies without coordinates.
834 """
835 return _to_meters(self.start_y_)
836
837 @property
838 def start_z(self):
839 """
840 The z coordinate at the beginning of each compartment. Returns ``None``
841 for morphologies without coordinates.
842 """
843 return _to_meters(self.start_z_)
844
845 @property
846 @abc.abstractmethod
847 def start_x_(self):
848 """
849 The x coordinate (as a unitless floating point number) at the beginning
850 of each compartment. Returns ``None`` for morphologies without
851 coordinates.
852 """
853 raise NotImplementedError()
854
855 @property
856 @abc.abstractmethod
857 def start_y_(self):
858 """
859 The y coordinate (as a unitless floating point number) at the beginning
860 of each compartment. Returns ``None`` for morphologies without
861 coordinates.
862 """
863 raise NotImplementedError()
864
865 @property
866 @abc.abstractmethod
867 def start_z_(self):
868 """
869 The z coordinate (as a unitless floating point number) at the beginning
870 of each compartment. Returns ``None`` for morphologies without
871 coordinates.
872 """
873 raise NotImplementedError()
874
875 @property
876 def x(self):
877 """
878 The x coordinate at the midpoint of each compartment. Returns ``None``
879 for morphologies without coordinates.
880 """
881 return _to_meters(self.x_)
882
883 @property
884 def y(self):
885 """
886 The y coordinate at the midpoint of each compartment. Returns ``None``
887 for morphologies without coordinates.
888 """
889 return _to_meters(self.y_)
890
891 @property
892 def z(self):
893 """
894 The y coordinate at the midpoint of each compartment. Returns ``None``
895 for morphologies without coordinates.
896 """
897 return _to_meters(self.z_)
898
899 @property
900 @abc.abstractmethod
901 def x_(self):
902 """
903 The x coordinate (as a unitless floating point number) at the midpoint
904 of each compartment. Returns ``None`` for morphologies without
905 coordinates.
906 """
907 raise NotImplementedError()
908
909 @property
910 @abc.abstractmethod
911 def y_(self):
912 """
913 The y coordinate (as a unitless floating point number) at the midpoint
914 of each compartment. Returns ``None`` for morphologies without
915 coordinates.
916 """
917 raise NotImplementedError()
918
919 @property
920 @abc.abstractmethod
921 def z_(self):
922 """
923 The z coordinate (as a unitless floating point number) at the midpoint
924 of each compartment. Returns ``None`` for morphologies without
925 coordinates.
926 """
927 raise NotImplementedError()
928
929 @property
930 def end_x(self):
931 """
932 The x coordinate at the end of each compartment. Returns ``None``
933 for morphologies without coordinates.
934 """
935 return _to_meters(self.end_x_)
936
937 @property
938 def end_y(self):
939 """
940 The y coordinate at the end of each compartment. Returns ``None``
941 for morphologies without coordinates.
942 """
943 return _to_meters(self.end_y_)
944
945 @property
946 def end_z(self):
947 """
948 The z coordinate at the end of each compartment. Returns ``None``
949 for morphologies without coordinates.
950 """
951 return _to_meters(self.end_z_)
952
953 @property
954 @abc.abstractmethod
955 def end_x_(self):
956 """
957 The x coordinate (as a unitless floating point number) at the end of
958 each compartment. Returns ``None`` for morphologies without coordinates.
959 """
960 raise NotImplementedError()
961
962 @property
963 @abc.abstractmethod
964 def end_y_(self):
965 """
966 The y coordinate (as a unitless floating point number) at the end of
967 each compartment. Returns ``None`` for morphologies without coordinates.
968 """
969 raise NotImplementedError()
970
971 @property
972 @abc.abstractmethod
973 def end_z_(self):
974 """
975 The z coordinate (as a unitless floating point number) at the end of
976 each compartment. Returns ``None`` for morphologies without coordinates.
977 """
978 raise NotImplementedError()
979
980 @property
981 def coordinates(self):
982 r"""
983 Array with all coordinates at the start- and end-points of each
984 compartment in this section. The array has size :math:`(n+1) \times 3`,
985 where :math:`n` is the number of compartments in this section. Each
986 row is one point (start point of first compartment, end point of first
987 compartment, end point of second compartment, ...), with the columns
988 being the x, y, and z coordinates. Returns ``None`` for morphologies
989 without coordinates.
990 """
991 if self.x_ is None:
992 return None
993 else:
994 return Quantity(self.coordinates_, dim=meter.dim)
995
996 @property
997 def coordinates_(self):
998 r"""
999 Array with all coordinates (as unitless floating point numbers) at the
1000 start- and end-points of each compartment in this section. The array has
1001 size :math:`(n+1) \times 3`, where :math:`n` is the number of
1002 compartments in this section. Each row is one point (start point of
1003 first compartment, end point of first compartment, end point of second
1004 compartment, ...), with the columns being the x, y, and z coordinates.
1005 Returns ``None`` for morphologies without coordinates.
1006 """
1007 if self.x_ is None:
1008 return None
1009 else:
1010 return np.vstack(
1011 [
1012 np.hstack([self.start_x_[0], self.end_x_[:]]),
1013 np.hstack([self.start_y_[0], self.end_y_[:]]),
1014 np.hstack([self.start_z_[0], self.end_z_[:]]),
1015 ]
1016 ).T
1017
1018 @staticmethod
1019 def _create_section(compartments, name, parent, sections, spherical_soma):
1020 if (
1021 spherical_soma
1022 and len(compartments) == 1
1023 and compartments[0].comp_name == "soma"
1024 ):
1025 soma = compartments[0]
1026 section = Soma(
1027 diameter=soma.diameter * um, x=soma.x * um, y=soma.y * um, z=soma.z * um
1028 )
1029 else:
1030 sec_x, sec_y, sec_z, sec_diameter = zip(
1031 *[(c.x, c.y, c.z, c.diameter) for c in compartments], strict=True
1032 )
1033 # Add a point for the end of the parent_idx compartment
1034 if parent is not None:
1035 n = len(compartments)
1036 if parent.comp_name is not None and parent.comp_name.lower() == "soma":
1037 # For a Soma, we don't use its diameter
1038 start_diameter = sec_diameter[0]
1039 else:
1040 start_diameter = parent.diameter
1041 # Use relative coordinates
1042 sec_x = np.array(sec_x) - parent.x
1043 sec_y = np.array(sec_y) - parent.y
1044 sec_z = np.array(sec_z) - parent.z
1045 start_x = start_y = start_z = 0.0
1046 else:
1047 n = len(compartments) - 1
1048 start_diameter = sec_diameter[0]
1049 sec_diameter = sec_diameter[1:]
1050 start_x = sec_x[0]
1051 start_y = sec_y[0]
1052 start_z = sec_z[0]
1053 sec_x = sec_x[1:]
1054 sec_y = sec_y[1:]
1055 sec_z = sec_z[1:]
1056
1057 diameter = np.hstack([start_diameter, sec_diameter]) * um
1058 x = np.hstack([start_x, sec_x]) * um
1059 y = np.hstack([start_y, sec_y]) * um
1060 z = np.hstack([start_z, sec_z]) * um
1061 section = Section(n=n, diameter=diameter, x=x, y=y, z=z, type=name)
1062
1063 # Add the section as a child to its parent
1064 if parent is not None:
1065 parent_sec = sections[parent.index]
1066 parent_sec.children.add(name, section, automatic_name=True)
1067
1068 return section
1069
1070 @staticmethod
1071 def _compartments_to_sections(
1072 compartment, spherical_soma, current_compartments=None, sections=None
1073 ):
1074 # Merge all unbranched compartments of the same type into a single
1075 # section
1076 if sections is None:
1077 sections = OrderedDict()
1078 if current_compartments is None:
1079 current_compartments = []
1080
1081 # We have to create a new section, if we are either
1082 # 1. at a leaf of the tree or at a branching point, or
1083 # 2. if the compartment type changes
1084 while True:
1085 current_compartments.append(compartment)
1086 if (
1087 len(compartment.children) != 1
1088 or compartment.children[0].comp_name != compartment.comp_name
1089 ):
1090 break
1091 compartment = compartment.children[0]
1092
1093 parent = current_compartments[0].parent
1094 section = Morphology._create_section(
1095 current_compartments,
1096 compartment.comp_name,
1097 parent=parent,
1098 sections=sections,
1099 spherical_soma=spherical_soma,
1100 )
1101 sections[current_compartments[-1].index] = section
1102 # If we are at a branching point, recurse into all subtrees
1103 for child in compartment.children:
1104 Morphology._compartments_to_sections(
1105 child,
1106 spherical_soma=spherical_soma,
1107 current_compartments=None,
1108 sections=sections,
1109 )
1110
1111 return sections
1112
1113 @staticmethod
1114 def _replace_three_point_soma(compartment, all_compartments):
1115 # Replace a three-point/two-cylinder soma by a single spherical soma
1116 # if possible (see http://neuromorpho.org/SomaFormat.html for some
1117 # details)
1118
1119 # We are looking for a node with two children of the soma type (and
1120 # other childen of other types), where the two children don't have any
1121 # children of their own
1122 # To avoid recursion errors we are not searching any further
1123 soma_children = [c for c in compartment.children if c.comp_name == "soma"]
1124 if (
1125 compartment.comp_name == "soma"
1126 and len(soma_children) == 2
1127 and all(len(c.children) == 0 for c in soma_children)
1128 ):
1129 # This is a 3-point soma to replace
1130 soma_c = [compartment] + soma_children
1131 if not all(abs(c.diameter - soma_c[0].diameter) < 1e-15 for c in soma_c):
1132 indices = ", ".join(str(c.index) for c in soma_c)
1133 raise ValueError(
1134 f"Found a '3-point-soma' (lines: {indices}), but not "
1135 "all the diameters are "
1136 "identical."
1137 )
1138 diameter = soma_c[0].diameter
1139 point_0 = np.array([soma_c[0].x, soma_c[0].y, soma_c[0].z])
1140 point_1 = np.array([soma_c[1].x, soma_c[1].y, soma_c[1].z])
1141 point_2 = np.array([soma_c[2].x, soma_c[2].y, soma_c[2].z])
1142 length_1 = np.sqrt(np.sum((point_1 - point_0) ** 2))
1143 length_2 = np.sqrt(np.sum((point_2 - point_0) ** 2))
1144 if (
1145 np.abs(length_1 - diameter / 2) > 0.1
1146 or np.abs(length_2 - diameter / 2) > 0.1
1147 ):
1148 raise ValueError(
1149 "Cannot replace '3-point-soma' by a single "
1150 "point, the second and third points should "
1151 "be positioned one radius away from the "
1152 f"first point. Distances are {length_1:.3f}um and "
1153 f"{length_2:.3f}um, respectively, while the "
1154 f"radius is {diameter / 2:.3f}um."
1155 )
1156 children = [c for c in compartment.children if c not in soma_c]
1157 compartment = Node(
1158 index=compartment.index,
1159 comp_name="soma",
1160 x=point_0[0],
1161 y=point_0[1],
1162 z=point_0[2],
1163 diameter=diameter,
1164 parent=compartment.parent,
1165 children=children,
1166 )
1167 all_compartments[compartment.index] = compartment
1168 del all_compartments[soma_children[0].index]
1169 del all_compartments[soma_children[1].index]
1170 else:
1171 # Raise a warning if there is more than one soma compartment
1172 somata = [c for c in all_compartments.values() if c.comp_name == "soma"]
1173 if len(somata) > 1:
1174 logger.warning(
1175 f"Found {len(somata)} soma compartments. If you have a 3-point soma, "
1176 "make sure it is at the beginning.",
1177 name_suffix="soma_compartments",
1178 )
1179
1180 @staticmethod
1181 def from_points(points, spherical_soma=True):
1182 """
1183 Create a morphology from a sequence of points (similar to the ``SWC``
1184 format, see `Morphology.from_swc_file`). Each point has to be
1185 a 7-tuple: ``(index, name, x, y, z, diameter, parent)``
1186
1187 Note that the values should not use units, but are instead all taken
1188 to be in micrometers.
1189
1190 Parameters
1191 ----------
1192 points : sequence of 7-tuples
1193 The points of the morphology.
1194 spherical_soma : bool, optional
1195 Whether to model a soma as a sphere.
1196 Returns
1197 -------
1198 morphology : `Morphology`
1199
1200 Notes
1201 -----
1202 This format closely follows the SWC format (see
1203 `Morphology.from_swc_file`) with two differences: the ``type`` should
1204 be a string (e.g. ``'soma'``) instead of an integer and the 6-th element
1205 should be the diameter and not the radius.
1206 """
1207 # First pass through all points to get the dependency structure
1208 compartments = OrderedDict()
1209 for counter, point in enumerate(points):
1210 if len(point) != 7:
1211 raise ValueError(
1212 "Each point needs to be described by 7 values, got"
1213 f" {len(point)} instead."
1214 )
1215 index, name, x, y, z, diameter, parent_idx = point
1216
1217 if index in compartments:
1218 raise ValueError(f"Two compartments with index {int(index)}")
1219 if parent_idx == index:
1220 raise ValueError(
1221 f"Compartment {int(index)} lists itself as the parent compartment."
1222 )
1223
1224 if counter == 0 and parent_idx == -1:
1225 parent = None # The first compartment does not have a parent
1226 elif parent_idx not in compartments:
1227 raise ValueError(
1228 f"Did not find the compartment {parent_idx} (parent "
1229 f"compartment of compartment {index}). Make sure "
1230 "that parent compartments are listed before "
1231 "their children."
1232 )
1233 else:
1234 parent = compartments[parent_idx]
1235 children = []
1236 node = Node(index, name, x, y, z, diameter, parent, children)
1237 compartments[index] = node
1238 if parent is not None:
1239 parent.children.append(node)
1240
1241 if spherical_soma:
1242 Morphology._replace_three_point_soma(
1243 list(compartments.values())[0], compartments
1244 )
1245
1246 sections = Morphology._compartments_to_sections(
1247 list(compartments.values())[0], spherical_soma
1248 )
1249
1250 # Go through all the sections again and add standard names for all
1251 # sections (potentially in addition to the name they already have):
1252 # "L" + "R" for one or two children, "1", "2", "3", etc. otherwise
1253 children_counter = defaultdict(int)
1254 for section in sections.values():
1255 parent = section.parent
1256 if parent is not None:
1257 children_counter[parent] += 1
1258 children = parent.children
1259 nth_child = children_counter[parent]
1260 if len(children) <= 2:
1261 name = "L" if nth_child == 1 else "R"
1262 else:
1263 name = f"{int(nth_child)}"
1264 children.add(name, section)
1265
1266 # There should only be one section without parents
1267 root = [sec for sec in sections.values() if sec.parent is None]
1268 assert len(root) == 1
1269 return root[0]
1270
1271 @staticmethod
1272 def from_swc_file(filename, spherical_soma=True):
1273 """
1274 Load a morphology from a ``SWC`` file. A large database of morphologies
1275 in this format can be found at http://neuromorpho.org
1276
1277 The format consists of an optional header of lines starting with ``#``
1278 (ignored), followed by a sequence of points, each described in a line
1279 following the format::
1280
1281 index type x y z radius parent
1282
1283 ``index`` is an integer label (starting at 1) that identifies the
1284 current point and increases by one each line. ``type`` is an integer
1285 representing the type of the neural segment. The only type that changes
1286 the interpretation by Brian is the type ``1`` which signals a soma.
1287 Types ``2`` (axon), ``3`` (dendrite), and ``4`` (apical dendrite) are
1288 used to give corresponding names to the respective sections. All other
1289 types are ignored. ``x``, ``y``, and ``z`` are the cartesian coordinates
1290 at each point and ``r`` is its radius. ``parent`` refers to the index
1291 of the parent point or is ``-1`` for the root point.
1292
1293 Parameters
1294 ----------
1295 filename : str
1296 The name of the ``SWC`` file.
1297 spherical_soma : bool, optional
1298 Whether to model the soma as a sphere.
1299
1300 Returns
1301 -------
1302 morpho : `Morphology`
1303 The morphology stored in the given file.
1304 """
1305 swc_types = defaultdict(lambda: None)
1306 # The following names will be translated into names, all other will be
1307 # ignored
1308 swc_types.update({"1": "soma", "2": "axon", "3": "dend", "4": "apic"})
1309
1310 with open(filename) as f:
1311 points = []
1312 for line_no, line in enumerate(f):
1313 line = line.strip()
1314 if line.startswith("#") or len(line) == 0:
1315 # Ignore comments or empty lines
1316 continue
1317 splitted = line.split()
1318 if len(splitted) != 7:
1319 raise ValueError(
1320 "Each line of an SWC file has to contain "
1321 "7 space-separated entries, but line "
1322 f"{line_no + 1} contains {len(splitted)}."
1323 )
1324 index, comp_type, x, y, z, radius, parent = splitted
1325 points.append(
1326 (
1327 int(index),
1328 swc_types[comp_type],
1329 float(x),
1330 float(y),
1331 float(z),
1332 2 * float(radius),
1333 int(parent),
1334 )
1335 )
1336
1337 return Morphology.from_points(points, spherical_soma=spherical_soma)
1338
1339 @staticmethod
1340 def from_file(filename, spherical_soma=True):
1341 """
1342 Convencience method to load a morphology from a given file. At the
1343 moment, only ``SWC`` files are supported, calling this function is
1344 therefore equivalent to calling `Morphology.from_swc_file` directly.
1345
1346 Parameters
1347 ----------
1348 filename : str
1349 The name of a file storing a morphology.
1350 spherical_soma : bool, optional
1351 Whether to model the soma as a sphere.
1352 Returns
1353 -------
1354 morphology : `Morphology`
1355 The morphology stored in the given file.
1356 """
1357 _, ext = os.path.splitext(filename)
1358 if ext.lower() == ".swc":
1359 return Morphology.from_swc_file(filename, spherical_soma=spherical_soma)
1360 else:
1361 raise NotImplementedError(
1362 "Currently, SWC is the only supported file format."
1363 )
1364
1365
1366 class SubMorphology:
1367 """
1368 A view on a subset of a section in a morphology.
1369 """
1370
1371 def __init__(self, morphology, i, j):
1372 self._morphology = morphology
1373 self.indices = MorphologyIndexWrapper(self)
1374 self._i = i
1375 self._j = j
1376
1377 def _indices(self, item=None):
1378 if not (item is None or item == slice(None)):
1379 raise IndexError("Cannot index a view on a subset of a section further")
1380 # Start index of the main section
1381 start_idx = _calc_start_idx(self._morphology)
1382 if item is None and self.n == 1:
1383 return start_idx + self._i
1384 else:
1385 return np.arange(start_idx + self._i, start_idx + self._j)
1386
1387 @property
1388 def n(self):
1389 """
1390 The number of compartments in this sub-section.
1391 """
1392 return self._j - self._i
1393
1394 def __len__(self):
1395 return self.n
1396
1397 @property
1398 def n_sections(self):
1399 """
1400 The number of sections in this sub-section (always 1).
1401 """
1402 return 1
1403
1404 # Per-compartment attributes
1405 @property
1406 def area(self):
1407 """
1408 The membrane surface area of each compartment in this sub-section.
1409 """
1410 return self._morphology.area[self._i : self._j]
1411
1412 @property
1413 def volume(self):
1414 """
1415 The volume of each compartment in this sub-section.
1416 """
1417 return self._morphology.volume[self._i : self._j]
1418
1419 @property
1420 def length(self):
1421 """
1422 The length of each compartment in this sub-section.
1423 """
1424 return self._morphology.length[self._i : self._j]
1425
1426 @property
1427 def r_length_1(self):
1428 """
1429 The geometry-dependent term to calculate the conductance between the
1430 start and the midpoint of each compartment in this sub-section.
1431 Dividing this value by the Intracellular resistivity gives the
1432 conductance.
1433 """
1434 return self._morphology.r_length_1[self._i : self._j]
1435
1436 @property
1437 def r_length_2(self):
1438 """
1439 The geometry-dependent term to calculate the conductance between the
1440 midpoint and the end of each compartment in this sub-section. Dividing
1441 this value by the Intracellular resistivity gives the conductance.
1442 """
1443 return self._morphology.r_length_2[self._i : self._j]
1444
1445 # At-midpoint attributes
1446 @property
1447 def diameter(self):
1448 """
1449 The diameter at the middle of each compartment in this sub-section.
1450 """
1451 return self._morphology.diameter[self._i : self._j]
1452
1453 @property
1454 def distance(self):
1455 """
1456 The total distance between the midpoint of each compartment in this
1457 sub-section and the root of the morphology.
1458 """
1459 return self._morphology.distance[self._i : self._j]
1460
1461 @property
1462 def start_x(self):
1463 """
1464 The x coordinate at the beginning of each compartment in this
1465 sub-section. Returns ``None`` for morphologies without coordinates.
1466 """
1467 return _to_meters(self.start_x_)
1468
1469 @property
1470 def start_y(self):
1471 """
1472 The y coordinate at the beginning of each compartment in this
1473 sub-section. Returns ``None`` for morphologies without coordinates.
1474 """
1475 return _to_meters(self.start_y_)
1476
1477 @property
1478 def start_z(self):
1479 """
1480 The x coordinate at the beginning of each compartment in this
1481 sub-section. Returns ``None`` for morphologies without coordinates.
1482 """
1483 return _to_meters(self.start_z_)
1484
1485 @property
1486 def start_x_(self):
1487 """
1488 The x coordinate (as a unitless floating point number) at the beginning
1489 of each compartment in this sub-section. Returns ``None`` for
1490 morphologies without coordinates.
1491 """
1492 return _from_morphology(self._morphology.start_x_, self._i, self._j)
1493
1494 @property
1495 def start_y_(self):
1496 """
1497 The y coordinate (as a unitless floating point number) at the beginning
1498 of each compartment in this sub-section. Returns ``None`` for
1499 morphologies without coordinates.
1500 """
1501 return _from_morphology(self._morphology.start_y_, self._i, self._j)
1502
1503 @property
1504 def start_z_(self):
1505 """
1506 The z coordinate (as a unitless floating point number) at the beginning
1507 of each compartment in this sub-section. Returns ``None`` for
1508 morphologies without coordinates.
1509 """
1510 return _from_morphology(self._morphology.start_z_, self._i, self._j)
1511
1512 @property
1513 def x(self):
1514 """
1515 The x coordinate at the midpoint of each compartment in this
1516 sub-section. Returns ``None`` for morphologies without coordinates.
1517 """
1518 return _to_meters(self.x_)
1519
1520 @property
1521 def y(self):
1522 """
1523 The y coordinate at the midpoint of each compartment in this
1524 sub-section. Returns ``None`` for morphologies without coordinates.
1525 """
1526 return _to_meters(self.y_)
1527
1528 @property
1529 def z(self):
1530 """
1531 The z coordinate at the midpoint of each compartment in this
1532 sub-section. Returns ``None`` for morphologies without coordinates.
1533 """
1534 return _to_meters(self.z_)
1535
1536 @property
1537 def x_(self):
1538 """
1539 The x coordinate (as a unitless floating point number) at the midpoint
1540 of each compartment in this sub-section. Returns ``None`` for
1541 morphologies without coordinates.
1542 """
1543 return _from_morphology(self._morphology.x_, self._i, self._j)
1544
1545 @property
1546 def y_(self):
1547 """
1548 The y coordinate (as a unitless floating point number) at the midpoint
1549 of each compartment in this sub-section. Returns ``None`` for
1550 morphologies without coordinates.
1551 """
1552 return _from_morphology(self._morphology.y_, self._i, self._j)
1553
1554 @property
1555 def z_(self):
1556 """
1557 The z coordinate (as a unitless floating point number) at the midpoint
1558 of each compartment in this sub-section. Returns ``None`` for
1559 morphologies without coordinates.
1560 """
1561 return _from_morphology(self._morphology.z_, self._i, self._j)
1562
1563 @property
1564 def end_x(self):
1565 """
1566 The x coordinate at the end of each compartment in this sub-section.
1567 Returns ``None`` for morphologies without coordinates.
1568 """
1569 return _to_meters(self.end_x_)
1570
1571 @property
1572 def end_y(self):
1573 """
1574 The y coordinate at the end of each compartment in this sub-section.
1575 Returns ``None`` for morphologies without coordinates.
1576 """
1577 return _to_meters(self.end_y_)
1578
1579 @property
1580 def end_z(self):
1581 """
1582 The z coordinate at the end of each compartment in this sub-section.
1583 Returns ``None`` for morphologies without coordinates.
1584 """
1585 return _to_meters(self.end_z_)
1586
1587 @property
1588 def end_x_(self):
1589 """
1590 The x coordinate (as a unitless floating point number) at the end of
1591 each compartment in this sub-section. Returns ``None`` for morphologies
1592 without coordinates.
1593 """
1594 return _from_morphology(self._morphology.end_x_, self._i, self._j)
1595
1596 @property
1597 def end_y_(self):
1598 """
1599 The y coordinate (as a unitless floating point number) at the end of
1600 each compartment in this sub-section. Returns ``None`` for morphologies
1601 without coordinates.
1602 """
1603 return _from_morphology(self._morphology.end_y_, self._i, self._j)
1604
1605 @property
1606 def end_z_(self):
1607 """
1608 The z coordinate (as a unitless floating point number) at the end of
1609 each compartment in this sub-section. Returns ``None`` for morphologies
1610 without coordinates.
1611 """
1612 return _from_morphology(self._morphology.end_z_, self._i, self._j)
1613
1614
1615 class Soma(Morphology):
1616 """
1617 A spherical, iso-potential soma.
1618
1619 Parameters
1620 ----------
1621 diameter : `Quantity`
1622 Diameter of the sphere.
1623 x : `Quantity`, optional
1624 The x coordinate of the position of the soma.
1625 y : `Quantity`, optional
1626 The y coordinate of the position of the soma.
1627 z : `Quantity`, optional
1628 The z coordinate of the position of the soma.
1629 type : str, optional
1630 The ``type`` of this section, defaults to ``'soma'``.
1631 """
1632
1633 @check_units(diameter=meter, x=meter, y=meter, z=meter)
1634 def __init__(self, diameter, x=None, y=None, z=None, type="soma"):
1635 Morphology.__init__(self, n=1, type=type)
1636 if diameter.shape != () and len(diameter) != 1:
1637 raise TypeError("Diameter has to be a scalar value.")
1638 for coord in [x, y, z]:
1639 if coord is not None and coord.shape != () and len(coord) != 1:
1640 raise TypeError("Coordinates have to be scalar values.")
1641 self._diameter = np.ones(1) * diameter
1642 if any(coord is not None for coord in (x, y, z)):
1643 default_value = np.array([0.0])
1644 else:
1645 default_value = None
1646 self._x = np.atleast_1d(np.asarray(x)) if x is not None else default_value
1647 self._y = np.atleast_1d(np.asarray(y)) if y is not None else default_value
1648 self._z = np.atleast_1d(np.asarray(z)) if z is not None else default_value
1649
1650 def __repr__(self):
1651 s = f"{self.__class__.__name__}(diameter={self.diameter[0]!r}"
1652 if self._x is not None:
1653 s += f", x={self.x[0]!r}, y={self.y[0]!r}, z={self.z[0]!r}"
1654 if self.type != "soma":
1655 s += f", type={self.type!r}"
1656 return f"{s})"
1657
1658 def copy_section(self):
1659 return Soma(self.diameter, x=self.x, y=self.y, z=self.z, type=self.type)
1660
1661 # Note that the per-compartment properties should always return 1D arrays,
1662 # i.e. for the soma arrays of length 1 instead of scalar values
1663 @property
1664 def area(self):
1665 """
1666 The membrane surface area of this section (as an array of length 1).
1667 """
1668 return np.pi * self.diameter**2
1669
1670 @property
1671 def volume(self):
1672 """
1673 The volume of this section (as an array of length 1).
1674 """
1675 return (np.pi * self.diameter**3) / 6
1676
1677 @property
1678 def length(self):
1679 """
1680 The "length" (equal to `diameter`) of this section (as an array of
1681 length 1).
1682 """
1683 return self.diameter
1684
1685 @property
1686 def r_length_1(self):
1687 """
1688 The geometry-dependent term to calculate the conductance between the
1689 start and the midpoint of each compartment. Returns a fixed (high)
1690 value for a `Soma`, corresponding to a section with very low
1691 intracellular resistance.
1692 """
1693 return [1] * meter
1694
1695 @property
1696 def r_length_2(self):
1697 """
1698 The geometry-dependent term to calculate the conductance between the
1699 midpoint and the end of each compartment. Returns a fixed (high)
1700 value for a `Soma`, corresponding to a section with very low
1701 intracellular resistance.
1702 """
1703 return [1] * meter
1704
1705 @property
1706 def diameter(self):
1707 """
1708 The diameter of this section (as an array of length 1).
1709 """
1710 return self._diameter
1711
1712 @property
1713 def distance(self):
1714 """
1715 The total distance between the midpoint of this section and the root
1716 of the morphology. The `Soma` is most likely the root of the
1717 morphology, and therefore the `distance` is 0.
1718 """
1719 dist = self._parent.distance[-1:] if self._parent is not None else [0] * um
1720 return dist
1721
1722 @property
1723 def start_x_(self):
1724 """
1725 The x-coordinate of the current section (as an array of length 1). Note
1726 that a `Soma` is modelled as a "point" with finite surface/volume,
1727 equivalent to that of a sphere with the given `diameter`. It's start-,
1728 midpoint-, and end-coordinates are therefore identical.
1729 """
1730 return self._x
1731
1732 @property
1733 def start_y_(self):
1734 """
1735 The y-coordinate of the current section (as an array of length 1). Note
1736 that a `Soma` is modelled as a "point" with finite surface/volume,
1737 equivalent to that of a sphere with the given `diameter`. It's start-,
1738 midpoint-, and end-coordinates are therefore identical.
1739 """
1740 return self._y
1741
1742 @property
1743 def start_z_(self):
1744 """
1745 The z-coordinate of the current section (as an array of length 1). Note
1746 that a `Soma` is modelled as a "point" with finite surface/volume,
1747 equivalent to that of a sphere with the given `diameter`. It's start-,
1748 midpoint-, and end-coordinates are therefore identical.
1749 """
1750 return self._z
1751
1752 @property
1753 def x_(self):
1754 """
1755 The x-coordinate of the current section (as an array of length 1). Note
1756 that a `Soma` is modelled as a "point" with finite surface/volume,
1757 equivalent to that of a sphere with the given `diameter`. It's start-,
1758 midpoint-, and end-coordinates are therefore identical.
1759 """
1760 return self._x
1761
1762 @property
1763 def y_(self):
1764 """
1765 The y-coordinate of the current section (as an array of length 1). Note
1766 that a `Soma` is modelled as a "point" with finite surface/volume,
1767 equivalent to that of a sphere with the given `diameter`. It's start-,
1768 midpoint-, and end-coordinates are therefore identical.
1769 """
1770 return self._y
1771
1772 @property
1773 def z_(self):
1774 """
1775 The z-coordinate of the current section (as an array of length 1). Note
1776 that a `Soma` is modelled as a "point" with finite surface/volume,
1777 equivalent to that of a sphere with the given `diameter`. It's start-,
1778 midpoint-, and end-coordinates are therefore identical.
1779 """
1780 return self._z
1781
1782 @property
1783 def end_x_(self):
1784 """
1785 The x-coordinate of the current section (as an array of length 1). Note
1786 that a `Soma` is modelled as a "point" with finite surface/volume,
1787 equivalent to that of a sphere with the given `diameter`. It's start-,
1788 midpoint-, and end-coordinates are therefore identical.
1789 """
1790 return self._x
1791
1792 @property
1793 def end_y_(self):
1794 """
1795 The y-coordinate of the current section (as an array of length 1). Note
1796 that a `Soma` is modelled as a "point" with finite surface/volume,
1797 equivalent to that of a sphere with the given `diameter`. It's start-,
1798 midpoint-, and end-coordinates are therefore identical.
1799 """
1800 return self._y
1801
1802 @property
1803 def end_z_(self):
1804 """
1805 The z-coordinate of the current section (as an array of length 1). Note
1806 that a `Soma` is modelled as a "point" with finite surface/volume,
1807 equivalent to that of a sphere with the given `diameter`. It's start-,
1808 midpoint-, and end-coordinates are therefore identical.
1809 """
1810 return self._z
1811
1812 @property
1813 def end_distance(self):
1814 """
1815 The distance to the root of the morphology at the end of this section.
1816 Note that since a `Soma` is modeled as a point (see docs of `x`, etc.),
1817 it does not add anything to the total distance, e.g. a section
1818 connecting to a `Soma` has a `distance` of 0 um at its start.
1819 """
1820 dist = self._parent.end_distance if self._parent is not None else 0 * um
1821 return dist
1822
1823
1824 class Section(Morphology):
1825 """
1826 A section (unbranched structure), described as a sequence of truncated
1827 cones with potentially varying diameters and lengths per compartment.
1828
1829 Parameters
1830 ----------
1831 diameter : `Quantity`
1832 Either a single value (the constant diameter along the whole section),
1833 or a value of length ``n+1``. When ``n+1`` values are given, they
1834 will be interpreted as the diameters at the start of the first
1835 compartment and the diameters at the end of each compartment (which is
1836 equivalent to: the diameter at the start of each compartment and the
1837 diameter at the end of the last compartment.
1838 n : int, optional
1839 The number of compartments in this section. Defaults to 1.
1840 length : `Quantity`, optional
1841 Either a single value (the total length of the section), or a value of
1842 length ``n``, the length of each individual compartment. Cannot be
1843 combined with the specification of coordinates.
1844 x : `Quantity`, optional
1845 ``n+1`` values, specifying the x coordinates of the start point of the
1846 first compartment and the end-points of all compartments (which is
1847 equivalent to: the start point of all compartments and the end point of
1848 the last compartment). The coordinates are interpreted as relative to
1849 the end point of the parent compartment (if any), so in most cases the
1850 start point should be ``0*um``. The common exception is a cylinder
1851 connecting to a `Soma`, here the start point can be used to make the
1852 cylinder start at the surface of the sphere instead of at its center.
1853 You can specify all of ``x``, ``y``, or ``z`` to specify
1854 a morphology in 3D, or only one or two out of them to specify a
1855 morphology in 1D or 2D.
1856 y : `Quantity`, optional
1857 See ``x``
1858 z : `Quantity`, optional
1859 See ``x``
1860 type : str, optional
1861 The type (e.g. ``"axon"``) of this `Section`.
1862 """
1863
1864 @check_units(
1865 n=1,
1866 length=meter,
1867 diameter=meter,
1868 start_diameter=meter,
1869 x=meter,
1870 y=meter,
1871 z=meter,
1872 )
1873 def __init__(
1874 self,
1875 diameter,
1876 n=1,
1877 length=None,
1878 x=None,
1879 y=None,
1880 z=None,
1881 start_diameter=None,
1882 origin=None,
1883 type=None,
1884 ):
1885 n = int(n)
1886 Morphology.__init__(self, n=n, type=type)
1887
1888 if diameter.ndim != 1 or len(diameter) != n + 1:
1889 raise TypeError(
1890 "The diameter argument has to be a one-dimensional array of length "
1891 f"{int(n + 1)}"
1892 )
1893 self._diameter = Quantity(diameter, copy=True).reshape((n + 1,))
1894
1895 if (x is not None or y is not None or z is not None) and length is not None:
1896 raise TypeError("Cannot specify coordinates and length at the same time.")
1897
1898 if length is not None:
1899 # Length
1900 if length.ndim != 1 or len(length) != n:
1901 raise TypeError(
1902 "The length argument has to be a one-dimensional array of length "
1903 f"{int(n)}"
1904 )
1905 self._length = Quantity(length, copy=True).reshape((n,))
1906 self._x = self._y = self._z = None
1907 else:
1908 # Coordinates
1909 if x is None and y is None and z is None:
1910 raise TypeError(
1911 "No length specified, need to specify at least "
1912 "one out of x, y, or z."
1913 )
1914 for name, value in [("x", x), ("y", y), ("z", z)]:
1915 if value is not None and (value.ndim != 1 or len(value) != n + 1):
1916 raise TypeError(
1917 f"'{name}' needs to be a 1-dimensional array of length {n + 1}."
1918 )
1919 self._x = (
1920 np.asarray(x).reshape((n + 1,)) if x is not None else np.zeros(n + 1)
1921 )
1922 self._y = (
1923 np.asarray(y).reshape((n + 1,)) if y is not None else np.zeros(n + 1)
1924 )
1925 self._z = (
1926 np.asarray(z).reshape((n + 1,)) if z is not None else np.zeros(n + 1)
1927 )
1928
1929 length = np.sqrt(
1930 (self.end_x - self.start_x) ** 2
1931 + (self.end_y - self.start_y) ** 2
1932 + (self.end_z - self.start_z) ** 2
1933 )
1934 self._length = length
1935
1936 def __repr__(self):
1937 if all(
1938 np.abs(self.end_diameter - self.end_diameter[0])
1939 < self.end_diameter[0] * 1e-12
1940 ):
1941 # Constant diameter
1942 diam = self.end_diameter[0]
1943 else:
1944 diam = (
1945 np.hstack(
1946 [np.asarray(self.start_diameter[0]), np.asarray(self.end_diameter)]
1947 )
1948 * meter
1949 )
1950 s = f"{self.__class__.__name__}(diameter={diam!r}"
1951 if self.n != 1:
1952 s += f", n={self.n}"
1953 if self._x is not None:
1954 s += f", x={self._x!r}, y={self._y!r}, z={self._z!r}"
1955 else:
1956 s += f", length={sum(self._length)!r}"
1957 if self.type is not None:
1958 s += f", type={self.type!r}"
1959 return f"{s})"
1960
1961 def copy_section(self):
1962 if self.x is None:
1963 x, y, z = None, None, None
1964 length = self.length
1965 else:
1966 x, y, z = self._x * meter, self._y * meter, self._z * meter
1967 length = None
1968 return Section(
1969 diameter=self._diameter,
1970 n=self.n,
1971 x=x,
1972 y=y,
1973 z=z,
1974 length=length,
1975 type=self.type,
1976 )
1977
1978 @property
1979 def area(self):
1980 r"""
1981 The membrane surface area of each compartment in this section. The
1982 surface area of each compartment is calculated as
1983 :math:`\frac{\pi}{2}(d_1 + d_2)\sqrt{\frac{(d_1 - d_2)^2}{4} + l^2)}`,
1984 where :math:`l` is the length of the compartment, and :math:`d_1` and
1985 :math:`d_2` are the diameter at the start and end of the compartment,
1986 respectively. Note that this surface area does not contain the area of
1987 the two disks at the two sides of the truncated cone.
1988 """
1989 d_1 = self.start_diameter
1990 d_2 = self.end_diameter
1991 return (
1992 np.pi / 2 * (d_1 + d_2) * np.sqrt(((d_1 - d_2) ** 2) / 4 + self._length**2)
1993 )
1994
1995 @property
1996 def volume(self):
1997 r"""
1998 The volume of each compartment in this section. The volume of each
1999 compartment is calculated as
2000 :math:`\frac{\pi}{12} l (d_1^2 + d_1 d_2 + d_2^2)`,
2001 where :math:`l` is the length of the compartment, and :math:`d_1` and
2002 :math:`d_2` are the diameter at the start and end of the compartment,
2003 respectively.
2004 """
2005 d_1 = self.start_diameter
2006 d_2 = self.end_diameter
2007 return np.pi * self._length * (d_1**2 + d_1 * d_2 + d_2**2) / 12
2008
2009 @property
2010 def length(self):
2011 """
2012 The length of each compartment in this section.
2013 """
2014 return self._length
2015
2016 @property
2017 def start_diameter(self):
2018 """
2019 The diameter at the start of each compartment in this section.
2020 """
2021 return Quantity(self._diameter[:-1], copy=True)
2022
2023 @property
2024 def end_diameter(self):
2025 """
2026 The diameter at the end of each compartment in this section.
2027 """
2028 return Quantity(self._diameter[1:], copy=True)
2029
2030 @property
2031 def diameter(self):
2032 """
2033 The diameter at the middle of each compartment in this section.
2034 """
2035 d_1 = self.start_diameter
2036 d_2 = self.end_diameter
2037 # Diameter at the center
2038 return 0.5 * (d_1 + d_2)
2039
2040 @property
2041 def distance(self):
2042 """
2043 The total distance between the midpoint of each compartment and the root
2044 of the morphology.
2045 """
2046 dist = self._parent.end_distance if self._parent is not None else 0 * um
2047 return dist + np.cumsum(self.length) - 0.5 * self.length
2048
2049 @property
2050 def end_distance(self):
2051 """
2052 The distance to the root of the morphology at the end of this section.
2053 """
2054 return self.distance[-1] + 0.5 * self.length[-1]
2055
2056 @property
2057 def r_length_1(self):
2058 """
2059 The geometry-dependent term to calculate the conductance between the
2060 start and the midpoint of each compartment. Dividing this value by the
2061 Intracellular resistivity gives the conductance.
2062 """
2063 d_1 = self.start_diameter
2064 d_2 = (self.start_diameter + self.end_diameter) * 0.5
2065 return np.pi / 2 * (d_1 * d_2) / self._length
2066
2067 @property
2068 def r_length_2(self):
2069 """
2070 The geometry-dependent term to calculate the conductance between the
2071 midpoint and the end of each compartment. Dividing this value by the
2072 Intracellular resistivity gives the conductance.
2073 """
2074 d_1 = (self.start_diameter + self.end_diameter) * 0.5
2075 d_2 = self.end_diameter
2076 return np.pi / 2 * (d_1 * d_2) / self._length
2077
2078 @property
2079 def start_x_(self):
2080 """
2081 The x coordinate (as a unitless floating point number) at the beginning
2082 of each compartment. Returns ``None`` for morphologies without
2083 coordinates.
2084 """
2085 if self._x is None:
2086 return None
2087 parent_end_x = self.parent.end_x_ if self.parent is not None else None
2088 if parent_end_x is not None:
2089 return parent_end_x[-1] + self._x[:-1]
2090 else:
2091 return self._x[:-1]
2092
2093 @property
2094 def start_y_(self):
2095 """
2096 The y coordinate (as a unitless floating point number) at the beginning
2097 of each compartment. Returns ``None`` for morphologies without
2098 coordinates.
2099 """
2100 if self._y is None:
2101 return None
2102 parent_end_y = self.parent.end_y_ if self.parent is not None else None
2103 if parent_end_y is not None:
2104 return parent_end_y[-1] + self._y[:-1]
2105 else:
2106 return self._y[:-1]
2107
2108 @property
2109 def start_z_(self):
2110 """
2111 The z coordinate (as a unitless floating point number) at the beginning
2112 of each compartment. Returns ``None`` for morphologies without
2113 coordinates.
2114 """
2115 if self._z is None:
2116 return None
2117 parent_end_z = self.parent.end_z_ if self.parent is not None else None
2118 if parent_end_z is not None:
2119 return parent_end_z[-1] + self._z[:-1]
2120 else:
2121 return self._z[:-1]
2122
2123 @property
2124 def x_(self):
2125 """
2126 The x coordinate (as a unitless floating point number) at the midpoint
2127 of each compartment. Returns ``None`` for morphologies without
2128 coordinates.
2129 """
2130 if self._x is None:
2131 return None
2132 start_x = self.start_x_
2133 diff_x = self.end_x_ - start_x
2134 return start_x + 0.5 * diff_x
2135
2136 @property
2137 def y_(self):
2138 """
2139 The y coordinate (as a unitless floating point number) at the midpoint
2140 of each compartment. Returns ``None`` for morphologies without
2141 coordinates.
2142 """
2143 if self._y is None:
2144 return None
2145 start_y = self.start_y_
2146 diff_y = self.end_y_ - start_y
2147 return start_y + 0.5 * diff_y
2148
2149 @property
2150 def z_(self):
2151 """
2152 The z coordinate (as a unitless floating point number) at the midpoint
2153 of each compartment. Returns ``None`` for morphologies without
2154 coordinates.
2155 """
2156 if self._z is None:
2157 return None
2158 start_z = self.start_z_
2159 diff_z = self.end_z_ - start_z
2160 return start_z + 0.5 * diff_z
2161
2162 @property
2163 def end_x_(self):
2164 """
2165 The x coordinate (as a unitless floating point number) at the end of
2166 each compartment. Returns ``None`` for morphologies without coordinates.
2167 """
2168 if self._x is None:
2169 return None
2170 parent_end_x = self.parent.end_x_ if self.parent is not None else None
2171 if parent_end_x is not None:
2172 return parent_end_x[-1] + self._x[1:]
2173 else:
2174 return self._x[1:]
2175
2176 @property
2177 def end_y_(self):
2178 """
2179 The y coordinate (as a unitless floating point number) at the end of
2180 each compartment. Returns ``None`` for morphologies without coordinates.
2181 """
2182 if self._y is None:
2183 return None
2184 parent_end_y = self.parent.end_y_ if self.parent is not None else None
2185 if parent_end_y is not None:
2186 return parent_end_y[-1] + self._y[1:]
2187 else:
2188 return self._y[1:]
2189
2190 @property
2191 def end_z_(self):
2192 """
2193 The z coordinate (as a unitless floating point number) at the end of
2194 each compartment. Returns ``None`` for morphologies without coordinates.
2195 """
2196 if self._z is None:
2197 return None
2198 parent_end_z = self.parent.end_z_ if self.parent is not None else None
2199 if parent_end_z is not None:
2200 return parent_end_z[-1] + self._z[1:]
2201 else:
2202 return self._z[1:]
2203
2204
2205 class Cylinder(Section):
2206 """
2207 A cylindrical section. For sections with more complex geometry (varying
2208 length and/or diameter of each compartment), use the `Section` class.
2209
2210 Parameters
2211 ----------
2212 diameter : `Quantity`
2213 The diameter of the cylinder.
2214 n : int, optional
2215 The number of compartments in this section. Defaults to 1.
2216 length : `Quantity`, optional
2217 The length of the cylinder. Cannot be combined with the specification
2218 of coordinates.
2219 x : `Quantity`, optional
2220 A sequence of two values, the start and the end point of the cylinder.
2221 The coordinates are interpreted as relative to the end point of the
2222 parent compartment (if any), so in most cases the start point should
2223 be ``0*um``. The common exception is a cylinder connecting to a `Soma`,
2224 here the start point can be used to make the cylinder start at the
2225 surface of the sphere instead of at its center.
2226 You can specify all of ``x``, ``y``, or ``z`` to specify
2227 a morphology in 3D, or only one or two out of them to specify a
2228 morphology in 1D or 2D.
2229 y : `Quantity`, optional
2230 See ``x``
2231 z : `Quantity`, optional
2232 See ``x``
2233 type : str, optional
2234 The type (e.g. ``"axon"``) of this `Cylinder`.
2235 """
2236
2237 @check_units(n=1, length=meter, diameter=meter, x=meter, y=meter, z=meter)
2238 def __init__(self, diameter, n=1, length=None, x=None, y=None, z=None, type=None):
2239 n = int(n)
2240 Morphology.__init__(self, n=n, type=type)
2241
2242 # Diameter
2243 if diameter.shape != () and (diameter.ndim > 1 or len(diameter) != 1):
2244 raise TypeError("The diameter argument has to be a single value.")
2245 diameter = np.ones(n) * diameter
2246 self._diameter = diameter
2247
2248 if (x is not None or y is not None or z is not None) and length is not None:
2249 raise TypeError("Cannot specify coordinates and length at the same time.")
2250
2251 if length is not None:
2252 # Length
2253 if length.shape != () and (length.ndim > 1 or len(length) != 1):
2254 raise TypeError("The length argument has to be a single value.")
2255 self._length = np.ones(n) * (length / n) # length was total length
2256 self._x = self._y = self._z = None
2257 else:
2258 # Coordinates
2259 if x is None and y is None and z is None:
2260 raise TypeError(
2261 "No length specified, need to specify at least "
2262 "one out of x, y, or z."
2263 )
2264 for name, value in [("x", x), ("y", y), ("z", z)]:
2265 if value is not None and (value.ndim != 1 or len(value) != 2):
2266 raise TypeError(
2267 f"{name} needs to be a 1-dimensional array of length 2 (start "
2268 "and end point)"
2269 )
2270 self._x = (
2271 np.asarray(np.linspace(x[0], x[1], n + 1))
2272 if x is not None
2273 else np.zeros(n + 1)
2274 )
2275 self._y = (
2276 np.asarray(np.linspace(y[0], y[1], n + 1))
2277 if y is not None
2278 else np.zeros(n + 1)
2279 )
2280 self._z = (
2281 np.asarray(np.linspace(z[0], z[1], n + 1))
2282 if z is not None
2283 else np.zeros(n + 1)
2284 )
2285 length = np.sqrt(
2286 (self.end_x - self.start_x) ** 2
2287 + (self.end_y - self.start_y) ** 2
2288 + (self.end_z - self.start_z) ** 2
2289 )
2290 self._length = length
2291
2292 def __repr__(self):
2293 s = f"{self.__class__.__name__}(diameter={self.diameter[0]!r}"
2294 if self.n != 1:
2295 s += f", n={self.n}"
2296 if self._x is not None:
2297 s += (
2298 f", x={self._x[[0, -1]]!r}, y={self._y[[0, -1]]!r},"
2299 f" z={self._z[[0, -1]]!r}"
2300 )
2301 else:
2302 s += f", length={sum(self._length)!r}"
2303 if self.type is not None:
2304 s += f", type={self.type!r}"
2305 return f"{s})"
2306
2307 def copy_section(self):
2308 if self.x is None:
2309 return Cylinder(
2310 self.diameter[0], n=self.n, length=self.length, type=self.type
2311 )
2312 else:
2313 return Cylinder(
2314 self.diameter[0],
2315 n=self.n,
2316 x=self._x[[0, -1]],
2317 y=self._y[[0, -1]],
2318 z=self._z[[0, -1]],
2319 type=self.type,
2320 )
2321
2322 # Overwrite the properties that differ from `Section`
2323 @property
2324 def area(self):
2325 r"""
2326 The membrane surface area of each compartment in this section. The
2327 surface area of each compartment is calculated as
2328 :math:`\pi d l`,
2329 where :math:`l` is the length of the compartment, and :math:`d` is its
2330 diameter. Note that this surface area does not contain the area of
2331 the two disks at the two sides of the cylinder.
2332 """
2333 return np.pi * self._diameter * self.length
2334
2335 @property
2336 def start_diameter(self):
2337 """
2338 The diameter at the start of each compartment in this section.
2339 """
2340 return self._diameter
2341
2342 @property
2343 def diameter(self):
2344 """
2345 The diameter at the middle of each compartment in this section.
2346 """
2347 return self._diameter
2348
2349 @property
2350 def end_diameter(self):
2351 """
2352 The diameter at the end of each compartment in this section.
2353 """
2354 return self._diameter
2355
2356 @property
2357 def volume(self):
2358 r"""
2359 The volume of each compartment in this section. The volume of each
2360 compartment is calculated as
2361 :math:`\pi \frac{d}{2}^2 l` ,
2362 where :math:`l` is the length of the compartment, and :math:`d` is its
2363 diameter.
2364 """
2365 return np.pi * (self._diameter / 2) ** 2 * self.length
2366
2367 @property
2368 def r_length_1(self):
2369 """
2370 The geometry-dependent term to calculate the conductance between the
2371 start and the midpoint of each compartment. Dividing this value by the
2372 Intracellular resistivity gives the conductance.
2373 """
2374 return np.pi / 2 * (self._diameter**2) / self.length
2375
2376 @property
2377 def r_length_2(self):
2378 """
2379 The geometry-dependent term to calculate the conductance between the
2380 midpoint and the end of each compartment. Dividing this value by the
2381 Intracellular resistivity gives the conductance.
2382 """
2383 return np.pi / 2 * (self._diameter**2) / self.length