Debian Codegraph @

brian2/groups/neurongroup.py

raw
1 """
2 This model defines the `NeuronGroup`, the core of most simulations.
3 """
4
5 import numbers
6 import string
7 from collections.abc import MutableMapping, Sequence
8
9 import numpy as np
10 import sympy
11 from pyparsing import Word
12
13 from brian2.codegen.translation import analyse_identifiers
14 from brian2.core.preferences import prefs
15 from brian2.core.spikesource import SpikeSource
16 from brian2.core.variables import Variables
17 from brian2.equations.equations import (
18 DIFFERENTIAL_EQUATION,
19 PARAMETER,
20 SUBEXPRESSION,
21 Equations,
22 check_subexpressions,
23 extract_constant_subexpressions,
24 )
25 from brian2.equations.refractory import add_refractoriness
26 from brian2.parsing.expressions import (
27 is_boolean_expression,
28 parse_expression_dimensions,
29 )
30 from brian2.stateupdaters.base import StateUpdateMethod
31 from brian2.units.allunits import second
32 from brian2.units.fundamentalunits import (
33 DIMENSIONLESS,
34 Quantity,
35 fail_for_dimension_mismatch,
36 )
37 from brian2.utils.logger import get_logger
38 from brian2.utils.stringtools import get_identifiers
39
40 from .group import CodeRunner, Group, get_dtype
41 from .subgroup import Subgroup
42
43 __all__ = ["NeuronGroup"]
44
45 logger = get_logger(__name__)
46
47
48 IDENTIFIER = Word(
49 f"{string.ascii_letters}_", f"{string.ascii_letters + string.digits}_"
50 ).set_results_name("identifier")
51
52
53 def _valid_event_name(event_name):
54 """
55 Helper function to check whether a name is a valid name for an event.
56
57 Parameters
58 ----------
59 event_name : str
60 The name to check
61
62 Returns
63 -------
64 is_valid : bool
65 Whether the given name is valid
66 """
67 parse_result = list(IDENTIFIER.scan_string(event_name))
68
69 # parse_result[0][0][0] refers to the matched string -- this should be the
70 # full identifier, if not it is an illegal identifier like "3foo" which only
71 # matched on "foo"
72 return len(parse_result) == 1 and parse_result[0][0][0] == event_name
73
74
75 def _guess_membrane_potential(equations):
76 """
77 Little helper function to guess which variable represents the membrane
78 potential. This follows the same logic as in Brian1 but is only used to
79 give a suggestion in the error message when a Brian1-style syntax is used
80 for threshold or reset.
81 """
82 if len(equations) == 1:
83 return list(equations.keys())[0]
84 for name in equations:
85 if name in ["V", "v", "Vm", "vm"]:
86 return name
87
88 # nothing found
89 return None
90
91
92 # Note that we do not register this function with
93 # Equations.register_identifier_check, because we do not want this check to
94 # apply unconditionally to all equation objects ("x_post = ... : ... (summed)"
95 # needs to be allowed)
96 def check_identifier_pre_post(identifier):
97 "Do not allow names ending in ``_pre`` or ``_post`` to avoid confusion."
98 if identifier.endswith("_pre") or identifier.endswith("_post"):
99 raise ValueError(
100 f"'{identifier}' cannot be used as a variable name, the "
101 "'_pre' and '_post' suffixes are used to refer to pre- and "
102 "post-synaptic variables in synapses."
103 )
104
105
106 def to_start_stop(item, N):
107 """
108 Helper function to transform a single number, a slice or an array of
109 contiguous indices to a start and stop value. This is used to allow for
110 some flexibility in the syntax of specifying subgroups in `.NeuronGroup`
111 and `.SpatialNeuron`.
112
113 Parameters
114 ----------
115 item : slice, int or sequence
116 The slice, index, or sequence of indices to use. Note that a sequence
117 of indices has to be a sorted ascending sequence of subsequent integers.
118 N : int
119 The total number of elements in the group.
120
121 Returns
122 -------
123 start : int
124 The start value of the slice.
125 stop : int
126 The stop value of the slice.
127
128 Examples
129 --------
130 >>> from brian2.groups.neurongroup import to_start_stop
131 >>> to_start_stop(slice(3, 6), 10)
132 (3, 6)
133 >>> to_start_stop(slice(3, None), 10)
134 (3, 10)
135 >>> to_start_stop(5, 10)
136 (5, 6)
137 >>> to_start_stop([3, 4, 5], 10)
138 (3, 6)
139 >>> to_start_stop([3, 5, 7], 10)
140 Traceback (most recent call last):
141 ...
142 IndexError: Subgroups can only be constructed using contiguous indices.
143
144 """
145 if isinstance(item, slice):
146 start, stop, step = item.indices(N)
147 elif isinstance(item, numbers.Integral):
148 start = item
149 stop = item + 1
150 step = 1
151 elif isinstance(item, (Sequence, np.ndarray)) and not isinstance(item, str):
152 if not (len(item) > 0 and np.all(np.diff(item) == 1)):
153 raise IndexError(
154 "Subgroups can only be constructed using contiguous indices."
155 )
156 if not np.issubdtype(np.asarray(item).dtype, np.integer):
157 raise TypeError("Subgroups can only be constructed using integer values.")
158 start = int(item[0])
159 stop = int(item[-1]) + 1
160 step = 1
161 else:
162 raise TypeError(
163 "Subgroups can only be constructed using slicing "
164 "syntax, a single index, or an array of contiguous "
165 "indices."
166 )
167 if step != 1:
168 raise IndexError("Subgroups have to be contiguous")
169 if start >= stop:
170 raise IndexError(
171 f"Illegal start/end values for subgroup, {int(start)}>={int(stop)}"
172 )
173 if start >= N:
174 raise IndexError(f"Illegal start value for subgroup, {int(start)}>={int(N)}")
175 if stop > N:
176 raise IndexError(f"Illegal stop value for subgroup, {int(stop)}>{int(N)}")
177 if start < 0:
178 raise IndexError("Indices have to be positive.")
179 return start, stop
180
181
182 class StateUpdater(CodeRunner):
183 """
184 The `CodeRunner` that updates the state variables of a `NeuronGroup`
185 at every timestep.
186 """
187
188 def __init__(self, group, method, method_options=None):
189 self.method_choice = method
190 self.method_options = method_options
191 CodeRunner.__init__(
192 self,
193 group,
194 "stateupdate",
195 code="", # will be set in update_abstract_code
196 clock=group.clock,
197 when="groups",
198 order=group.order,
199 name=f"{group.name}_stateupdater",
200 check_units=False,
201 generate_empty_code=False,
202 )
203
204 def _get_refractory_code(self, run_namespace):
205 ref = self.group._refractory
206 if ref is False:
207 # No refractoriness
208 abstract_code = ""
209 elif isinstance(ref, Quantity):
210 fail_for_dimension_mismatch(
211 ref,
212 second,
213 "Refractory period has to "
214 "be specified in units "
215 "of seconds but got "
216 "{value}",
217 value=ref,
218 )
219 ref = float(ref)
220 if prefs.legacy.refractory_timing:
221 abstract_code = f"not_refractory = (t - lastspike) > {ref}\n"
222 else:
223 abstract_code = f"not_refractory = timestep(t - lastspike, dt) >= timestep({ref}, dt)\n"
224 else:
225 identifiers = get_identifiers(ref)
226 variables = self.group.resolve_all(
227 identifiers, run_namespace, user_identifiers=identifiers
228 )
229 dims = parse_expression_dimensions(str(ref), variables)
230 if dims is second.dim:
231 if prefs.legacy.refractory_timing:
232 abstract_code = f"(t - lastspike) > {ref}\n"
233 else:
234 abstract_code = (
235 "not_refractory = timestep(t - lastspike, dt) >="
236 f" timestep({ref}, dt)\n"
237 )
238 elif dims is DIMENSIONLESS:
239 if not is_boolean_expression(str(ref), variables):
240 raise TypeError(
241 "Refractory expression is dimensionless "
242 "but not a boolean value. It needs to "
243 "either evaluate to a timespan or to a "
244 "boolean value."
245 )
246 # boolean condition
247 # we have to be a bit careful here, we can't just use the given
248 # condition as it is, because we only want to *leave*
249 # refractoriness, based on the condition
250 abstract_code = f"not_refractory = not_refractory or not ({ref})\n"
251 else:
252 raise TypeError(
253 "Refractory expression has to evaluate to a "
254 "timespan or a boolean value, expression"
255 f"'{ref}' has units {dims} instead"
256 )
257 return abstract_code
258
259 def update_abstract_code(self, run_namespace):
260 # Update the not_refractory variable for the refractory period mechanism
261 self.abstract_code = self._get_refractory_code(run_namespace=run_namespace)
262
263 # Get the names used in the refractory code
264 _, used_known, unknown = analyse_identifiers(
265 self.abstract_code, self.group.variables, recursive=True
266 )
267
268 # Get all names used in the equations (and always get "dt")
269 names = self.group.equations.names
270 external_names = self.group.equations.identifiers | {"dt"}
271
272 variables = self.group.resolve_all(
273 used_known | unknown | names | external_names,
274 run_namespace,
275 # we don't need to raise any warnings
276 # for the user here, warnings will
277 # be raised in create_runner_codeobj
278 user_identifiers=set(),
279 )
280 if len(self.group.equations.diff_eq_names) > 0:
281 stateupdate_output = StateUpdateMethod.apply_stateupdater(
282 self.group.equations,
283 variables,
284 self.method_choice,
285 method_options=self.method_options,
286 group_name=self.group.name,
287 )
288 if isinstance(stateupdate_output, str):
289 self.abstract_code += stateupdate_output
290 else:
291 # Note that the reason to send self along with this method is so the StateUpdater
292 # can be modified! i.e. in GSL StateUpdateMethod a custom CodeObject gets added
293 # to the StateUpdater together with some auxiliary information
294 self.abstract_code += stateupdate_output(self)
295
296 user_code = "\n".join(
297 [
298 f"{var} = {expr}"
299 for var, expr in self.group.equations.get_substituted_expressions(
300 variables
301 )
302 ]
303 )
304 self.user_code = user_code
305
306
307 class SubexpressionUpdater(CodeRunner):
308 """
309 The `CodeRunner` that updates the state variables storing the values of
310 subexpressions that have been marked as "constant over dt".
311 """
312
313 def __init__(self, group, subexpressions, when="before_start"):
314 code_lines = []
315 for subexpr in subexpressions.ordered:
316 code_lines.append(f"{subexpr.varname} = {subexpr.expr}")
317 code = "\n".join(code_lines)
318 CodeRunner.__init__(
319 self,
320 group,
321 "stateupdate",
322 code=code, # will be set in update_abstract_code
323 clock=group.clock,
324 when=when,
325 order=group.order,
326 name=f"{group.name}_subexpression_update*",
327 )
328
329
330 class Thresholder(CodeRunner):
331 """
332 The `CodeRunner` that applies the threshold condition to the state
333 variables of a `NeuronGroup` at every timestep and sets its ``spikes``
334 and ``refractory_until`` attributes.
335 """
336
337 def __init__(self, group, when="thresholds", event="spike"):
338 self.event = event
339 if group._refractory is False or event != "spike":
340 template_kwds = {"_uses_refractory": False}
341 needed_variables = []
342 else:
343 template_kwds = {"_uses_refractory": True}
344 needed_variables = ["t", "not_refractory", "lastspike"]
345 # Since this now works for general events not only spikes, we have to
346 # pass the information about which variable to use to the template,
347 # it can not longer simply refer to "_spikespace"
348 eventspace_name = f"_{event}space"
349 template_kwds["eventspace_variable"] = group.variables[eventspace_name]
350 needed_variables.append(eventspace_name)
351 self.variables = Variables(self)
352 self.variables.add_auxiliary_variable("_cond", dtype=bool)
353 CodeRunner.__init__(
354 self,
355 group,
356 "threshold",
357 code="", # will be set in update_abstract_code
358 clock=group.clock,
359 when=when,
360 order=group.order,
361 name=f"{group.name}_{event}_thresholder",
362 needed_variables=needed_variables,
363 template_kwds=template_kwds,
364 )
365
366 def update_abstract_code(self, run_namespace):
367 code = self.group.events[self.event]
368 # Raise a useful error message when the user used a Brian1 syntax
369 if not isinstance(code, str):
370 if isinstance(code, Quantity):
371 t = "a quantity"
372 else:
373 t = f"{type(code)}"
374 error_msg = f"Threshold condition has to be a string, not {t}."
375 if self.event == "spike":
376 try:
377 vm_var = _guess_membrane_potential(self.group.equations)
378 except AttributeError: # not a group with equations...
379 vm_var = None
380 if vm_var is not None:
381 error_msg += f" Probably you intended to use '{vm_var} > ...'?"
382 raise TypeError(error_msg)
383
384 self.user_code = f"_cond = {code}"
385
386 identifiers = get_identifiers(code)
387 variables = self.group.resolve_all(
388 identifiers, run_namespace, user_identifiers=identifiers
389 )
390 if not is_boolean_expression(code, variables):
391 raise TypeError(f"Threshold condition '{code}' is not a boolean expression")
392 if self.group._refractory is False or self.event != "spike":
393 self.abstract_code = f"_cond = {code}"
394 else:
395 self.abstract_code = f"_cond = ({code}) and not_refractory"
396
397
398 class Resetter(CodeRunner):
399 """
400 The `CodeRunner` that applies the reset statement(s) to the state
401 variables of neurons that have spiked in this timestep.
402 """
403
404 def __init__(self, group, when="resets", order=None, event="spike"):
405 self.event = event
406 # Since this now works for general events not only spikes, we have to
407 # pass the information about which variable to use to the template,
408 # it can not longer simply refer to "_spikespace"
409 eventspace_name = f"_{event}space"
410 template_kwds = {"eventspace_variable": group.variables[eventspace_name]}
411 needed_variables = [eventspace_name]
412 order = order if order is not None else group.order
413 CodeRunner.__init__(
414 self,
415 group,
416 "reset",
417 code="", # will be set in update_abstract_code
418 clock=group.clock,
419 when=when,
420 order=order,
421 name=f"{group.name}_{event}_resetter",
422 override_conditional_write=["not_refractory"],
423 needed_variables=needed_variables,
424 template_kwds=template_kwds,
425 )
426
427 def update_abstract_code(self, run_namespace):
428 code = self.group.event_codes[self.event]
429 # Raise a useful error message when the user used a Brian1 syntax
430 if not isinstance(code, str):
431 if isinstance(code, Quantity):
432 t = "a quantity"
433 else:
434 t = f"{type(code)}"
435 error_msg = f"Reset statement has to be a string, not {t}."
436 if self.event == "spike":
437 vm_var = _guess_membrane_potential(self.group.equations)
438 if vm_var is not None:
439 error_msg += f" Probably you intended to use '{vm_var} = ...'?"
440 raise TypeError(error_msg)
441
442 self.abstract_code = code
443
444
445 class NeuronGroup(Group, SpikeSource):
446 """
447 A group of neurons.
448
449
450 Parameters
451 ----------
452 N : int
453 Number of neurons in the group.
454 model : str, `Equations`
455 The differential equations defining the group
456 method : (str, function), optional
457 The numerical integration method. Either a string with the name of a
458 registered method (e.g. "euler") or a function that receives an
459 `Equations` object and returns the corresponding abstract code. If no
460 method is specified, a suitable method will be chosen automatically.
461 threshold : str, optional
462 The condition which produces spikes. Should be a single line boolean
463 expression.
464 reset : str, optional
465 The (possibly multi-line) string with the code to execute on reset.
466 refractory : {str, `Quantity`}, optional
467 Either the length of the refractory period (e.g. ``2*ms``), a string
468 expression that evaluates to the length of the refractory period
469 after each spike (e.g. ``'(1 + rand())*ms'``), or a string expression
470 evaluating to a boolean value, given the condition under which the
471 neuron stays refractory after a spike (e.g. ``'v > -20*mV'``)
472 events : dict, optional
473 User-defined events in addition to the "spike" event defined by the
474 ``threshold``. Has to be a mapping of strings (the event name) to
475 strings (the condition) that will be checked.
476 namespace: dict, optional
477 A dictionary mapping identifier names to objects. If not given, the
478 namespace will be filled in at the time of the call of `Network.run`,
479 with either the values from the ``namespace`` argument of the
480 `Network.run` method or from the local context, if no such argument is
481 given.
482 dtype : (`dtype`, `dict`), optional
483 The `numpy.dtype` that will be used to store the values, or a
484 dictionary specifying the type for variable names. If a value is not
485 provided for a variable (or no value is provided at all), the preference
486 setting `core.default_float_dtype` is used.
487 codeobj_class : class, optional
488 The `CodeObject` class to run code with.
489 dt : `Quantity`, optional
490 The time step to be used for the simulation. Cannot be combined with
491 the `clock` argument.
492 clock : `Clock`, optional
493 The update clock to be used. If neither a clock, nor the `dt` argument
494 is specified, the `defaultclock` will be used.
495 order : int, optional
496 The priority of of this group for operations occurring at the same time
497 step and in the same scheduling slot. Defaults to 0.
498 name : str, optional
499 A unique name for the group, otherwise use ``neurongroup_0``, etc.
500
501 Notes
502 -----
503 `NeuronGroup` contains a `StateUpdater`, `Thresholder` and `Resetter`, and
504 these are run at the 'groups', 'thresholds' and 'resets' slots (i.e. the
505 values of their `when` attribute take these values). The `order`
506 attribute will be passed down to the contained objects but can be set
507 individually by setting the `order` attribute of the `state_updater`,
508 `thresholder` and `resetter` attributes, respectively.
509 """
510
511 add_to_magic_network = True
512
513 def __init__(
514 self,
515 N,
516 model,
517 method=("exact", "euler", "heun"),
518 method_options=None,
519 threshold=None,
520 reset=None,
521 refractory=False,
522 events=None,
523 namespace=None,
524 dtype=None,
525 dt=None,
526 clock=None,
527 order=0,
528 name="neurongroup*",
529 codeobj_class=None,
530 ):
531 Group.__init__(
532 self,
533 dt=dt,
534 clock=clock,
535 when="start",
536 order=order,
537 namespace=namespace,
538 name=name,
539 )
540 if dtype is None:
541 dtype = {}
542 if isinstance(dtype, MutableMapping):
543 dtype["lastspike"] = self._clock.variables["t"].dtype
544
545 self.codeobj_class = codeobj_class
546
547 try:
548 self._N = N = int(N)
549 except ValueError:
550 if isinstance(N, str):
551 raise TypeError(
552 "First NeuronGroup argument should be size, not equations."
553 ) from None
554 raise
555 if N < 1:
556 raise ValueError(f"NeuronGroup size should be at least 1, was {str(N)}")
557
558 self.start = 0
559 self.stop = self._N
560
561 ##### Prepare and validate equations
562 if isinstance(model, str):
563 model = Equations(model)
564 if not isinstance(model, Equations):
565 raise TypeError(
566 "model has to be a string or an Equations "
567 f"object, is '{type(model)}' instead."
568 )
569
570 # Check flags
571 model.check_flags(
572 {
573 DIFFERENTIAL_EQUATION: ("unless refractory",),
574 PARAMETER: ("constant", "shared", "linked"),
575 SUBEXPRESSION: ("shared", "constant over dt"),
576 }
577 )
578
579 # add refractoriness
580 #: The original equations as specified by the user (i.e. without
581 #: the multiplied `int(not_refractory)` term for equations marked as
582 #: `(unless refractory)`)
583 self.user_equations = model
584 if refractory is not False:
585 model = add_refractoriness(model)
586 uses_refractoriness = len(model) and any(
587 [
588 "unless refractory" in eq.flags
589 for eq in model.values()
590 if eq.type == DIFFERENTIAL_EQUATION
591 ]
592 )
593
594 # Separate subexpressions depending whether they are considered to be
595 # constant over a time step or not
596 model, constant_over_dt = extract_constant_subexpressions(model)
597 self.equations = model
598
599 self._linked_variables = set()
600 logger.diagnostic(
601 f"Creating NeuronGroup of size {self._N}, equations {self.equations}."
602 )
603
604 # All of the following will be created in before_run
605
606 #: The refractory condition or timespan
607 self._refractory = refractory
608 if uses_refractoriness and refractory is False:
609 logger.warn(
610 'Model equations use the "unless refractory" flag but '
611 "no refractory keyword was given.",
612 "no_refractory",
613 )
614
615 #: The state update method selected by the user
616 self.method_choice = method
617
618 if events is None:
619 events = {}
620
621 if threshold is not None and (reset is None and refractory is False):
622 if not ("rand(" in threshold or "randn(" in threshold):
623 logger.warn(
624 f"The NeuronGroup '{self.name}' sets a threshold but "
625 "neither a reset condition nor a refractory "
626 "condition has been set. Did you forget either of "
627 "those? If this was intended, set the reset "
628 "argument to an empty string in order to avoid "
629 "this warning.",
630 name_suffix="only_threshold",
631 )
632
633 if threshold is not None:
634 if "spike" in events:
635 raise ValueError(
636 "The NeuronGroup defines both a threshold and a 'spike' event"
637 )
638 events["spike"] = threshold
639
640 # Setup variables
641 # Since we have to create _spikespace and possibly other "eventspace"
642 # variables, we pass the supported events
643 self._create_variables(dtype, events=list(events.keys()))
644
645 #: Events supported by this group
646 self.events = events
647
648 #: Code that is triggered on events (e.g. reset)
649 self.event_codes = {}
650
651 #: Checks the spike threshold (or abitrary user-defined events)
652 self.thresholder = {}
653
654 #: Reset neurons which have spiked (or perform arbitrary actions for
655 #: user-defined events)
656 self.resetter = {}
657
658 for event_name in events.keys():
659 if not isinstance(event_name, str):
660 raise TypeError(
661 "Keys in the 'events' dictionary have to be "
662 f"strings, not type {event_name}."
663 )
664 if not _valid_event_name(event_name):
665 raise TypeError(
666 f"The name '{event_name}' cannot be used as an event name."
667 )
668 # By default, user-defined events are checked after the threshold
669 when = "thresholds" if event_name == "spike" else "after_thresholds"
670 # creating a Thresholder will take care of checking the validity
671 # of the condition
672 thresholder = Thresholder(self, event=event_name, when=when)
673 self.thresholder[event_name] = thresholder
674 self.contained_objects.append(thresholder)
675
676 if reset is not None:
677 self.run_on_event("spike", reset, when="resets")
678
679 #: Performs numerical integration step
680 self.state_updater = StateUpdater(self, method, method_options)
681 self.contained_objects.append(self.state_updater)
682
683 #: Update the "constant over a time step" subexpressions
684 self.subexpression_updater = None
685 if len(constant_over_dt):
686 self.subexpression_updater = SubexpressionUpdater(self, constant_over_dt)
687 self.contained_objects.append(self.subexpression_updater)
688
689 if refractory is not False:
690 # Set the refractoriness information
691 self.variables["lastspike"].set_value(-1e4 * second)
692 self.variables["not_refractory"].set_value(True)
693
694 # Activate name attribute access
695 self._enable_group_attributes()
696
697 @property
698 def spikes(self):
699 """
700 The spikes returned by the most recent thresholding operation.
701 """
702 # Note that we have to directly access the ArrayVariable object here
703 # instead of using the Group mechanism by accessing self._spikespace
704 # Using the latter would cut _spikespace to the length of the group
705 spikespace = self.variables["_spikespace"].get_value()
706 return spikespace[: spikespace[-1]]
707
708 def state(self, name, use_units=True, level=0):
709 try:
710 return Group.state(self, name, use_units=use_units, level=level + 1)
711 except KeyError as ex:
712 if name in self._linked_variables:
713 raise TypeError(
714 f"Link target for variable {name} has not been set."
715 ) from ex
716 else:
717 raise ex
718
719 def run_on_event(self, event, code, when="after_resets", order=None):
720 """
721 Run code triggered by a custom-defined event (see `NeuronGroup`
722 documentation for the specification of events).The created `Resetter`
723 object will be automatically added to the group, it therefore does not
724 need to be added to the network manually. However, a reference to the
725 object will be returned, which can be used to later remove it from the
726 group or to set it to inactive.
727
728 Parameters
729 ----------
730 event : str
731 The name of the event that should trigger the code
732 code : str
733 The code that should be executed
734 when : str, optional
735 The scheduling slot that should be used to execute the code.
736 Defaults to `'after_resets'`. See :ref:`scheduling` for possible values.
737 order : int, optional
738 The order for operations in the same scheduling slot. Defaults to
739 the order of the `NeuronGroup`.
740
741 Returns
742 -------
743 obj : `Resetter`
744 A reference to the object that will be run.
745 """
746 if event not in self.events:
747 error_message = f"Unknown event '{event}'."
748 if event == "spike":
749 error_message += " Did you forget to define a threshold?"
750 raise ValueError(error_message)
751 if event in self.resetter:
752 raise ValueError(
753 "Cannot add code for event '%s', code for this "
754 "event has already been added." % event
755 )
756 self.event_codes[event] = code
757 resetter = Resetter(self, when=when, order=order, event=event)
758 self.resetter[event] = resetter
759 self.contained_objects.append(resetter)
760
761 return resetter
762
763 def set_event_schedule(self, event, when="after_thresholds", order=None):
764 """
765 Change the scheduling slot for checking the condition of an event.
766
767 Parameters
768 ----------
769 event : str
770 The name of the event for which the scheduling should be changed
771 when : str, optional
772 The scheduling slot that should be used to check the condition.
773 Defaults to `'after_thresholds'`. See :ref:`scheduling` for possible values.
774 order : int, optional
775 The order for operations in the same scheduling slot. Defaults to
776 the order of the `NeuronGroup`.
777 """
778 if event not in self.thresholder:
779 raise ValueError(f"Unknown event '{event}'.")
780 order = order if order is not None else self.order
781 self.thresholder[event].when = when
782 self.thresholder[event].order = order
783
784 def __getitem__(self, item):
785 start, stop = to_start_stop(item, self._N)
786
787 return Subgroup(self, start, stop)
788
789 def _create_variables(self, user_dtype, events):
790 """
791 Create the variables dictionary for this `NeuronGroup`, containing
792 entries for the equation variables and some standard entries.
793 """
794 self.variables = Variables(self)
795 self.variables.add_constant("N", self._N)
796
797 # Standard variables always present
798 for event in events:
799 self.variables.add_array(
800 f"_{event}space", size=self._N + 1, dtype=np.int32, constant=False
801 )
802 # Add the special variable "i" which can be used to refer to the neuron index
803 self.variables.add_arange("i", size=self._N, constant=True, read_only=True)
804 # Add the clock variables
805 self.variables.create_clock_variables(self._clock)
806
807 for eq in self.equations.values():
808 dtype = get_dtype(eq, user_dtype)
809 check_identifier_pre_post(eq.varname)
810 if eq.type in (DIFFERENTIAL_EQUATION, PARAMETER):
811 if "linked" in eq.flags:
812 # 'linked' cannot be combined with other flags
813 if not len(eq.flags) == 1:
814 raise SyntaxError(
815 "The 'linked' flag cannot be combined with other flags"
816 )
817 self._linked_variables.add(eq.varname)
818 else:
819 constant = "constant" in eq.flags
820 shared = "shared" in eq.flags
821 size = 1 if shared else self._N
822 self.variables.add_array(
823 eq.varname,
824 size=size,
825 dimensions=eq.dim,
826 dtype=dtype,
827 constant=constant,
828 scalar=shared,
829 )
830 elif eq.type == SUBEXPRESSION:
831 self.variables.add_subexpression(
832 eq.varname,
833 dimensions=eq.dim,
834 expr=str(eq.expr),
835 dtype=dtype,
836 scalar="shared" in eq.flags,
837 )
838 else:
839 raise AssertionError(f"Unknown type of equation: {eq.eq_type}")
840
841 # Add the conditional-write attribute for variables with the
842 # "unless refractory" flag
843 if self._refractory is not False:
844 for eq in self.equations.values():
845 if eq.type == DIFFERENTIAL_EQUATION and "unless refractory" in eq.flags:
846 not_refractory_var = self.variables["not_refractory"]
847 var = self.variables[eq.varname]
848 var.set_conditional_write(not_refractory_var)
849
850 # Stochastic variables
851 for xi in self.equations.stochastic_variables:
852 self.variables.add_auxiliary_variable(xi, dimensions=(second**-0.5).dim)
853
854 # Check scalar subexpressions
855 for eq in self.equations.values():
856 if eq.type == SUBEXPRESSION and "shared" in eq.flags:
857 var = self.variables[eq.varname]
858 for identifier in var.identifiers:
859 if identifier in self.variables:
860 if not self.variables[identifier].scalar:
861 raise SyntaxError(
862 f"Shared subexpression '{eq.varname}' "
863 "refers to non-shared variable "
864 f"'{identifier}'."
865 )
866
867 def before_run(self, run_namespace=None):
868 # Check units
869 self.equations.check_units(self, run_namespace=run_namespace)
870 # Check that subexpressions that refer to stateful functions are labeled
871 # as "constant over dt"
872 check_subexpressions(self, self.equations, run_namespace)
873 super().before_run(run_namespace=run_namespace)
874
875 def _repr_html_(self):
876 text = [rf"NeuronGroup '{self.name}' with {self._N} neurons.<br>"]
877 text.append(r"<b>Model:</b><nr>")
878 text.append(sympy.latex(self.equations))
879
880 def add_event_to_text(event):
881 if event == "spike":
882 event_header = "Spiking behaviour"
883 event_condition = "Threshold condition"
884 event_code = "Reset statement(s)"
885 else:
886 event_header = f'Event "{event}"'
887 event_condition = "Event condition"
888 event_code = "Executed statement(s)"
889 condition = self.events[event]
890 text.append(
891 rf'<b>{event_header}:</b><ul style="list-style-type: none; margin-top:'
892 r' 0px;">'
893 )
894 text.append(rf"<li><i>{event_condition}: </i>")
895 text.append(f"<code>{str(condition)}</code></li>")
896 statements = self.event_codes.get(event, None)
897 if statements is not None:
898 text.append(rf"<li><i>{event_code}:</i>")
899 if "\n" in str(statements):
900 text.append("</br>")
901 text.append(rf"<code>{str(statements)}</code></li>")
902 text.append("</ul>")
903
904 if "spike" in self.events:
905 add_event_to_text("spike")
906 for event in self.events:
907 if event != "spike":
908 add_event_to_text(event)
909
910 return "\n".join(text)