| 1 |
""" |
| 2 |
Compartmental models. |
| 3 |
This module defines the `SpatialNeuron` class, which defines multicompartmental |
| 4 |
models. |
| 5 |
""" |
| 6 |
|
| 7 |
import copy |
| 8 |
import weakref |
| 9 |
|
| 10 |
import numpy as np |
| 11 |
import sympy as sp |
| 12 |
|
| 13 |
from brian2.core.variables import Variables |
| 14 |
from brian2.equations.codestrings import Expression |
| 15 |
from brian2.equations.equations import ( |
| 16 |
DIFFERENTIAL_EQUATION, |
| 17 |
PARAMETER, |
| 18 |
SUBEXPRESSION, |
| 19 |
Equations, |
| 20 |
SingleEquation, |
| 21 |
extract_constant_subexpressions, |
| 22 |
) |
| 23 |
from brian2.groups.group import CodeRunner, Group |
| 24 |
from brian2.groups.neurongroup import NeuronGroup, SubexpressionUpdater, to_start_stop |
| 25 |
from brian2.groups.subgroup import Subgroup |
| 26 |
from brian2.parsing.sympytools import str_to_sympy, sympy_to_str |
| 27 |
from brian2.units.allunits import amp, meter, ohm, siemens, volt |
| 28 |
from brian2.units.fundamentalunits import ( |
| 29 |
DimensionMismatchError, |
| 30 |
Quantity, |
| 31 |
fail_for_dimension_mismatch, |
| 32 |
have_same_dimensions, |
| 33 |
) |
| 34 |
from brian2.units.stdunits import cm, uF |
| 35 |
from brian2.utils.logger import get_logger |
| 36 |
|
| 37 |
__all__ = ["SpatialNeuron"] |
| 38 |
|
| 39 |
logger = get_logger(__name__) |
| 40 |
|
| 41 |
|
| 42 |
class FlatMorphology: |
| 43 |
""" |
| 44 |
Container object to store the flattened representation of a morphology. |
| 45 |
Note that all values are stored as numpy arrays without unit information |
| 46 |
(i.e. in base units). |
| 47 |
""" |
| 48 |
|
| 49 |
def __init__(self, morphology): |
| 50 |
self.n = n = morphology.total_compartments # Total number of compartments |
| 51 |
# Per-compartment attributes |
| 52 |
self.length = np.zeros(n) |
| 53 |
self.distance = np.zeros(n) |
| 54 |
self.area = np.zeros(n) |
| 55 |
self.diameter = np.zeros(n) |
| 56 |
self.volume = np.zeros(n) |
| 57 |
self.r_length_1 = np.zeros(n) |
| 58 |
self.r_length_2 = np.zeros(n) |
| 59 |
self.start_x = np.zeros(n) |
| 60 |
self.start_y = np.zeros(n) |
| 61 |
self.start_z = np.zeros(n) |
| 62 |
self.x = np.zeros(n) |
| 63 |
self.y = np.zeros(n) |
| 64 |
self.z = np.zeros(n) |
| 65 |
self.end_x = np.zeros(n) |
| 66 |
self.end_y = np.zeros(n) |
| 67 |
self.end_z = np.zeros(n) |
| 68 |
self.depth = np.zeros(n, dtype=np.int32) |
| 69 |
self.sections = sections = morphology.total_sections |
| 70 |
self.end_distance = np.zeros(sections) |
| 71 |
# Index of the parent for each section (-1 for the root) |
| 72 |
self.morph_parent_i = np.zeros(sections, dtype=np.int32) |
| 73 |
# The children indices for each section (list of lists, will be later |
| 74 |
# transformed into an array representation) |
| 75 |
self.morph_children = [] |
| 76 |
# each section is child of exactly one parent, this stores the index in |
| 77 |
# the parents list of children |
| 78 |
self.morph_idxchild = np.zeros(sections, dtype=np.int32) |
| 79 |
self.starts = np.zeros(sections, dtype=np.int32) |
| 80 |
self.ends = np.zeros(sections, dtype=np.int32) |
| 81 |
|
| 82 |
# recursively fill the data structures |
| 83 |
self._sections_without_coordinates = False |
| 84 |
self.has_coordinates = False |
| 85 |
self._offset = 0 |
| 86 |
self._section_counter = 0 |
| 87 |
self._insert_data(morphology) |
| 88 |
if self.has_coordinates and self._sections_without_coordinates: |
| 89 |
logger.info( |
| 90 |
"The morphology has a mix of sections with and " |
| 91 |
"without coordinates. The SpatialNeuron object " |
| 92 |
"will store NaN values for the coordinates of " |
| 93 |
"the sections that do not specify coordinates. " |
| 94 |
"Call generate_coordinates on the morphology " |
| 95 |
"before creating the SpatialNeuron object to fill " |
| 96 |
"in the missing coordinates." |
| 97 |
) |
| 98 |
# Do not store coordinates for morphologies that don't define them |
| 99 |
if not self.has_coordinates: |
| 100 |
self.start_x = self.start_y = self.start_z = None |
| 101 |
self.x = self.y = self.z = None |
| 102 |
self.end_x = self.end_y = self.end_z = None |
| 103 |
|
| 104 |
# Transform the list of list of children into a 2D array (stored as |
| 105 |
# 1D) -- note that this wastes space if the number of children per |
| 106 |
# section is very different. In practice, this should not be much of a |
| 107 |
# problem since most sections have 0, 1, or 2 children (e.g. SWC files |
| 108 |
# on neuromorpho.org are all binary trees) |
| 109 |
self.morph_children_num = np.array([len(c) for c in self.morph_children] + [0]) |
| 110 |
max_children = max(self.morph_children_num) |
| 111 |
morph_children = np.zeros((sections + 1, max_children), dtype=np.int32) |
| 112 |
for idx, section_children in enumerate(self.morph_children): |
| 113 |
morph_children[idx, : len(section_children)] = section_children |
| 114 |
self.morph_children = morph_children.reshape(-1) |
| 115 |
|
| 116 |
def _insert_data(self, section, parent_idx=-1, depth=0): |
| 117 |
n = section.n |
| 118 |
start = self._offset |
| 119 |
end = self._offset + n |
| 120 |
# Compartment attributes |
| 121 |
self.depth[start:end] = depth |
| 122 |
self.length[start:end] = np.asarray(section.length) |
| 123 |
self.distance[start:end] = np.asarray(section.distance) |
| 124 |
self.area[start:end] = np.asarray(section.area) |
| 125 |
self.diameter[start:end] = np.asarray(section.diameter) |
| 126 |
self.volume[start:end] = np.asarray(section.volume) |
| 127 |
self.r_length_1[start:end] = np.asarray(section.r_length_1) |
| 128 |
self.r_length_2[start:end] = np.asarray(section.r_length_2) |
| 129 |
if section.x is None: |
| 130 |
self._sections_without_coordinates = True |
| 131 |
self.start_x[start:end] = np.ones(n) * np.nan |
| 132 |
self.start_y[start:end] = np.ones(n) * np.nan |
| 133 |
self.start_z[start:end] = np.ones(n) * np.nan |
| 134 |
self.x[start:end] = np.ones(n) * np.nan |
| 135 |
self.y[start:end] = np.ones(n) * np.nan |
| 136 |
self.z[start:end] = np.ones(n) * np.nan |
| 137 |
self.end_x[start:end] = np.ones(n) * np.nan |
| 138 |
self.end_y[start:end] = np.ones(n) * np.nan |
| 139 |
self.end_z[start:end] = np.ones(n) * np.nan |
| 140 |
else: |
| 141 |
self.has_coordinates = True |
| 142 |
self.start_x[start:end] = np.asarray(section.start_x) |
| 143 |
self.start_y[start:end] = np.asarray(section.start_y) |
| 144 |
self.start_z[start:end] = np.asarray(section.start_z) |
| 145 |
self.x[start:end] = np.asarray(section.x) |
| 146 |
self.y[start:end] = np.asarray(section.y) |
| 147 |
self.z[start:end] = np.asarray(section.z) |
| 148 |
self.end_x[start:end] = np.asarray(section.end_x) |
| 149 |
self.end_y[start:end] = np.asarray(section.end_y) |
| 150 |
self.end_z[start:end] = np.asarray(section.end_z) |
| 151 |
|
| 152 |
# Section attributes |
| 153 |
idx = self._section_counter |
| 154 |
# We start counting from 1 for the parent indices, since the index 0 |
| 155 |
# is used for the (virtual) root compartment |
| 156 |
self.morph_parent_i[idx] = parent_idx + 1 |
| 157 |
self.morph_children.append([]) |
| 158 |
self.starts[idx] = start |
| 159 |
self.ends[idx] = end |
| 160 |
# Append ourselves to the children list of our parent |
| 161 |
self.morph_idxchild[idx] = len(self.morph_children[parent_idx + 1]) |
| 162 |
self.morph_children[parent_idx + 1].append(idx + 1) |
| 163 |
self.end_distance[idx] = section.end_distance |
| 164 |
# Recurse down the tree |
| 165 |
self._offset += n |
| 166 |
self._section_counter += 1 |
| 167 |
for child in section.children: |
| 168 |
self._insert_data(child, parent_idx=idx, depth=depth + 1) |
| 169 |
|
| 170 |
|
| 171 |
class SpatialNeuron(NeuronGroup): |
| 172 |
""" |
| 173 |
A single neuron with a morphology and possibly many compartments. |
| 174 |
|
| 175 |
Parameters |
| 176 |
---------- |
| 177 |
morphology : `Morphology` |
| 178 |
The morphology of the neuron. |
| 179 |
model : str, `Equations` |
| 180 |
The equations defining the group. |
| 181 |
method : str, function, optional |
| 182 |
The numerical integration method. Either a string with the name of a |
| 183 |
registered method (e.g. "euler") or a function that receives an |
| 184 |
`Equations` object and returns the corresponding abstract code. If no |
| 185 |
method is specified, a suitable method will be chosen automatically. |
| 186 |
threshold : str, optional |
| 187 |
The condition which produces spikes. Should be a single line boolean |
| 188 |
expression. |
| 189 |
threshold_location : (int, `Morphology`), optional |
| 190 |
Compartment where the threshold condition applies, specified as an |
| 191 |
integer (compartment index) or a `Morphology` object corresponding to |
| 192 |
the compartment (e.g. ``morpho.axon[10*um]``). |
| 193 |
If unspecified, the threshold condition applies at all compartments. |
| 194 |
Cm : `Quantity`, optional |
| 195 |
Specific capacitance in uF/cm**2 (default 0.9). It can be accessed and |
| 196 |
modified later as a state variable. In particular, its value can differ |
| 197 |
in different compartments. |
| 198 |
Ri : `Quantity`, optional |
| 199 |
Intracellular resistivity in ohm.cm (default 150). It can be accessed |
| 200 |
as a shared state variable, but modified only before the first run. |
| 201 |
It is uniform across the neuron. |
| 202 |
reset : str, optional |
| 203 |
The (possibly multi-line) string with the code to execute on reset. |
| 204 |
events : dict, optional |
| 205 |
User-defined events in addition to the "spike" event defined by the |
| 206 |
``threshold``. Has to be a mapping of strings (the event name) to |
| 207 |
strings (the condition) that will be checked. |
| 208 |
refractory : {str, `Quantity`}, optional |
| 209 |
Either the length of the refractory period (e.g. ``2*ms``), a string |
| 210 |
expression that evaluates to the length of the refractory period |
| 211 |
after each spike (e.g. ``'(1 + rand())*ms'``), or a string expression |
| 212 |
evaluating to a boolean value, given the condition under which the |
| 213 |
neuron stays refractory after a spike (e.g. ``'v > -20*mV'``) |
| 214 |
namespace : dict, optional |
| 215 |
A dictionary mapping identifier names to objects. If not given, the |
| 216 |
namespace will be filled in at the time of the call of `Network.run`, |
| 217 |
with either the values from the ``namespace`` argument of the |
| 218 |
`Network.run` method or from the local context, if no such argument is |
| 219 |
given. |
| 220 |
dtype : (`dtype`, `dict`), optional |
| 221 |
The `numpy.dtype` that will be used to store the values, or a |
| 222 |
dictionary specifying the type for variable names. If a value is not |
| 223 |
provided for a variable (or no value is provided at all), the preference |
| 224 |
setting `core.default_float_dtype` is used. |
| 225 |
dt : `Quantity`, optional |
| 226 |
The time step to be used for the simulation. Cannot be combined with |
| 227 |
the `clock` argument. |
| 228 |
clock : `Clock`, optional |
| 229 |
The update clock to be used. If neither a clock, nor the `dt` argument |
| 230 |
is specified, the `defaultclock` will be used. |
| 231 |
order : int, optional |
| 232 |
The priority of of this group for operations occurring at the same time |
| 233 |
step and in the same scheduling slot. Defaults to 0. |
| 234 |
name : str, optional |
| 235 |
A unique name for the group, otherwise use ``spatialneuron_0``, etc. |
| 236 |
""" |
| 237 |
|
| 238 |
def __init__( |
| 239 |
self, |
| 240 |
morphology=None, |
| 241 |
model=None, |
| 242 |
threshold=None, |
| 243 |
refractory=False, |
| 244 |
reset=None, |
| 245 |
events=None, |
| 246 |
threshold_location=None, |
| 247 |
dt=None, |
| 248 |
clock=None, |
| 249 |
order=0, |
| 250 |
Cm=0.9 * uF / cm**2, |
| 251 |
Ri=150 * ohm * cm, |
| 252 |
name="spatialneuron*", |
| 253 |
dtype=None, |
| 254 |
namespace=None, |
| 255 |
method=("exact", "exponential_euler", "rk2", "heun"), |
| 256 |
method_options=None, |
| 257 |
): |
| 258 |
# #### Prepare and validate equations |
| 259 |
if isinstance(model, str): |
| 260 |
model = Equations(model) |
| 261 |
if not isinstance(model, Equations): |
| 262 |
raise TypeError( |
| 263 |
"model has to be a string or an Equations " |
| 264 |
f"object, is '{type(model)}' instead." |
| 265 |
) |
| 266 |
|
| 267 |
# Insert the threshold mechanism at the specified location |
| 268 |
if threshold_location is not None: |
| 269 |
if hasattr(threshold_location, "_indices"): # assuming this is a method |
| 270 |
threshold_location = threshold_location._indices() |
| 271 |
# for now, only a single compartment allowed |
| 272 |
try: |
| 273 |
int(threshold_location) |
| 274 |
except TypeError: |
| 275 |
raise AttributeError( |
| 276 |
"Threshold can only be applied on a single location" |
| 277 |
) from None |
| 278 |
threshold = f"({threshold}) and (i == {str(threshold_location)})" |
| 279 |
|
| 280 |
# Check flags (we have point currents) |
| 281 |
model.check_flags( |
| 282 |
{ |
| 283 |
DIFFERENTIAL_EQUATION: ("point current",), |
| 284 |
PARAMETER: ("constant", "shared", "linked", "point current"), |
| 285 |
SUBEXPRESSION: ("shared", "point current", "constant over dt"), |
| 286 |
} |
| 287 |
) |
| 288 |
#: The original equations as specified by the user (i.e. before |
| 289 |
#: inserting point-currents into the membrane equation, before adding |
| 290 |
#: all the internally used variables and constants, etc.). |
| 291 |
self.user_equations = model |
| 292 |
|
| 293 |
# Separate subexpressions depending whether they are considered to be |
| 294 |
# constant over a time step or not (this would also be done by the |
| 295 |
# NeuronGroup initializer later, but this would give incorrect results |
| 296 |
# for the linearity check) |
| 297 |
model, constant_over_dt = extract_constant_subexpressions(model) |
| 298 |
|
| 299 |
# Extract membrane equation |
| 300 |
if "Im" in model: |
| 301 |
if len(model["Im"].flags): |
| 302 |
raise TypeError( |
| 303 |
"Cannot specify any flags for the transmembrane current 'Im'." |
| 304 |
) |
| 305 |
membrane_expr = model["Im"].expr # the membrane equation |
| 306 |
else: |
| 307 |
raise TypeError("The transmembrane current 'Im' must be defined") |
| 308 |
|
| 309 |
model_equations = [] |
| 310 |
# Insert point currents in the membrane equation |
| 311 |
for eq in model.values(): |
| 312 |
if eq.varname == "Im": |
| 313 |
continue # ignore -- handled separately |
| 314 |
if "point current" in eq.flags: |
| 315 |
fail_for_dimension_mismatch( |
| 316 |
eq.dim, amp, f"Point current {eq.varname} should be in amp" |
| 317 |
) |
| 318 |
membrane_expr = Expression( |
| 319 |
f"{str(membrane_expr.code)}+{eq.varname}/area" |
| 320 |
) |
| 321 |
eq = SingleEquation( |
| 322 |
eq.type, |
| 323 |
eq.varname, |
| 324 |
eq.dim, |
| 325 |
expr=eq.expr, |
| 326 |
flags=list(set(eq.flags) - {"point current"}), |
| 327 |
) |
| 328 |
model_equations.append(eq) |
| 329 |
|
| 330 |
model_equations.append( |
| 331 |
SingleEquation( |
| 332 |
SUBEXPRESSION, |
| 333 |
"Im", |
| 334 |
dimensions=(amp / meter**2).dim, |
| 335 |
expr=membrane_expr, |
| 336 |
) |
| 337 |
) |
| 338 |
model_equations.append(SingleEquation(PARAMETER, "v", volt.dim)) |
| 339 |
model = Equations(model_equations) |
| 340 |
|
| 341 |
###### Process model equations (Im) to extract total conductance and the remaining current |
| 342 |
# Expand expressions in the membrane equation |
| 343 |
for var, expr in model.get_substituted_expressions(include_subexpressions=True): |
| 344 |
if var == "Im": |
| 345 |
Im_expr = expr |
| 346 |
break |
| 347 |
else: |
| 348 |
raise AssertionError("Model equations did not contain Im!") |
| 349 |
|
| 350 |
# Differentiate Im with respect to v |
| 351 |
Im_sympy_exp = str_to_sympy(Im_expr.code) |
| 352 |
v_sympy = sp.Symbol("v", real=True) |
| 353 |
diffed = sp.diff(Im_sympy_exp, v_sympy) |
| 354 |
|
| 355 |
unevaled_derivatives = diffed.atoms(sp.Derivative) |
| 356 |
if len(unevaled_derivatives): |
| 357 |
raise TypeError( |
| 358 |
f"Cannot take the derivative of '{Im_expr.code}' with respect to v." |
| 359 |
) |
| 360 |
|
| 361 |
gtot_str = sympy_to_str(sp.simplify(-diffed)) |
| 362 |
I0_str = sympy_to_str(sp.simplify(Im_sympy_exp - diffed * v_sympy)) |
| 363 |
|
| 364 |
if gtot_str == "0": |
| 365 |
gtot_str += "*siemens/meter**2" |
| 366 |
if I0_str == "0": |
| 367 |
I0_str += "*amp/meter**2" |
| 368 |
gtot_str = f"gtot__private={gtot_str}: siemens/meter**2" |
| 369 |
I0_str = f"I0__private={I0_str}: amp/meter**2" |
| 370 |
|
| 371 |
model += Equations(f"{gtot_str}\n{I0_str}") |
| 372 |
|
| 373 |
# Insert morphology (store a copy) |
| 374 |
self.morphology = copy.deepcopy(morphology) |
| 375 |
|
| 376 |
# Flatten the morphology |
| 377 |
self.flat_morphology = FlatMorphology(morphology) |
| 378 |
|
| 379 |
# Equations for morphology |
| 380 |
# TODO: check whether Cm and Ri are already in the equations |
| 381 |
# no: should be shared instead of constant |
| 382 |
# yes: should be constant (check) |
| 383 |
eqs_constants = Equations( |
| 384 |
""" |
| 385 |
length : meter (constant) |
| 386 |
distance : meter (constant) |
| 387 |
area : meter**2 (constant) |
| 388 |
volume : meter**3 |
| 389 |
Ic : amp/meter**2 |
| 390 |
diameter : meter (constant) |
| 391 |
Cm : farad/meter**2 (constant) |
| 392 |
Ri : ohm*meter (constant, shared) |
| 393 |
r_length_1 : meter (constant) |
| 394 |
r_length_2 : meter (constant) |
| 395 |
time_constant = Cm/gtot__private : second |
| 396 |
space_constant = (2/pi)**(1.0/3.0) * (area/(1/r_length_1 + 1/r_length_2))**(1.0/6.0) / |
| 397 |
(2*(Ri*gtot__private)**(1.0/2.0)) : meter |
| 398 |
""" |
| 399 |
) |
| 400 |
if self.flat_morphology.has_coordinates: |
| 401 |
eqs_constants += Equations( |
| 402 |
""" |
| 403 |
x : meter (constant) |
| 404 |
y : meter (constant) |
| 405 |
z : meter (constant) |
| 406 |
""" |
| 407 |
) |
| 408 |
|
| 409 |
NeuronGroup.__init__( |
| 410 |
self, |
| 411 |
morphology.total_compartments, |
| 412 |
model=model + eqs_constants, |
| 413 |
method_options=method_options, |
| 414 |
threshold=threshold, |
| 415 |
refractory=refractory, |
| 416 |
reset=reset, |
| 417 |
events=events, |
| 418 |
method=method, |
| 419 |
dt=dt, |
| 420 |
clock=clock, |
| 421 |
order=order, |
| 422 |
namespace=namespace, |
| 423 |
dtype=dtype, |
| 424 |
name=name, |
| 425 |
) |
| 426 |
# Parameters and intermediate variables for solving the cable equations |
| 427 |
# Note that some of these variables could have meaningful physical |
| 428 |
# units (e.g. _v_star is in volt, _I0_all is in amp/meter**2 etc.) but |
| 429 |
# since these variables should never be used in user code, we don't |
| 430 |
# assign them any units |
| 431 |
self.variables.add_arrays( |
| 432 |
[ |
| 433 |
"_ab_star0", |
| 434 |
"_ab_star1", |
| 435 |
"_ab_star2", |
| 436 |
"_b_plus", |
| 437 |
"_b_minus", |
| 438 |
"_v_star", |
| 439 |
"_u_plus", |
| 440 |
"_u_minus", |
| 441 |
"_v_previous", |
| 442 |
"_c", |
| 443 |
# The following two are only necessary for |
| 444 |
# C code where we cannot deal with scalars |
| 445 |
# and arrays interchangeably: |
| 446 |
"_I0_all", |
| 447 |
"_gtot_all", |
| 448 |
], |
| 449 |
size=self.N, |
| 450 |
read_only=True, |
| 451 |
) |
| 452 |
|
| 453 |
self.Cm = Cm |
| 454 |
self.Ri = Ri |
| 455 |
# These explict assignments will load the morphology values from disk |
| 456 |
# in standalone mode |
| 457 |
self.distance_ = self.flat_morphology.distance |
| 458 |
self.length_ = self.flat_morphology.length |
| 459 |
self.area_ = self.flat_morphology.area |
| 460 |
self.diameter_ = self.flat_morphology.diameter |
| 461 |
self.volume_ = self.flat_morphology.volume |
| 462 |
self.r_length_1_ = self.flat_morphology.r_length_1 |
| 463 |
self.r_length_2_ = self.flat_morphology.r_length_2 |
| 464 |
if self.flat_morphology.has_coordinates: |
| 465 |
self.x_ = self.flat_morphology.x |
| 466 |
self.y_ = self.flat_morphology.y |
| 467 |
self.z_ = self.flat_morphology.z |
| 468 |
|
| 469 |
# Performs numerical integration step |
| 470 |
self.add_attribute("diffusion_state_updater") |
| 471 |
self.diffusion_state_updater = SpatialStateUpdater( |
| 472 |
self, method, clock=self.clock, order=order |
| 473 |
) |
| 474 |
|
| 475 |
# Update v after the gating variables to obtain consistent Ic and Im |
| 476 |
self.diffusion_state_updater.order = 1 |
| 477 |
|
| 478 |
# Creation of contained_objects that do the work |
| 479 |
self.contained_objects.extend([self.diffusion_state_updater]) |
| 480 |
|
| 481 |
if len(constant_over_dt): |
| 482 |
self.subexpression_updater = SubexpressionUpdater(self, constant_over_dt) |
| 483 |
self.contained_objects.append(self.subexpression_updater) |
| 484 |
|
| 485 |
def __getattr__(self, name): |
| 486 |
""" |
| 487 |
Subtrees are accessed by attribute, e.g. neuron.axon. |
| 488 |
""" |
| 489 |
return self.spatialneuron_attribute(self, name) |
| 490 |
|
| 491 |
def __getitem__(self, item): |
| 492 |
""" |
| 493 |
Selects a segment, where x is a slice of either compartment |
| 494 |
indexes or distances. |
| 495 |
Note a: segment is not a SpatialNeuron, only a Group. |
| 496 |
""" |
| 497 |
return self.spatialneuron_segment(self, item) |
| 498 |
|
| 499 |
@staticmethod |
| 500 |
def _find_subtree_end(morpho): |
| 501 |
""" |
| 502 |
Go down a morphology recursively to find the (absolute) index of the |
| 503 |
"final" compartment (i.e. the one with the highest index) of the |
| 504 |
subtree. |
| 505 |
|
| 506 |
Parameters |
| 507 |
---------- |
| 508 |
morpho : `Morphology` |
| 509 |
The morphology for which to find the index. |
| 510 |
|
| 511 |
Returns |
| 512 |
------- |
| 513 |
index : int |
| 514 |
The highest index within the subtree. |
| 515 |
""" |
| 516 |
indices = [morpho.indices[-1]] |
| 517 |
for child in morpho.children: |
| 518 |
indices.append(SpatialNeuron._find_subtree_end(child)) |
| 519 |
return max(indices) |
| 520 |
|
| 521 |
@staticmethod |
| 522 |
def spatialneuron_attribute(neuron, name): |
| 523 |
""" |
| 524 |
Selects a subtree from `SpatialNeuron` neuron and returns a `SpatialSubgroup`. |
| 525 |
If it does not exist, returns the `Group` attribute. |
| 526 |
""" |
| 527 |
if name == "main": # Main section, without the subtrees |
| 528 |
indices = neuron.morphology.indices[:] |
| 529 |
start, stop = indices[0], indices[-1] |
| 530 |
return SpatialSubgroup( |
| 531 |
neuron, start, stop + 1, morphology=neuron.morphology |
| 532 |
) |
| 533 |
elif (name != "morphology") and ( |
| 534 |
(name in getattr(neuron.morphology, "children", [])) |
| 535 |
or all([c in "LR123456789" for c in name]) |
| 536 |
): # subtree |
| 537 |
morpho = neuron.morphology[name] |
| 538 |
start = morpho.indices[0] |
| 539 |
stop = SpatialNeuron._find_subtree_end(morpho) |
| 540 |
return SpatialSubgroup(neuron, start, stop + 1, morphology=morpho) |
| 541 |
else: |
| 542 |
return Group.__getattr__(neuron, name) |
| 543 |
|
| 544 |
@staticmethod |
| 545 |
def spatialneuron_segment(neuron, item): |
| 546 |
""" |
| 547 |
Selects a segment from `SpatialNeuron` neuron, where item is a slice of |
| 548 |
either compartment indexes or distances. |
| 549 |
Note a: segment is not a `SpatialNeuron`, only a `Group`. |
| 550 |
""" |
| 551 |
if isinstance(item, slice) and isinstance(item.start, Quantity): |
| 552 |
if item.step is not None: |
| 553 |
raise ValueError( |
| 554 |
"Cannot specify a step size for slicing basedon length." |
| 555 |
) |
| 556 |
start, stop = item.start, item.stop |
| 557 |
if not have_same_dimensions(start, meter) or not have_same_dimensions( |
| 558 |
stop, meter |
| 559 |
): |
| 560 |
raise DimensionMismatchError( |
| 561 |
"Start and stop should have units of meter", start, stop |
| 562 |
) |
| 563 |
# Convert to integers (compartment numbers) |
| 564 |
indices = neuron.morphology.indices[item] |
| 565 |
start, stop = indices[0], indices[-1] + 1 |
| 566 |
elif not isinstance(item, slice) and hasattr(item, "indices"): |
| 567 |
start, stop = to_start_stop(item.indices[:], neuron._N) |
| 568 |
else: |
| 569 |
start, stop = to_start_stop(item, neuron._N) |
| 570 |
if isinstance(neuron, SpatialSubgroup): |
| 571 |
start += neuron.start |
| 572 |
stop += neuron.start |
| 573 |
|
| 574 |
if start >= stop: |
| 575 |
raise IndexError( |
| 576 |
f"Illegal start/end values for subgroup, {int(start)}>={int(stop)}" |
| 577 |
) |
| 578 |
if isinstance(neuron, SpatialSubgroup): |
| 579 |
# Note that the start/stop values calculated above are always |
| 580 |
# absolute values, even for subgroups |
| 581 |
neuron = neuron.source |
| 582 |
return Subgroup(neuron, start, stop) |
| 583 |
|
| 584 |
|
| 585 |
class SpatialSubgroup(Subgroup): |
| 586 |
""" |
| 587 |
A subgroup of a `SpatialNeuron`. |
| 588 |
|
| 589 |
Parameters |
| 590 |
---------- |
| 591 |
source : int |
| 592 |
First compartment. |
| 593 |
stop : int |
| 594 |
Ending compartment, not included (as in slices). |
| 595 |
morphology : `Morphology` |
| 596 |
Morphology corresponding to the subgroup (not the full |
| 597 |
morphology). |
| 598 |
name : str, optional |
| 599 |
Name of the subgroup. |
| 600 |
""" |
| 601 |
|
| 602 |
def __init__(self, source, start, stop, morphology, name=None): |
| 603 |
self.morphology = morphology |
| 604 |
if isinstance(source, SpatialSubgroup): |
| 605 |
source = source.source |
| 606 |
start += source.start |
| 607 |
stop += source.start |
| 608 |
Subgroup.__init__(self, source, start, stop, name) |
| 609 |
|
| 610 |
def __getattr__(self, name): |
| 611 |
return SpatialNeuron.spatialneuron_attribute(self, name) |
| 612 |
|
| 613 |
def __getitem__(self, item): |
| 614 |
return SpatialNeuron.spatialneuron_segment(self, item) |
| 615 |
|
| 616 |
|
| 617 |
class SpatialStateUpdater(CodeRunner, Group): |
| 618 |
""" |
| 619 |
The `CodeRunner` that updates the state variables of a `SpatialNeuron` |
| 620 |
at every timestep. |
| 621 |
""" |
| 622 |
|
| 623 |
def __init__(self, group, method, clock, order=0): |
| 624 |
# group is the neuron (a group of compartments) |
| 625 |
self.method_choice = method |
| 626 |
self.group = weakref.proxy(group) |
| 627 |
|
| 628 |
compartments = group.flat_morphology.n |
| 629 |
sections = group.flat_morphology.sections |
| 630 |
|
| 631 |
CodeRunner.__init__( |
| 632 |
self, |
| 633 |
group, |
| 634 |
"spatialstateupdate", |
| 635 |
code="""_gtot = gtot__private |
| 636 |
_I0 = I0__private""", |
| 637 |
clock=clock, |
| 638 |
when="groups", |
| 639 |
order=order, |
| 640 |
name=f"{group.name}_spatialstateupdater*", |
| 641 |
check_units=False, |
| 642 |
template_kwds={"number_sections": sections}, |
| 643 |
) |
| 644 |
|
| 645 |
self.variables = Variables(self, default_index="_section_idx") |
| 646 |
self.variables.add_reference("N", group) |
| 647 |
# One value per compartment |
| 648 |
self.variables.add_arange("_compartment_idx", size=compartments) |
| 649 |
self.variables.add_array( |
| 650 |
"_invr", |
| 651 |
dimensions=siemens.dim, |
| 652 |
size=compartments, |
| 653 |
constant=True, |
| 654 |
index="_compartment_idx", |
| 655 |
) |
| 656 |
# one value per section |
| 657 |
self.variables.add_arange("_section_idx", size=sections) |
| 658 |
self.variables.add_array( |
| 659 |
"_P_parent", size=sections, constant=True |
| 660 |
) # elements below diagonal |
| 661 |
self.variables.add_arrays( |
| 662 |
["_morph_idxchild", "_morph_parent_i", "_starts", "_ends"], |
| 663 |
size=sections, |
| 664 |
dtype=np.int32, |
| 665 |
constant=True, |
| 666 |
) |
| 667 |
self.variables.add_arrays( |
| 668 |
["_invr0", "_invrn"], dimensions=siemens.dim, size=sections, constant=True |
| 669 |
) |
| 670 |
# one value per section + 1 value for the root |
| 671 |
self.variables.add_arange("_section_root_idx", size=sections + 1) |
| 672 |
self.variables.add_array( |
| 673 |
"_P_diag", size=sections + 1, constant=True, index="_section_root_idx" |
| 674 |
) |
| 675 |
self.variables.add_array( |
| 676 |
"_B", size=sections + 1, constant=True, index="_section_root_idx" |
| 677 |
) |
| 678 |
self.variables.add_array( |
| 679 |
"_morph_children_num", |
| 680 |
size=sections + 1, |
| 681 |
dtype=np.int32, |
| 682 |
constant=True, |
| 683 |
index="_section_root_idx", |
| 684 |
) |
| 685 |
# 2D matrices of size (sections + 1) x max children per section |
| 686 |
self.variables.add_arange( |
| 687 |
"_morph_children_idx", size=len(group.flat_morphology.morph_children) |
| 688 |
) |
| 689 |
self.variables.add_array( |
| 690 |
"_P_children", |
| 691 |
size=len(group.flat_morphology.morph_children), |
| 692 |
index="_morph_children_idx", |
| 693 |
constant=True, |
| 694 |
) # elements above diagonal |
| 695 |
self.variables.add_array( |
| 696 |
"_morph_children", |
| 697 |
size=len(group.flat_morphology.morph_children), |
| 698 |
dtype=np.int32, |
| 699 |
constant=True, |
| 700 |
index="_morph_children_idx", |
| 701 |
) |
| 702 |
self._enable_group_attributes() |
| 703 |
|
| 704 |
self._morph_parent_i = group.flat_morphology.morph_parent_i |
| 705 |
self._morph_children_num = group.flat_morphology.morph_children_num |
| 706 |
self._morph_children = group.flat_morphology.morph_children |
| 707 |
self._morph_idxchild = group.flat_morphology.morph_idxchild |
| 708 |
self._starts = group.flat_morphology.starts |
| 709 |
self._ends = group.flat_morphology.ends |