Debian Codegraph @

brian2/synapses/synapses.py

raw
1 """
2 Module providing the `Synapses` class and related helper classes/functions.
3 """
4
5 import functools
6 import numbers
7 import re
8 import weakref
9 from collections import defaultdict
10 from collections.abc import Mapping, MutableMapping, Sequence
11
12 import numpy as np
13
14 from brian2.codegen.codeobject import create_runner_codeobj
15 from brian2.codegen.translation import get_identifiers_recursively
16 from brian2.core.base import device_override, weakproxy_with_fallback
17 from brian2.core.namespace import get_local_namespace
18 from brian2.core.spikesource import SpikeSource
19 from brian2.core.variables import DynamicArrayVariable, Variables
20 from brian2.devices.device import get_device
21 from brian2.equations.equations import (
22 DIFFERENTIAL_EQUATION,
23 PARAMETER,
24 SUBEXPRESSION,
25 EquationError,
26 Equations,
27 check_subexpressions,
28 )
29 from brian2.groups.group import CodeRunner, Group, get_dtype
30 from brian2.groups.neurongroup import (
31 SubexpressionUpdater,
32 check_identifier_pre_post,
33 extract_constant_subexpressions,
34 )
35 from brian2.parsing.bast import brian_ast
36 from brian2.parsing.expressions import (
37 is_boolean_expression,
38 parse_expression_dimensions,
39 )
40 from brian2.parsing.rendering import NodeRenderer
41 from brian2.stateupdaters.base import StateUpdateMethod, UnsupportedEquationsException
42 from brian2.stateupdaters.exact import linear
43 from brian2.synapses.parse_synaptic_generator_syntax import parse_synapse_generator
44 from brian2.units.allunits import second
45 from brian2.units.fundamentalunits import (
46 DIMENSIONLESS,
47 DimensionMismatchError,
48 Quantity,
49 fail_for_dimension_mismatch,
50 )
51 from brian2.utils.arrays import calc_repeats
52 from brian2.utils.logger import get_logger
53 from brian2.utils.stringtools import get_identifiers, word_substitute
54
55 MAX_SYNAPSES = 2147483647
56
57 __all__ = ["Synapses"]
58
59 logger = get_logger(__name__)
60
61
62 class StateUpdater(CodeRunner):
63 """
64 The `CodeRunner` that updates the state variables of a `Synapses`
65 at every timestep.
66 """
67
68 def __init__(self, group, method, clock, order, method_options=None):
69 self.method_choice = method
70 self.method_options = method_options
71 CodeRunner.__init__(
72 self,
73 group,
74 "stateupdate",
75 clock=clock,
76 when="groups",
77 order=order,
78 name=group.name + "_stateupdater",
79 check_units=False,
80 generate_empty_code=False,
81 )
82
83 def update_abstract_code(self, run_namespace):
84 if len(self.group.equations) > 0:
85 # Resolve variables in the equations to correctly perform checks
86 # for repeated stateful functions (e.g. rand() calls)
87 names = self.group.equations.names
88 external_names = self.group.equations.identifiers | {"dt"}
89
90 variables = self.group.resolve_all(
91 names | external_names,
92 run_namespace,
93 # we don't need to raise any warnings
94 # for the user here, warnings will
95 # be raised in create_runner_codeobj
96 user_identifiers=set(),
97 )
98 stateupdate_output = StateUpdateMethod.apply_stateupdater(
99 self.group.equations,
100 variables,
101 self.method_choice,
102 method_options=self.method_options,
103 group_name=self.group.name,
104 )
105 if isinstance(stateupdate_output, str):
106 self.abstract_code = stateupdate_output
107 else:
108 # Note that the reason to send self along with this method is so the StateUpdater
109 # can be modified! i.e. in GSL StateUpdateMethod a custom CodeObject gets added
110 # to the StateUpdater together with some auxiliary information
111 self.abstract_code = stateupdate_output(self)
112 else:
113 self.abstract_code = ""
114
115
116 class SummedVariableUpdater(CodeRunner):
117 """
118 The `CodeRunner` that updates a value in the target group with the
119 sum over values in the `Synapses` object.
120 """
121
122 def __init__(
123 self, expression, target_varname, synapses, target, target_size_name, index_var
124 ):
125 # Handling sumped variables using the standard mechanisms is not
126 # possible, we therefore also directly give the names of the arrays
127 # to the template.
128
129 code = f"""
130 _synaptic_var = {expression}
131 """
132 self.target_varname = target_varname
133 self.expression = expression
134 self.target_var = synapses.variables[target_varname]
135 self.target = target
136 template_kwds = {
137 "_target_var": self.target_var,
138 "_target_size_name": target_size_name,
139 "_index_var": synapses.variables[index_var],
140 "_target_start": getattr(target, "start", 0),
141 "_target_stop": getattr(target, "stop", -1),
142 }
143
144 CodeRunner.__init__(
145 self,
146 group=synapses,
147 template="summed_variable",
148 code=code,
149 needed_variables=[target_varname, target_size_name, index_var],
150 # We want to update the summed variable before
151 # the target group gets updated
152 clock=target.clock,
153 when="groups",
154 order=target.order - 1,
155 name=synapses.name + "_summed_variable_" + target_varname,
156 template_kwds=template_kwds,
157 )
158
159 def before_run(self, run_namespace):
160 variables = self.group.resolve_all(self.expression.identifiers, run_namespace)
161 rhs_unit = parse_expression_dimensions(self.expression.code, variables)
162 fail_for_dimension_mismatch(
163 self.target_var,
164 # Using a quantity instead of dimensions
165 # here makes fail_for_dimension_mismatch
166 # state the dimensions as part of the error
167 # message
168 Quantity(1, dim=rhs_unit),
169 "The target variable "
170 f"'{self.target_varname}' does not have "
171 "the same dimensions as the right-hand "
172 f"side expression '{self.expression}'.",
173 )
174 super().before_run(run_namespace)
175
176
177 class SynapticPathway(CodeRunner, Group):
178 """
179 The `CodeRunner` that applies the pre/post statement(s) to the state
180 variables of synapses where the pre-/postsynaptic group spiked in this
181 time step.
182
183 Parameters
184 ----------
185
186 synapses : `Synapses`
187 Reference to the main `Synapses` object
188 prepost : {'pre', 'post'}
189 Whether this object should react to pre- or postsynaptic spikes
190 objname : str, optional
191 The name to use for the object, will be appendend to the name of
192 `synapses` to create a name in the sense of `Nameable`. If ``None``
193 is provided (the default), ``prepost`` will be used.
194 delay : `Quantity`, optional
195 A scalar delay (same delay for all synapses) for this pathway. If
196 not given, delays are expected to vary between synapses.
197 """
198
199 def __init__(
200 self, synapses, code, prepost, objname=None, delay=None, event="spike"
201 ):
202 self.code = code
203 self.prepost = prepost
204 self.event = event
205 if prepost == "pre":
206 self.source = synapses.source
207 self.target = synapses.target
208 self.synapse_sources = synapses.variables["_synaptic_pre"]
209 self.synapse_targets = synapses.variables["_synaptic_post"]
210 order = -1
211 elif prepost == "post":
212 self.source = synapses.target
213 self.target = synapses.source
214 self.synapse_sources = synapses.variables["_synaptic_post"]
215 self.synapse_targets = synapses.variables["_synaptic_pre"]
216 order = 1
217 else:
218 raise ValueError("prepost argument has to be either 'pre' or 'post'")
219 self.synapses = weakref.proxy(synapses)
220 # Allow to use the same indexing of the delay variable as in the parent
221 # Synapses object (e.g. 2d indexing with pre- and post-synaptic indices)
222 self._indices = self.synapses._indices
223
224 if objname is None:
225 objname = prepost
226
227 CodeRunner.__init__(
228 self,
229 synapses,
230 "synapses",
231 code=code,
232 clock=self.source.clock,
233 when="synapses",
234 order=order,
235 name=synapses.name + "_" + objname,
236 template_kwds={"pathway": self},
237 )
238
239 self._pushspikes_codeobj = None
240
241 self.spikes_start = self.source.start
242 self.spikes_stop = self.source.stop
243 self.eventspace_name = f"_{event}space"
244 self.eventspace = None # will be set in before_run
245 # Setting the Synapses object instead of "self" as an owner makes
246 # indexing conflicts disappear (e.g. with synapses connecting subgroups)
247 self.variables = Variables(synapses)
248 self.variables.add_reference(self.eventspace_name, self.source)
249 self.variables.add_reference("N", synapses)
250 if prepost == "pre":
251 self.variables.add_reference("_n_sources", synapses, "N_pre")
252 self.variables.add_reference("_n_targets", synapses, "N_post")
253 self.variables.add_reference("_source_dt", synapses.source, "dt")
254 else:
255 self.variables.add_reference("_n_sources", synapses, "N_post")
256 self.variables.add_reference("_n_targets", synapses, "N_pre")
257 self.variables.add_reference("_source_dt", synapses.target, "dt")
258 if delay is None: # variable delays
259 if getattr(synapses, "N", None) is not None:
260 n_synapses = synapses.N
261 else:
262 n_synapses = 0
263 self.variables.add_dynamic_array(
264 "delay", dimensions=second.dim, size=n_synapses, constant=True
265 )
266 # Register the object with the `SynapticIndex` object so it gets
267 # automatically resized
268 synapses.register_variable(self.variables["delay"])
269 else:
270 if not isinstance(delay, Quantity):
271 raise TypeError(
272 f"Cannot set the delay for pathway '{objname}': "
273 f"expected a quantity, got {type(delay)} instead."
274 )
275 if delay.size != 1:
276 raise TypeError(
277 f"Cannot set the delay for pathway '{objname}': "
278 "expected a scalar quantity, got a "
279 f"quantity with shape {delay.shape!s} instead."
280 )
281 fail_for_dimension_mismatch(
282 delay,
283 second,
284 "Delay has to be specified in units of seconds but got {value}",
285 value=delay,
286 )
287 # We use a "dynamic" array of constant size here because it makes
288 # the generated code easier, we don't need to deal with a different
289 # type for scalar and variable delays
290 self.variables.add_dynamic_array(
291 "delay", dimensions=second.dim, size=1, constant=True, scalar=True
292 )
293 # Since this array does not grow with the number of synapses, we
294 # have to resize it ourselves
295 self.variables["delay"].resize(1)
296 self.variables["delay"].set_value(delay)
297
298 self._delays = self.variables["delay"]
299
300 # Re-extract the last part of the name from the full name
301 self.objname = self.name[len(synapses.name) + 1 :]
302
303 #: The `CodeObject` initalising the `SpikeQueue` at the begin of a run
304 self._initialise_queue_codeobj = None
305
306 self.namespace = synapses.namespace
307
308 # Allow the use of string expressions referring to synaptic (including
309 # pre-/post-synaptic) variables
310 # Only include non-private variables (and their indices)
311 synaptic_vars = {
312 varname
313 for varname in list(synapses.variables)
314 if not varname.startswith("_")
315 }
316 synaptic_idcs = {
317 varname: synapses.variables.indices[varname] for varname in synaptic_vars
318 }
319 synaptic_vars |= {
320 index_name
321 for index_name in synaptic_idcs.values()
322 if index_name not in ["_idx", "0"]
323 }
324 self.variables.add_references(synapses, synaptic_vars)
325 self.variables.indices.update(synaptic_idcs)
326
327 #: The `SpikeQueue`
328 self.queue = get_device().spike_queue(self.source.start, self.source.stop)
329 self.variables.add_object("_queue", self.queue)
330
331 if self.queue: # when using RuntimeDevice
332 self.variables.add_object(
333 "_queue_capsule",
334 self.queue.get_capsule(), # Wrapped C++ pointer in a PyCapsule
335 )
336
337 self._enable_group_attributes()
338
339 def check_variable_write(self, variable):
340 # Forward the check to the `Synapses` object (raises an error if no
341 # synapse has been created yet)
342 self.synapses.check_variable_write(variable)
343
344 @device_override("synaptic_pathway_update_abstract_code")
345 def update_abstract_code(self, run_namespace=None, level=0):
346 if self.synapses.event_driven is not None:
347 event_driven_eqs = self.synapses.event_driven
348 try:
349 event_driven_update = linear(event_driven_eqs, self.group.variables)
350 except UnsupportedEquationsException as ex:
351 err = (
352 "Cannot solve the differential equations as "
353 "event-driven. Use (clock-driven) instead."
354 )
355 raise UnsupportedEquationsException(err) from ex
356
357 # TODO: Any way to do this more elegantly?
358 event_driven_update = re.sub(
359 r"\bdt\b", "(t - lastupdate)", event_driven_update
360 )
361
362 self.abstract_code = event_driven_update + "\n"
363 else:
364 self.abstract_code = ""
365
366 self.abstract_code += self.code + "\n"
367 if self.synapses.event_driven is not None:
368 self.abstract_code += "lastupdate = t\n"
369
370 @device_override("synaptic_pathway_before_run")
371 def before_run(self, run_namespace):
372 super().before_run(run_namespace)
373
374 def create_code_objects(self, run_namespace):
375 if self._pushspikes_codeobj is None:
376 # Since this now works for general events not only spikes, we have to
377 # pass the information about which variable to use to the template,
378 # it can not longer simply refer to "_spikespace"
379 # Strictly speaking this is only true for the standalone mode at the
380 # moment, since in runtime, all the template does is to call
381 # SynapticPathway.push_spike
382 eventspace_name = f"_{self.event}space"
383 template_kwds = {
384 # Standard Brian2 variable for spike event data
385 # This provides access to the spike array in the generated Cython code
386 "eventspace_variable": self.source.variables[eventspace_name],
387 }
388 needed_variables = [eventspace_name]
389
390 self._pushspikes_codeobj = create_runner_codeobj(
391 self,
392 "", # no code
393 "synapses_push_spikes",
394 name=self.name + "_push_spikes",
395 check_units=False,
396 additional_variables=self.variables,
397 needed_variables=needed_variables,
398 template_kwds=template_kwds,
399 run_namespace=run_namespace,
400 )
401 self.code_objects[:] = [
402 weakref.proxy(self._pushspikes_codeobj),
403 weakref.proxy(self.create_default_code_object(run_namespace)),
404 ]
405
406 def initialise_queue(self):
407 self.eventspace = self.source.variables[self.eventspace_name].get_value()
408
409 n_synapses = len(self.synapses)
410 if n_synapses == 0 and not self.synapses._connect_called:
411 raise TypeError(
412 "Synapses object '%s' does not do anything, since "
413 "it has not created synapses with 'connect'. "
414 "Set its active attribute to False if you "
415 "intend to do only do this for a subsequent"
416 " run." % self.synapses.name
417 )
418
419 # Update the dt (might have changed between runs)
420 self.queue.prepare(
421 self._delays.get_value(),
422 self.source.clock.dt_,
423 self.synapse_sources.get_value(),
424 )
425
426 if (
427 len({self.source.clock.dt_, self.synapses.clock.dt_, self.target.clock.dt_})
428 > 1
429 ):
430 logger.warn(
431 f"Note that the synaptic pathway '{self.name}' will run on the "
432 f"clock of the group '{self.source.name}' using a dt of "
433 f"{self.source.clock.dt}. Either the Synapses object "
434 f"'{self.synapses.name}' or the target '{self.target.name}' "
435 "(or both) are using a different dt. This might lead to "
436 "unexpected results. In particular, all delays will be "
437 f"rounded to multiples of {self.source.clock.dt}. If in "
438 f"doubt, try to ensure that '{self.source.name}', "
439 f"'{self.synapses.name}', and '{self.target.name}' use the "
440 "same dt.",
441 "synapses_dt_mismatch",
442 once=True,
443 )
444
445 def _full_state(self):
446 state = super()._full_state()
447 if self.queue is not None:
448 state["_spikequeue"] = self.queue._full_state()
449 else:
450 state["_spikequeue"] = None
451 delay_var = self.variables["delay"]
452 state["delay"] = (np.array(delay_var.get_value(), copy=True), delay_var.size)
453 return state
454
455 def _restore_from_full_state(self, state):
456 # We have to handle the SpikeQueue and delays separately from the other state
457 # variables, so remove it from the state dictionary so that it does not
458 # get treated as a state variable by the standard mechanism in
459 # `VariableOwner`
460 queue_state = state.pop("_spikequeue")
461 if "delay" in state:
462 delay_state = state.pop("delay")
463 else: # for backwards compatibility with old stored pickle files
464 delay_state = None
465 super()._restore_from_full_state(state)
466 if self.queue is None:
467 self.queue = get_device().spike_queue(self.source.start, self.source.stop)
468
469 converted_queue_state = self._convert_queue_state_if_needed(queue_state)
470 self.queue._restore_from_full_state(converted_queue_state)
471
472 if delay_state:
473 self.variables["delay"].resize(delay_state[1])
474 self.variables["delay"].set_value(delay_state[0])
475 state["delay"] = delay_state
476
477 state["_spikequeue"] = queue_state
478
479 def _convert_queue_state_if_needed(self, queue_state):
480 """
481 Convert spike queue state from Python format to Cython format if needed.
482
483 Python format: (time, spike_indices_array, queue_capacities)
484 Cython format: (offset, list_of_spike_lists)
485
486 Returns the queue_state in Cython format.
487 """
488 # Check if this is the old Python format (3-tuple vs 2-tuple) , also note this is sort of a hack
489 # As it's completely based on Python format being a 3 tuple ...
490 if isinstance(queue_state, tuple) and len(queue_state) == 3:
491 # This is Python spike queue format, need to convert
492 return self._python_to_cython_format(queue_state)
493 else:
494 return queue_state
495
496 def _python_to_cython_format(self, python_state):
497 """
498 Convert Python spike queue format to Cython format.
499
500 Python format: (current_time, spike_array, queue_sizes)
501 - current_time: float representing current simulation time
502 - spike_array: 2D array where spike_array[delay_slot][spike_index] = neuron_id
503 - queue_sizes: tuple of queue capacities
504
505 Cython format: (offset, spike_lists)
506 - offset: int representing current position in circular buffer
507 - spike_lists: list of lists, where spike_lists[i] contains spikes for time slot i
508 """
509 _, spike_array, __ = python_state
510
511 if not spike_array.any():
512 return (0, [])
513
514 # The first column contains the delay slots, the second the snyapse indexes that would be triggered
515 delay_slots = spike_array[:, 0]
516 synapse_indexes = spike_array[:, 1]
517
518 # Now we'll determine the size of the new queue by the maximum delay
519 max_delay = np.max(delay_slots)
520 new_queue = [[] for _ in range(max_delay + 1)]
521
522 for delay, synapse_idx in zip(delay_slots, synapse_indexes, strict=True):
523 new_queue[delay].append(synapse_idx)
524
525 # The offset in Cython format represents the current position in the circular buffer
526 # For a newly converted queue, we typically start at offset 0
527 offset = 0
528 return (offset, new_queue)
529
530 def push_spikes(self):
531 # Push new events (e.g. spikes) into the queue
532 events = self.eventspace[: self.eventspace[len(self.eventspace) - 1]]
533
534 if len(events):
535 self.queue.push(events)
536
537
538 def slice_to_test(x):
539 """
540 Returns a testing function corresponding to whether an index is in slice x.
541 x can also be an int.
542 """
543 try:
544 x = int(x)
545 return lambda y: (y == x)
546 except TypeError:
547 pass
548
549 if isinstance(x, slice):
550 if isinstance(x, slice) and x == slice(None):
551 # No need for testing
552 return lambda y: np.repeat(True, len(y))
553 start, stop, step = x.start, x.stop, x.step
554
555 if start is None:
556 # No need to test for >= start
557 if step is None:
558 # Only have a stop value
559 return lambda y: (y < stop)
560 else:
561 # Stop and step
562 return lambda y: (y < stop) & ((y % step) == 0)
563 else:
564 # We need to test for >= start
565 if step is None:
566 if stop is None:
567 # Only a start value
568 return lambda y: (y >= start)
569 else:
570 # Start and stop
571 return lambda y: (y >= start) & (y < stop)
572 else:
573 if stop is None:
574 # Start and step value
575 return lambda y: (y >= start) & ((y - start) % step == 0)
576 else:
577 # Start, step and stop
578 return (
579 lambda y: (y >= start) & ((y - start) % step == 0) & (y < stop)
580 )
581 else:
582 raise TypeError(f"Expected int or slice, got {type(x)} instead")
583
584
585 def find_synapses(index, synaptic_neuron):
586 try:
587 index = index.item()
588 except (TypeError, ValueError):
589 pass
590
591 if isinstance(index, (int, slice)):
592 test = slice_to_test(index)
593 found = test(synaptic_neuron)
594 synapses = np.flatnonzero(found)
595 else:
596 synapses = []
597 for neuron in index:
598 targets = np.flatnonzero(synaptic_neuron == neuron)
599 synapses.extend(targets)
600 synapses = np.array(synapses, dtype=np.int32)
601
602 return synapses
603
604
605 class SynapticSubgroup:
606 """
607 A simple subgroup of `Synapses` that can be used for indexing.
608
609 Parameters
610 ----------
611 indices : `ndarray` of int
612 The synaptic indices represented by this subgroup.
613 synaptic_pre : `DynamicArrayVariable`
614 References to all pre-synaptic indices. Only used to throw an error
615 when new synapses where added after creating this object.
616 """
617
618 def __init__(self, synapses, indices):
619 self.synapses = weakproxy_with_fallback(synapses)
620 self._stored_indices = indices
621 self._synaptic_pre = synapses.variables["_synaptic_pre"]
622 self._source_N = self._synaptic_pre.size # total number of synapses
623
624 def _indices(self, index_var="_idx"):
625 if index_var != "_idx":
626 raise AssertionError(f"Did not expect index {index_var} here.")
627 if len(self._synaptic_pre.get_value()) != self._source_N:
628 raise RuntimeError(
629 "Synapses have been added/removed since this "
630 "synaptic subgroup has been created"
631 )
632 return self._stored_indices
633
634 def __len__(self):
635 return len(self._stored_indices)
636
637 def __repr__(self):
638 return (
639 f"<{self.__class__.__name__}, storing {len(self._stored_indices):d} "
640 f"indices of {self.synapses.name}>"
641 )
642
643
644 class SynapticIndexing:
645 def __init__(self, synapses):
646 self.synapses = weakref.proxy(synapses)
647 self.source = weakproxy_with_fallback(self.synapses.source)
648 self.target = weakproxy_with_fallback(self.synapses.target)
649 self.synaptic_pre = synapses.variables["_synaptic_pre"]
650 self.synaptic_post = synapses.variables["_synaptic_post"]
651 if synapses.multisynaptic_index is not None:
652 self.synapse_number = synapses.variables[synapses.multisynaptic_index]
653 else:
654 self.synapse_number = None
655
656 def __call__(self, index=None, index_var="_idx"):
657 """
658 Returns synaptic indices for `index`, which can be a tuple of indices
659 (including arrays and slices), a single index or a string.
660
661 """
662 if index is None or (isinstance(index, str) and index == "True"):
663 index = slice(None)
664
665 if not isinstance(index, (tuple, str)) and (
666 isinstance(index, (numbers.Integral, np.ndarray, slice, Sequence))
667 or hasattr(index, "_indices")
668 ):
669 if hasattr(index, "_indices"):
670 final_indices = index._indices(index_var=index_var).astype(np.int32)
671 elif isinstance(index, slice):
672 start, stop, step = index.indices(len(self.synaptic_pre.get_value()))
673 final_indices = np.arange(start, stop, step, dtype=np.int32)
674 else:
675 final_indices = np.asarray(index)
676 elif isinstance(index, tuple):
677 if len(index) == 2: # two indices (pre- and postsynaptic cell)
678 index = (index[0], index[1], slice(None))
679 elif len(index) > 3:
680 raise IndexError(f"Need 1, 2 or 3 indices, got {len(index)}.")
681
682 i_indices, j_indices, k_indices = index
683 # Convert to absolute indices (e.g. for subgroups)
684 # Allow the indexing to fail, we'll later return an empty array in
685 # that case
686 try:
687 if hasattr(
688 i_indices, "_indices"
689 ): # will return absolute indices already
690 i_indices = i_indices._indices()
691 else:
692 i_indices = self.source._indices(i_indices)
693 pre_synapses = find_synapses(i_indices, self.synaptic_pre.get_value())
694 except IndexError:
695 pre_synapses = np.array([], dtype=np.int32)
696 try:
697 if hasattr(j_indices, "_indices"):
698 j_indices = j_indices._indices()
699 else:
700 j_indices = self.target._indices(j_indices)
701 post_synapses = find_synapses(j_indices, self.synaptic_post.get_value())
702 except IndexError:
703 post_synapses = np.array([], dtype=np.int32)
704
705 matching_synapses = np.intersect1d(
706 pre_synapses, post_synapses, assume_unique=True
707 )
708
709 if isinstance(k_indices, slice) and k_indices == slice(None):
710 final_indices = matching_synapses
711 else:
712 if self.synapse_number is None:
713 raise IndexError(
714 "To index by the third dimension you need "
715 "to switch on the calculation of the "
716 "'multisynaptic_index' when you create "
717 "the Synapses object."
718 )
719 if isinstance(k_indices, (numbers.Integral, slice)):
720 test_k = slice_to_test(k_indices)
721 else:
722 raise NotImplementedError(
723 "Indexing synapses with arrays notimplemented yet"
724 )
725
726 # We want to access the raw arrays here, not go through the Variable
727 synapse_numbers = self.synapse_number.get_value()[matching_synapses]
728 final_indices = np.intersect1d(
729 matching_synapses,
730 np.flatnonzero(test_k(synapse_numbers)),
731 assume_unique=True,
732 )
733 else:
734 raise IndexError(f"Unsupported index type {type(index)}")
735
736 if index_var not in ("_idx", "0"):
737 return index_var.get_value()[final_indices.astype(np.int32)]
738 else:
739 return final_indices.astype(np.int32)
740
741
742 class Synapses(Group):
743 """
744 Class representing synaptic connections.
745
746 Creating a new `Synapses` object does by default not create any synapses,
747 you have to call the `Synapses.connect` method for that.
748
749 Parameters
750 ----------
751
752 source : `SpikeSource`
753 The source of spikes, e.g. a `NeuronGroup`.
754 target : `Group`, optional
755 The target of the spikes, typically a `NeuronGroup`. If none is given,
756 the same as `source`
757 model : `str`, `Equations`, optional
758 The model equations for the synapses.
759 on_pre : str, dict, optional
760 The code that will be executed after every pre-synaptic spike. Can be
761 either a single (possibly multi-line) string, or a dictionary mapping
762 pathway names to code strings. In the first case, the pathway will be
763 called ``pre`` and made available as an attribute of the same name.
764 In the latter case, the given names will be used as the
765 pathway/attribute names. Each pathway has its own code and its own
766 delays.
767 pre : str, dict, optional
768 Deprecated. Use ``on_pre`` instead.
769 on_post : str, dict, optional
770 The code that will be executed after every post-synaptic spike. Same
771 conventions as for `on_pre``, the default name for the pathway is
772 ``post``.
773 post : str, dict, optional
774 Deprecated. Use ``on_post`` instead.
775 delay : `Quantity`, dict, optional
776 The delay for the "pre" pathway (same for all synapses) or a dictionary
777 mapping pathway names to delays. If a delay is specified in this way
778 for a pathway, it is stored as a single scalar value. It can still
779 be changed afterwards, but only to a single scalar value. If you want
780 to have delays that vary across synapses, do not use the keyword
781 argument, but instead set the delays via the attribute of the pathway,
782 e.g. ``S.pre.delay = ...`` (or ``S.delay = ...`` as an abbreviation),
783 ``S.post.delay = ...``, etc.
784 on_event : str or dict, optional
785 Define the events which trigger the pre and post pathways. By default,
786 both pathways are triggered by the ``'spike'`` event, i.e. the event
787 that is triggered by the ``threshold`` condition in the connected
788 groups.
789 multisynaptic_index : str, optional
790 The name of a variable (which will be automatically created) that stores
791 the "synapse number". This number enumerates all synapses between the
792 same source and target so that they can be distinguished. For models
793 where each source-target pair has only a single connection, this number
794 only wastes memory (it would always default to 0), it is therefore not
795 stored by default. Defaults to ``None`` (no variable).
796 namespace : dict, optional
797 A dictionary mapping identifier names to objects. If not given, the
798 namespace will be filled in at the time of the call of `Network.run`,
799 with either the values from the ``namespace`` argument of the
800 `Network.run` method or from the local context, if no such argument is
801 given.
802 dtype : `dtype`, dict, optional
803 The `numpy.dtype` that will be used to store the values, or a
804 dictionary specifying the type for variable names. If a value is not
805 provided for a variable (or no value is provided at all), the preference
806 setting `core.default_float_dtype` is used.
807 codeobj_class : class, optional
808 The `CodeObject` class to use to run code.
809 dt : `Quantity`, optional
810 The time step to be used for the update of the state variables.
811 Cannot be combined with the `clock` argument.
812 clock : `Clock`, optional
813 The update clock to be used. If neither a clock, nor the `dt` argument
814 is specified, the `defaultclock` will be used.
815 order : int, optional
816 The priority of of this group for operations occurring at the same time
817 step and in the same scheduling slot. Defaults to 0.
818 method : str, `StateUpdateMethod`, optional
819 The numerical integration method to use. If none is given, an
820 appropriate one is automatically determined.
821 name : str, optional
822 The name for this object. If none is given, a unique name of the form
823 ``synapses``, ``synapses_1``, etc. will be automatically chosen.
824 """
825
826 add_to_magic_network = True
827
828 def __init__(
829 self,
830 source,
831 target=None,
832 model=None,
833 on_pre=None,
834 pre=None,
835 on_post=None,
836 post=None,
837 connect=None,
838 delay=None,
839 on_event="spike",
840 multisynaptic_index=None,
841 namespace=None,
842 dtype=None,
843 codeobj_class=None,
844 dt=None,
845 clock=None,
846 order=0,
847 method=("exact", "euler", "heun"),
848 method_options=None,
849 name="synapses*",
850 ):
851 if connect is not None:
852 raise TypeError(
853 "The connect keyword argument is no longer "
854 "supported, call the connect method instead."
855 )
856
857 if pre is not None:
858 if on_pre is not None:
859 raise TypeError(
860 "Cannot specify both 'pre' and 'on_pre'. The "
861 "'pre' keyword is deprecated, use the 'on_pre' "
862 "keyword instead."
863 )
864 logger.warn(
865 "The 'pre' keyword is deprecated, use 'on_pre' instead.",
866 "deprecated_pre",
867 once=True,
868 )
869 on_pre = pre
870
871 if post is not None:
872 if on_post is not None:
873 raise TypeError(
874 "Cannot specify both 'post' and 'on_post'. The "
875 "'post' keyword is deprecated, use the "
876 "'on_post' keyword instead."
877 )
878 logger.warn(
879 "The 'post' keyword is deprecated, use 'on_post' instead.",
880 "deprecated_post",
881 once=True,
882 )
883 on_post = post
884
885 Group.__init__(
886 self,
887 dt=dt,
888 clock=clock,
889 when="start",
890 order=order,
891 namespace=namespace,
892 name=name,
893 )
894
895 if dtype is None:
896 dtype = {}
897 if isinstance(dtype, MutableMapping):
898 dtype["lastupdate"] = self._clock.variables["t"].dtype
899
900 #: remember whether connect was called to raise an error if an
901 #: assignment to a synaptic variable is attempted without a preceding
902 #: connect.
903 self._connect_called = False
904 self.codeobj_class = codeobj_class
905
906 self.source = source
907 self.add_dependency(source)
908 if target is None:
909 self.target = self.source
910 else:
911 self.target = target
912 self.add_dependency(target)
913
914 ##### Prepare and validate equations
915 if model is None:
916 model = ""
917
918 if isinstance(model, str):
919 model = Equations(model)
920 if not isinstance(model, Equations):
921 raise TypeError(
922 "model has to be a string or an Equations "
923 f"object, is '{type(model)}' instead."
924 )
925
926 # Check flags
927 model.check_flags(
928 {
929 DIFFERENTIAL_EQUATION: ["event-driven", "clock-driven"],
930 SUBEXPRESSION: ["summed", "shared", "constant over dt"],
931 PARAMETER: ["constant", "shared", "linked"],
932 },
933 incompatible_flags=[
934 ("event-driven", "clock-driven"),
935 # 'summed' cannot be combined with
936 # any other flag
937 ("summed", "shared", "constant over dt"),
938 ],
939 )
940
941 for name in ["i", "j", "delay"]:
942 if name in model.names:
943 raise SyntaxError(
944 f"'{name}' is a reserved name that cannot be "
945 "used as a variable name."
946 )
947
948 # Add the "multisynaptic index", if desired
949 self.multisynaptic_index = multisynaptic_index
950 if multisynaptic_index is not None:
951 if not isinstance(multisynaptic_index, str):
952 raise TypeError("multisynaptic_index argument has to be a string")
953 model = model + Equations(f"{multisynaptic_index} : integer")
954
955 # Separate subexpressions depending whether they are considered to be
956 # constant over a time step or not
957 model, constant_over_dt = extract_constant_subexpressions(model)
958
959 # Separate the equations into event-driven equations,
960 # continuously updated equations and summed variable updates
961 event_driven = []
962 continuous = []
963 summed_updates = []
964 for single_equation in model.values():
965 if "event-driven" in single_equation.flags:
966 event_driven.append(single_equation)
967 elif "summed" in single_equation.flags:
968 summed_updates.append(single_equation)
969 else:
970 if (
971 single_equation.type == DIFFERENTIAL_EQUATION
972 and "clock-driven" not in single_equation.flags
973 ):
974 logger.info(
975 "The synaptic equation for the variable "
976 f"{single_equation.varname} does not specify whether it "
977 "should be integrated at every timestep ('clock-driven') "
978 "or only at spiking events ('event-driven'). It will be "
979 "integrated at every timestep which can slow down your "
980 "simulation unnecessarily if you only need the values of "
981 "this variable whenever a spike occurs. Specify the equation "
982 "as clock-driven explicitly to avoid this warning.",
983 "clock_driven",
984 once=True,
985 )
986 continuous.append(single_equation)
987 if single_equation.type != DIFFERENTIAL_EQUATION:
988 # General subexpressions (not summed variables) or
989 # parameters, might be referred from event-driven equations
990 # as well.
991 # Note that the code generation step will ignore them if
992 # nothing refers to them, so we don't have to filter here.
993 event_driven.append(single_equation)
994 # Get the dependencies of all equations
995 dependencies = model.dependencies
996
997 # Check whether there are dependencies between summed
998 # variables/clocked-driven equations and event-driven variables
999 for eq_name, deps in dependencies.items():
1000 eq = model[eq_name]
1001 if not (eq.type == DIFFERENTIAL_EQUATION or "summed" in eq.flags):
1002 continue
1003 if eq in continuous:
1004 Synapses.verify_dependencies(
1005 eq, "clock-driven", deps, event_driven, "event-driven"
1006 )
1007 elif "summed" in eq.flags:
1008 Synapses.verify_dependencies(
1009 eq, "summed", deps, event_driven, "event-driven"
1010 )
1011 elif eq in event_driven:
1012 Synapses.verify_dependencies(
1013 eq, "event-driven", deps, continuous, "clock-driven"
1014 )
1015
1016 if any(eq.type == DIFFERENTIAL_EQUATION for eq in event_driven):
1017 self.event_driven = Equations(event_driven)
1018 # Add the lastupdate variable, needed for event-driven updates
1019 model += Equations("lastupdate : second")
1020 else:
1021 self.event_driven = None
1022
1023 self._linked_variables = set()
1024
1025 self._create_variables(model, user_dtype=dtype)
1026 self.equations = Equations(continuous)
1027
1028 #: Set of `Variable` objects that should be resized when the
1029 #: number of synapses changes
1030 self._registered_variables = set()
1031
1032 for varname, var in self.variables.items():
1033 if (
1034 isinstance(var, DynamicArrayVariable)
1035 and self.variables.indices[varname] == "_idx"
1036 ):
1037 # Register the array with the `SynapticItemMapping` object so
1038 # it gets automatically resized
1039 self.register_variable(var)
1040
1041 # Support 2d indexing
1042 self._indices = SynapticIndexing(self)
1043
1044 if delay is None:
1045 delay = {}
1046
1047 if isinstance(delay, Quantity):
1048 delay = {"pre": delay}
1049 elif not isinstance(delay, Mapping):
1050 raise TypeError(
1051 "Delay argument has to be a quantity or a "
1052 f"dictionary, is type {type(delay)} instead."
1053 )
1054
1055 #: List of names of all updaters, e.g. ['pre', 'post']
1056 self._synaptic_updaters = []
1057 #: List of all `SynapticPathway` objects
1058 self._pathways = []
1059
1060 if isinstance(on_event, str):
1061 self.default_event = on_event
1062 events_dict = {}
1063 else:
1064 self.default_event = "spike"
1065 events_dict = dict(on_event)
1066
1067 #: "Events" for all the pathways
1068 self.events = events_dict
1069 for prepost, argument in zip(("pre", "post"), (on_pre, on_post), strict=True):
1070 if not argument:
1071 continue
1072 if isinstance(argument, str):
1073 pathway_delay = delay.get(prepost)
1074 self._add_updater(
1075 argument,
1076 prepost,
1077 delay=pathway_delay,
1078 event=self.events.get(prepost, self.default_event),
1079 )
1080 elif isinstance(argument, Mapping):
1081 for key, value in argument.items():
1082 if not isinstance(key, str):
1083 err_msg = (
1084 f"Keys for the 'on_{prepost}' argument"
1085 "have to be strings, got "
1086 f"{type(key)} instead."
1087 )
1088 raise TypeError(err_msg)
1089 pathway_delay = delay.get(key)
1090 self._add_updater(
1091 value,
1092 prepost,
1093 objname=key,
1094 delay=pathway_delay,
1095 event=self.events.get(key, self.default_event),
1096 )
1097
1098 # Check whether any delays were specified for pathways that don't exist
1099 for pathway in delay:
1100 if pathway not in self._synaptic_updaters:
1101 raise ValueError(
1102 f"Cannot set the delay for pathway '{pathway}': unknown pathway."
1103 )
1104
1105 #: Performs numerical integration step
1106 self.state_updater = None
1107
1108 # We only need a state update if we have differential equations
1109 if len(self.equations.diff_eq_names):
1110 self.state_updater = StateUpdater(
1111 self,
1112 method,
1113 method_options=method_options,
1114 clock=self.clock,
1115 order=order,
1116 )
1117 self.contained_objects.append(self.state_updater)
1118
1119 #: Update the "constant over a time step" subexpressions
1120 self.subexpression_updater = None
1121 if len(constant_over_dt) > 0:
1122 self.subexpression_updater = SubexpressionUpdater(self, constant_over_dt)
1123 self.contained_objects.append(self.subexpression_updater)
1124
1125 #: "Summed variable" mechanism -- sum over all synapses of a
1126 #: pre-/postsynaptic target
1127 self.summed_updaters = {}
1128 # We want to raise an error if the same variable is updated twice
1129 # using this mechanism. This could happen if the Synapses object
1130 # connected a NeuronGroup to itself since then all variables are
1131 # accessible as var_pre and var_post.
1132 summed_targets = set()
1133 for single_equation in summed_updates:
1134 varname = single_equation.varname
1135 if not (varname.endswith("_pre") or varname.endswith("_post")):
1136 raise ValueError(
1137 f"The summed variable '{varname}' does not end "
1138 "in '_pre' or '_post'."
1139 )
1140 if varname not in self.variables:
1141 raise ValueError(
1142 f"The summed variable '{varname}' does not refer "
1143 "to any known variable in the "
1144 "target group."
1145 )
1146 if varname.endswith("_pre"):
1147 summed_target = self.source
1148 summed_target_size_name = "N_pre"
1149 orig_varname = varname[:-4]
1150 summed_var_index = "_synaptic_pre"
1151 else:
1152 summed_target = self.target
1153 summed_target_size_name = "N_post"
1154 orig_varname = varname[:-5]
1155 summed_var_index = "_synaptic_post"
1156
1157 target_eq = getattr(summed_target, "equations", {}).get(orig_varname, None)
1158 if target_eq is None or target_eq.type != PARAMETER:
1159 raise ValueError(
1160 f"The summed variable '{varname}' needs a "
1161 f"corresponding parameter '{orig_varname}' in the "
1162 "target group."
1163 )
1164
1165 fail_for_dimension_mismatch(
1166 self.variables["_summed_" + varname].dim,
1167 self.variables[varname].dim,
1168 "Summed variables need to have "
1169 "the same units in Synapses "
1170 "and the target group",
1171 )
1172 if self.variables[varname] in summed_targets:
1173 raise ValueError(
1174 f"The target variable '{orig_varname}' is already "
1175 "updated by another summed variable"
1176 )
1177 summed_targets.add(self.variables[varname])
1178 updater = SummedVariableUpdater(
1179 single_equation.expr,
1180 varname,
1181 self,
1182 summed_target,
1183 summed_target_size_name,
1184 summed_var_index,
1185 )
1186 self.summed_updaters[varname] = updater
1187 self.contained_objects.append(updater)
1188
1189 # Activate name attribute access
1190 self._enable_group_attributes()
1191
1192 @staticmethod
1193 def verify_dependencies(
1194 eq, eq_type, deps, should_not_depend_on, should_not_depend_on_name
1195 ):
1196 """
1197 Helper function to verify that event-driven equations do not depend
1198 on clock-driven equations and the other way round.
1199
1200 Parameters
1201 ----------
1202 eq : `SingleEquation`
1203 The equation to verify
1204 eq_type : str
1205 The type of the equation (for the error message)
1206 deps : list
1207 A list of dependencies
1208 should_not_depend_on : list
1209 A list of equations to verify against the dependencies
1210 should_not_depend_on_name : str
1211 The name of the list of equations (for the error message)
1212
1213 Raises
1214 ------
1215 `EquationError`
1216 If the given equation depends on something in the other set of
1217 equations.
1218 """
1219 for dep in deps:
1220 if dep.equation in should_not_depend_on and (
1221 dep.equation.type == DIFFERENTIAL_EQUATION
1222 or "summed" in dep.equation.flags
1223 ):
1224 via_str = ""
1225 if dep.via:
1226 via_str = " (via " + ", ".join(f"'{v}'" for v in dep.via) + ")"
1227 raise EquationError(
1228 f"The {eq_type} '{eq.varname}' should "
1229 "not depend on the "
1230 f"{should_not_depend_on_name} variable "
1231 f"'{dep.equation.varname}'{via_str}."
1232 )
1233
1234 N_outgoing_pre = property(
1235 fget=lambda self: self.variables["N_outgoing"].get_value(),
1236 doc=(
1237 "The number of outgoing synapses for each neuron in the pre-synaptic group."
1238 ),
1239 )
1240 N_incoming_post = property(
1241 fget=lambda self: self.variables["N_incoming"].get_value(),
1242 doc=(
1243 "The number of incoming synapses for each neuron in the "
1244 "post-synaptic group."
1245 ),
1246 )
1247
1248 def __getitem__(self, item):
1249 indices = self.indices[item]
1250 return SynapticSubgroup(self, indices)
1251
1252 def _set_delay(self, delay, with_unit):
1253 if "pre" not in self._synaptic_updaters:
1254 raise AttributeError(
1255 "Synapses do not have a 'pre' pathway, "
1256 "do not know what 'delay' refers to."
1257 )
1258 # Note that we cannot simply say: "self.pre.delay = delay" because this
1259 # would not correctly deal with references to external constants
1260 var = self.pre.variables["delay"]
1261 if with_unit:
1262 reference = var.get_addressable_value_with_unit("delay", self.pre)
1263 else:
1264 reference = var.get_addressable_value("delay", self.pre)
1265 reference.set_item("True", delay, level=2)
1266
1267 def _get_delay(self, with_unit):
1268 if "pre" not in self._synaptic_updaters:
1269 raise AttributeError(
1270 "Synapses do not have a 'pre' pathway, "
1271 "do not know what 'delay' refers to."
1272 )
1273 var = self.pre.variables["delay"]
1274 if with_unit:
1275 return var.get_addressable_value_with_unit("delay", self.pre)
1276 else:
1277 return var.get_addressable_value("delay", self.pre)
1278
1279 delay = property(
1280 functools.partial(_get_delay, with_unit=True),
1281 functools.partial(_set_delay, with_unit=True),
1282 doc="The presynaptic delay (if a pre-synaptic pathway exists).",
1283 )
1284 delay_ = property(
1285 functools.partial(_get_delay, with_unit=False),
1286 functools.partial(_set_delay, with_unit=False),
1287 doc=(
1288 "The presynaptic delay without unit information (if a"
1289 "pre-synaptic pathway exists)."
1290 ),
1291 )
1292
1293 def _add_updater(self, code, prepost, objname=None, delay=None, event="spike"):
1294 """
1295 Add a new target updater. Users should call `add_pre` or `add_post`
1296 instead.
1297
1298 Parameters
1299 ----------
1300 code : str
1301 The abstract code that should be executed on pre-/postsynaptic
1302 spikes.
1303 prepost : {'pre', 'post'}
1304 Whether the code is triggered by presynaptic or postsynaptic spikes
1305 objname : str, optional
1306 A name for the object, see `SynapticPathway` for more details.
1307 delay : `Quantity`, optional
1308 A scalar delay (same delay for all synapses) for this pathway. If
1309 not given, delays are expected to vary between synapses.
1310
1311 Returns
1312 -------
1313 objname : str
1314 The final name for the object. Equals `objname` if it was explicitly
1315 given (and did not end in a wildcard character).
1316
1317 """
1318 if prepost == "pre":
1319 spike_group, group_name = self.source, "Source"
1320 elif prepost == "post":
1321 spike_group, group_name = self.target, "Target"
1322 else:
1323 raise AssertionError(
1324 f"'prepost' argument has to be 'pre' or 'post', is '{prepost}'."
1325 )
1326 if event not in spike_group.events:
1327 if event == "spike":
1328 threshold_text = " Did you forget to set a 'threshold'?"
1329 else:
1330 threshold_text = ""
1331 raise ValueError(
1332 f"{group_name} group '{spike_group.name}' does not define "
1333 f"an event '{event}'.{threshold_text}"
1334 )
1335
1336 if not isinstance(spike_group, SpikeSource) or not hasattr(
1337 spike_group, "clock"
1338 ):
1339 raise TypeError(
1340 f"'{group_name}' has to be a SpikeSource with spikes and"
1341 f" clock attribute. Is type {type(spike_group)!r} instead."
1342 )
1343
1344 updater = SynapticPathway(
1345 self, code, prepost, objname, delay=delay, event=event
1346 )
1347 objname = updater.objname
1348 if hasattr(self, objname):
1349 raise ValueError(
1350 f"Cannot add updater with name '{objname}', synapses "
1351 "object already has an attribute with this "
1352 "name."
1353 )
1354
1355 setattr(self, objname, updater)
1356 self._synaptic_updaters.append(objname)
1357 self._pathways.append(updater)
1358 self.contained_objects.append(updater)
1359 return objname
1360
1361 def _create_variables(self, equations, user_dtype=None):
1362 """
1363 Create the variables dictionary for this `Synapses`, containing
1364 entries for the equation variables and some standard entries.
1365 """
1366 self.variables = Variables(self)
1367
1368 # Standard variables always present
1369 self.variables.add_dynamic_array(
1370 "_synaptic_pre", size=0, dtype=np.int32, constant=True, read_only=True
1371 )
1372 self.variables.add_dynamic_array(
1373 "_synaptic_post", size=0, dtype=np.int32, constant=True, read_only=True
1374 )
1375 self.variables.create_clock_variables(self._clock)
1376 if "_offset" in self.target.variables:
1377 self.variables.add_reference("_target_offset", self.target, "_offset")
1378 else:
1379 self.variables.add_constant("_target_offset", value=0)
1380 if "_offset" in self.source.variables:
1381 self.variables.add_reference("_source_offset", self.source, "_offset")
1382 else:
1383 self.variables.add_constant("_source_offset", value=0)
1384 # To cope with connections to/from other synapses, N_incoming/N_outgoing
1385 # will be resized when synapses are created
1386 self.variables.add_dynamic_array(
1387 "N_incoming",
1388 size=0,
1389 dtype=np.int32,
1390 constant=True,
1391 read_only=True,
1392 index="_postsynaptic_idx",
1393 )
1394 self.variables.add_dynamic_array(
1395 "N_outgoing",
1396 size=0,
1397 dtype=np.int32,
1398 constant=True,
1399 read_only=True,
1400 index="_presynaptic_idx",
1401 )
1402
1403 # We have to make a distinction here between the indices
1404 # and the arrays (even though they refer to the same object)
1405 # the synaptic propagation template would otherwise overwrite
1406 # synaptic_post in its namespace with the value of the
1407 # postsynaptic index, leading to errors for the next
1408 # propagation.
1409 self.variables.add_reference("_presynaptic_idx", self, "_synaptic_pre")
1410 self.variables.add_reference("_postsynaptic_idx", self, "_synaptic_post")
1411
1412 # Except for subgroups (which potentially add an offset), the "i" and
1413 # "j" variables are simply equivalent to `_synaptic_pre` and
1414 # `_synaptic_post`
1415 if getattr(self.source, "start", 0) == 0:
1416 self.variables.add_reference("i", self, "_synaptic_pre")
1417 else:
1418 self.variables.add_reference(
1419 "_source_i", self.source.source, "i", index="_presynaptic_idx"
1420 )
1421 self.variables.add_reference("_source_offset", self.source, "_offset")
1422 self.variables.add_subexpression(
1423 "i",
1424 dtype=self.source.source.variables["i"].dtype,
1425 expr="_source_i - _source_offset",
1426 index="_presynaptic_idx",
1427 )
1428 if getattr(self.target, "start", 0) == 0:
1429 self.variables.add_reference("j", self, "_synaptic_post")
1430 else:
1431 self.variables.add_reference(
1432 "_target_j", self.target.source, "i", index="_postsynaptic_idx"
1433 )
1434 self.variables.add_reference("_target_offset", self.target, "_offset")
1435 self.variables.add_subexpression(
1436 "j",
1437 dtype=self.target.source.variables["i"].dtype,
1438 expr="_target_j - _target_offset",
1439 index="_postsynaptic_idx",
1440 )
1441
1442 # Add the standard variables
1443 self.variables.add_array(
1444 "N", dtype=np.int32, size=1, scalar=True, constant=True, read_only=True
1445 )
1446
1447 for eq in equations.values():
1448 dtype = get_dtype(eq, user_dtype)
1449 if eq.type in (DIFFERENTIAL_EQUATION, PARAMETER):
1450 check_identifier_pre_post(eq.varname)
1451 constant = "constant" in eq.flags
1452 shared = "shared" in eq.flags
1453 linked = "linked" in eq.flags
1454 if linked:
1455 self._linked_variables.add(eq.varname)
1456 elif shared:
1457 self.variables.add_array(
1458 eq.varname,
1459 size=1,
1460 dimensions=eq.dim,
1461 dtype=dtype,
1462 constant=constant,
1463 scalar=True,
1464 index="0",
1465 )
1466 else:
1467 self.variables.add_dynamic_array(
1468 eq.varname,
1469 size=0,
1470 dimensions=eq.dim,
1471 dtype=dtype,
1472 constant=constant,
1473 )
1474 elif eq.type == SUBEXPRESSION:
1475 if "summed" in eq.flags:
1476 # Give a special name to the subexpression for summed
1477 # variables to avoid confusion with the pre/postsynaptic
1478 # target variable
1479 varname = "_summed_" + eq.varname
1480 else:
1481 check_identifier_pre_post(eq.varname)
1482 varname = eq.varname
1483 self.variables.add_subexpression(
1484 varname,
1485 dimensions=eq.dim,
1486 expr=str(eq.expr),
1487 scalar="shared" in eq.flags,
1488 dtype=dtype,
1489 )
1490 else:
1491 raise AssertionError(f"Unknown type of equation: {eq.eq_type}")
1492
1493 # Stochastic variables
1494 for xi in equations.stochastic_variables:
1495 self.variables.add_auxiliary_variable(xi, dimensions=(second**-0.5).dim)
1496
1497 # Add all the pre and post variables with _pre and _post suffixes
1498 for name in getattr(self.source, "variables", {}):
1499 # Raise an error if a variable name is also used for a synaptic
1500 # variable (we ignore 'lastupdate' to allow connections from another
1501 # Synapses object)
1502 if (
1503 name in equations.names
1504 and name != "lastupdate"
1505 and "summed" not in equations[name].flags
1506 ):
1507 error_msg = (
1508 f"The pre-synaptic variable {name} has the same "
1509 "name as a synaptic variable, rename the synaptic "
1510 "variable."
1511 )
1512 if name + "_syn" not in self.variables:
1513 error_msg += f"(for example to '{name}_syn') "
1514 error_msg += "to avoid confusion"
1515 raise ValueError(error_msg)
1516 if name.startswith("_"):
1517 continue # Do not add internal variables
1518 var = self.source.variables[name]
1519 index = "0" if var.scalar else "_presynaptic_idx"
1520 try:
1521 self.variables.add_reference(
1522 name + "_pre", self.source, name, index=index
1523 )
1524 except TypeError:
1525 logger.diagnostic(
1526 f"Cannot include a reference to '{name}' in "
1527 f"'{self.name}', '{name}' uses a non-standard "
1528 "indexing in the pre-synaptic group "
1529 f"'{self.source.name}'."
1530 )
1531 for name in getattr(self.target, "variables", {}):
1532 # Raise an error if a variable name is also used for a synaptic
1533 # variable (we ignore 'lastupdate' to allow connections to another
1534 # Synapses object)
1535 if (
1536 name in equations.names
1537 and name != "lastupdate"
1538 and "summed" not in equations[name].flags
1539 ):
1540 error_msg = (
1541 f"The post-synaptic variable '{name}' has the same "
1542 "name as a synaptic variable, rename the synaptic "
1543 "variable."
1544 )
1545 if name + "_syn" not in self.variables:
1546 error_msg += f"(for example to '{name}_syn') "
1547 error_msg += "to avoid confusion"
1548 raise ValueError(error_msg)
1549 if name.startswith("_"):
1550 continue # Do not add internal variables
1551 var = self.target.variables[name]
1552 index = "0" if var.scalar else "_postsynaptic_idx"
1553 try:
1554 self.variables.add_reference(
1555 name + "_post", self.target, name, index=index
1556 )
1557 # Also add all the post variables without a suffix, but only if
1558 # it does not have a post or pre suffix in the target group
1559 # (which could happen when connecting to synapses)
1560 if not name.endswith("_post") or name.endswith("_pre"):
1561 self.variables.add_reference(name, self.target, name, index=index)
1562 except TypeError:
1563 logger.diagnostic(
1564 f"Cannot include a reference to '{name}' in "
1565 f"'{self.name}', '{name}' uses a non-standard "
1566 "indexing in the post-synaptic group "
1567 f"'{self.target.name}'."
1568 )
1569
1570 # Check scalar subexpressions
1571 for eq in equations.values():
1572 if eq.type == SUBEXPRESSION and "shared" in eq.flags:
1573 var = self.variables[eq.varname]
1574 for identifier in var.identifiers:
1575 if identifier in self.variables:
1576 if not self.variables[identifier].scalar:
1577 raise SyntaxError(
1578 f"Shared subexpression '{eq.varname}' "
1579 "refers to non-shared variable "
1580 f"'{identifier}'."
1581 )
1582
1583 def before_run(self, run_namespace):
1584 self.equations.check_units(self, run_namespace=run_namespace)
1585 # Check that subexpressions that refer to stateful functions are labeled
1586 # as "constant over dt"
1587 check_subexpressions(self, self.equations, run_namespace)
1588 super().before_run(run_namespace=run_namespace)
1589
1590 @device_override("synapses_connect")
1591 def connect(
1592 self,
1593 condition=None,
1594 i=None,
1595 j=None,
1596 p=1.0,
1597 n=1,
1598 skip_if_invalid=False,
1599 namespace=None,
1600 level=0,
1601 ):
1602 """
1603 Add synapses.
1604
1605 See :doc:`/user/synapses` for details.
1606
1607 Parameters
1608 ----------
1609 condition : str, bool, optional
1610 A boolean or string expression that evaluates to a boolean.
1611 The expression can depend on indices ``i`` and ``j`` and on
1612 pre- and post-synaptic variables. Can be combined with
1613 arguments ``n``, and ``p`` but not ``i`` or ``j``.
1614 i : int, ndarray of int, str, optional
1615 The presynaptic neuron indices It can be an index or array of
1616 indices if combined with the ``j`` argument, or it can be a string
1617 generator expression.
1618 j : int, ndarray of int, str, optional
1619 The postsynaptic neuron indices. It can be an index or array of
1620 indices if combined with the ``i`` argument, or it can be a string
1621 generator expression.
1622 p : float, str, optional
1623 The probability to create ``n`` synapses wherever the ``condition``
1624 evaluates to true. Cannot be used with generator syntax for ``j``.
1625 n : int, str, optional
1626 The number of synapses to create per pre/post connection pair.
1627 Defaults to 1.
1628 skip_if_invalid : bool, optional
1629 If set to True, rather than raising an error if you try to
1630 create an invalid/out of range pair (i, j) it will just
1631 quietly skip those synapses.
1632 namespace : dict-like, optional
1633 A namespace that will be used in addition to the group-specific
1634 namespaces (if defined). If not specified, the locals
1635 and globals around the run function will be used.
1636 level : int, optional
1637 How deep to go up the stack frame to look for the locals/global
1638 (see ``namespace`` argument).
1639
1640 Examples
1641 --------
1642 >>> from brian2 import *
1643 >>> import numpy as np
1644 >>> G = NeuronGroup(10, 'dv/dt = -v / tau : 1', threshold='v>1', reset='v=0')
1645 >>> S = Synapses(G, G, 'w:1', on_pre='v+=w')
1646 >>> S.connect(condition='i != j') # all-to-all but no self-connections
1647 >>> S.connect(i=0, j=0) # connect neuron 0 to itself
1648 >>> S.connect(i=np.array([1, 2]), j=np.array([2, 1])) # connect 1->2 and 2->1
1649 >>> S.connect() # connect all-to-all
1650 >>> S.connect(condition='i != j', p=0.1) # Connect neurons with 10% probability, exclude self-connections
1651 >>> S.connect(j='i', n=2) # Connect all neurons to themselves with 2 synapses
1652 >>> S.connect(j='k for k in range(i+1)') # Connect neuron i to all j with 0<=j<=i
1653 >>> S.connect(j='i+(-1)**k for k in range(2) if i>0 and i<N_pre-1') # connect neuron i to its neighbours if it has both neighbours
1654 >>> S.connect(j='k for k in sample(N_post, p=i*1.0/(N_pre-1))') # neuron i connects to j with probability i/(N-1)
1655 >>> S.connect(j='k for k in sample(N_post, size=i//2)') # Each neuron connects to i//2 other neurons (chosen randomly)
1656 """
1657 # check types
1658 self._verify_connect_argument_types(condition, i, j, n, p)
1659
1660 self._connect_called = True
1661
1662 # Get namespace information
1663 if namespace is None:
1664 namespace = get_local_namespace(level=level + 2)
1665
1666 try: # wrap everything to catch IndexError
1667 # which connection case are we in?
1668 # 1: Connection condition
1669 if condition is None and i is None and j is None:
1670 condition = True
1671 if condition is not None:
1672 if i is not None or j is not None:
1673 raise ValueError("Cannot combine condition with i or j arguments")
1674 if condition is False or condition == "False":
1675 # Nothing to do
1676 return
1677 j = self._condition_to_generator_expression(condition, p, namespace)
1678 self._add_synapses_generator(
1679 j,
1680 n,
1681 skip_if_invalid=skip_if_invalid,
1682 namespace=namespace,
1683 level=level + 2,
1684 over_presynaptic=True,
1685 )
1686 # 2: connection indices
1687 elif (i is not None and j is not None) and not (
1688 isinstance(i, str) or isinstance(j, str)
1689 ):
1690 if skip_if_invalid:
1691 raise ValueError("Can only use skip_if_invalid with string syntax")
1692 i, j, n = self._verify_connect_array_arguments(i, j, n)
1693 self._add_synapses_from_arrays(i, j, n, p, namespace=namespace)
1694 # 3: Generator expression over post-synaptic cells (i='...')
1695 elif isinstance(i, str):
1696 i = self._finalize_generator_expression(i, j, p, "i", "j")
1697 self._add_synapses_generator(
1698 i,
1699 n,
1700 skip_if_invalid=skip_if_invalid,
1701 namespace=namespace,
1702 level=level + 2,
1703 over_presynaptic=False,
1704 )
1705 # 4: Generator expression over pre-synaptic cells (i='...')
1706 elif isinstance(j, str):
1707 j = self._finalize_generator_expression(j, i, p, "j", "i")
1708 self._add_synapses_generator(
1709 j,
1710 n,
1711 skip_if_invalid=skip_if_invalid,
1712 namespace=namespace,
1713 level=level + 2,
1714 over_presynaptic=True,
1715 )
1716 else:
1717 raise ValueError(
1718 "Must specify at least one of condition, i or j arguments"
1719 )
1720 except IndexError as e:
1721 raise IndexError(
1722 "Tried to create synapse indices outside valid range."
1723 ) from e
1724
1725 # Helper functions for Synapses.connect ↑
1726 def _verify_connect_array_arguments(self, i, j, n):
1727 if hasattr(i, "_indices"):
1728 i = i._indices()
1729 i = np.asarray(i)
1730 if not np.issubdtype(i.dtype, np.signedinteger):
1731 raise TypeError(
1732 "Presynaptic indices have to be given as "
1733 f"integers, are type {i.dtype} "
1734 "instead."
1735 )
1736 if hasattr(j, "_indices"):
1737 j = j._indices()
1738 j = np.asarray(j)
1739 if not np.issubdtype(j.dtype, np.signedinteger):
1740 raise TypeError(
1741 "Presynaptic indices can only be combined "
1742 "with postsynaptic integer indices))"
1743 )
1744 if isinstance(n, str):
1745 raise TypeError(
1746 "Indices cannot be combined with a string"
1747 "expression for n. Either use an "
1748 "array/scalar for n, or a string "
1749 "expression for the connections"
1750 )
1751 i, j, n = np.broadcast_arrays(i, j, n)
1752 if i.ndim > 1:
1753 raise ValueError("Can only use 1-dimensional indices")
1754 return i, j, n
1755
1756 def _condition_to_generator_expression(self, condition, p, namespace):
1757 if condition is True:
1758 condition = "True"
1759 # Check that the condition is a boolean expresion
1760 identifiers = get_identifiers(condition)
1761 variables = self.resolve_all(identifiers, namespace)
1762 if not is_boolean_expression(condition, variables):
1763 raise TypeError(f"Condition '{condition}' is not a boolean condition")
1764 # Check the units (mostly to check for unit consistency within the condition)
1765 dims = parse_expression_dimensions(condition, variables)
1766 if dims is not DIMENSIONLESS:
1767 # We should not get here normally
1768 raise TypeError(f"Condition '{condition}' is not a boolean condition")
1769 condition = word_substitute(condition, {"j": "_k"})
1770 if not isinstance(p, str) and p == 1:
1771 j = f"_k for _k in range(N_post) if {condition}"
1772 else:
1773 j = None
1774 if isinstance(p, str):
1775 identifiers = get_identifiers(p)
1776 variables = self.resolve_all(identifiers, namespace)
1777 dim = parse_expression_dimensions(p, variables)
1778 if dim is not DIMENSIONLESS:
1779 raise DimensionMismatchError(
1780 "Expression for p should be dimensionless."
1781 )
1782 p_dep = self._expression_index_dependence(p, namespace=namespace)
1783 if "_postsynaptic_idx" in p_dep or "_iterator_idx" in p_dep:
1784 j = f"_k for _k in range(N_post) if ({condition}) and rand()<{p}"
1785 if j is None:
1786 j = f"_k for _k in sample(N_post, p={p}) if {condition}"
1787 return j
1788
1789 def _verify_connect_argument_types(self, condition, i, j, n, p):
1790 if condition is not None and not isinstance(condition, (bool, str)):
1791 raise TypeError(
1792 "condition argument must be bool or string. If you "
1793 "want to connect based on indices, use "
1794 "connect(i=..., j=...)."
1795 )
1796 if i is not None and not (
1797 isinstance(i, (numbers.Integral, np.ndarray, Sequence))
1798 or hasattr(i, "_indices")
1799 ):
1800 raise TypeError("i argument must be int, array or string")
1801 if j is not None and not (
1802 isinstance(j, (numbers.Integral, np.ndarray, Sequence))
1803 or hasattr(j, "_indices")
1804 ):
1805 raise TypeError("j argument must be int, array or string")
1806 # TODO: eliminate these restrictions
1807 if not isinstance(p, (int, float, str)):
1808 raise TypeError("p must be float or string")
1809 if not isinstance(n, (int, str)):
1810 raise TypeError("n must be int or string")
1811 if isinstance(condition, str) and re.search(r"\bfor\b", condition):
1812 raise ValueError(
1813 "Generator expression given for condition, write "
1814 f"connect(j='{condition}'...) instead of "
1815 f"connect('{condition}'...)."
1816 )
1817
1818 def check_variable_write(self, variable):
1819 """
1820 Checks that `Synapses.connect` has been called before setting a
1821 synaptic variable.
1822
1823 Parameters
1824 ----------
1825 variable : `Variable`
1826 The variable that the user attempts to set.
1827
1828 Raises
1829 ------
1830 TypeError
1831 If `Synapses.connect` has not been called yet.
1832 """
1833 if not self._connect_called:
1834 raise TypeError(
1835 f"Cannot write to synaptic variable '{variable.name}', you "
1836 "need to call connect(...) first"
1837 )
1838
1839 def _resize(self, number):
1840 if not isinstance(number, (numbers.Integral, np.integer)):
1841 raise TypeError(f"Expected an integer number, got {type(number)} instead.")
1842 if number < self.N:
1843 raise ValueError(
1844 f"Cannot reduce number of synapses, {number} < {len(self)}."
1845 )
1846
1847 for variable in self._registered_variables:
1848 variable.resize(number)
1849
1850 self.variables["N"].set_value(number)
1851
1852 def _update_synapse_numbers(self, old_num_synapses):
1853 source_offset = self.variables["_source_offset"].get_value()
1854 target_offset = self.variables["_target_offset"].get_value()
1855 # This resizing is only necessary if we are connecting to/from synapses
1856 post_with_offset = self.variables["N_post"].item() + target_offset
1857 pre_with_offset = self.variables["N_pre"].item() + source_offset
1858 self.variables["N_incoming"].resize(post_with_offset)
1859 self.variables["N_outgoing"].resize(pre_with_offset)
1860 N_outgoing = self.variables["N_outgoing"].get_value()
1861 N_incoming = self.variables["N_incoming"].get_value()
1862 synaptic_pre = self.variables["_synaptic_pre"].get_value()
1863 synaptic_post = self.variables["_synaptic_post"].get_value()
1864
1865 # Update the number of total outgoing/incoming synapses per
1866 # source/target neuron
1867 N_outgoing[:] += np.bincount(
1868 synaptic_pre[old_num_synapses:], minlength=len(N_outgoing)
1869 )
1870 N_incoming[:] += np.bincount(
1871 synaptic_post[old_num_synapses:], minlength=len(N_incoming)
1872 )
1873
1874 if self.multisynaptic_index is not None:
1875 synapse_number_var = self.variables[self.multisynaptic_index]
1876 synapse_number = synapse_number_var.get_value()
1877
1878 # Update the "synapse number" (number of synapses for the same
1879 # source-target pair)
1880 # We wrap pairs of source/target indices into a complex number for
1881 # convenience
1882 _source_target_pairs = synaptic_pre + synaptic_post * 1j
1883 synapse_number[:] = calc_repeats(_source_target_pairs)
1884
1885 def register_variable(self, variable):
1886 """
1887 Register a `DynamicArray` to be automatically resized when the size of
1888 the indices change. Called automatically when a `SynapticArrayVariable`
1889 specifier is created.
1890 """
1891 if not hasattr(variable, "resize"):
1892 raise TypeError(
1893 f"Variable of type {type(variable)} does not have a resize "
1894 "method, cannot register it with the synaptic "
1895 "indices."
1896 )
1897 self._registered_variables.add(variable)
1898
1899 def unregister_variable(self, variable):
1900 """
1901 Unregister a `DynamicArray` from the automatic resizing mechanism.
1902 """
1903 self._registered_variables.remove(variable)
1904
1905 def _get_multisynaptic_indices(self):
1906 template_kwds = {"multisynaptic_index": self.multisynaptic_index}
1907 if self.multisynaptic_index is not None:
1908 needed_variables = [self.multisynaptic_index]
1909 else:
1910 needed_variables = []
1911 return template_kwds, needed_variables
1912
1913 def _add_synapses_from_arrays(self, sources, targets, n, p, namespace=None):
1914 template_kwds, needed_variables = self._get_multisynaptic_indices()
1915
1916 variables = Variables(self)
1917
1918 sources = np.atleast_1d(sources).astype(np.int32)
1919 targets = np.atleast_1d(targets).astype(np.int32)
1920
1921 # Check whether the values in sources/targets make sense
1922 error_message = (
1923 "The given {source_or_target} indices contain "
1924 "values outside of the range [0, {max_value}] "
1925 "allowed for the {source_or_target} group "
1926 '"{group_name}"'
1927 )
1928 try:
1929 for indices, source_or_target, group in [
1930 (sources, "source", self.source),
1931 (targets, "target", self.target),
1932 ]:
1933 if np.max(indices) >= len(group) or np.min(indices) < 0:
1934 raise IndexError(
1935 error_message.format(
1936 source_or_target=source_or_target,
1937 max_value=len(group) - 1,
1938 group_name=group.name,
1939 )
1940 )
1941 except NotImplementedError:
1942 logger.warn(
1943 "Cannot check whether the indices given for the connect call are valid."
1944 " This can happen in standalone mode when using indices to connect to"
1945 " synapses that have been created with a connection pattern. You can"
1946 " avoid this situation by either using a connection pattern or synaptic"
1947 " indices in both connect calls.",
1948 name_suffix="cannot_check_synapse_indices",
1949 )
1950 n = np.atleast_1d(n)
1951 p = np.atleast_1d(p)
1952
1953 if not len(p) == 1 or p != 1:
1954 use_connections = np.random.rand(len(sources)) < p
1955 sources = sources[use_connections]
1956 targets = targets[use_connections]
1957 n = n[use_connections]
1958 sources = sources.repeat(n)
1959 targets = targets.repeat(n)
1960
1961 variables.add_array(
1962 "sources", len(sources), dtype=np.int32, values=sources, read_only=True
1963 )
1964 variables.add_array(
1965 "targets", len(targets), dtype=np.int32, values=targets, read_only=True
1966 )
1967 # These definitions are important to get the types right in C++
1968 variables.add_auxiliary_variable("_real_sources", dtype=np.int32)
1969 variables.add_auxiliary_variable("_real_targets", dtype=np.int32)
1970 abstract_code = ""
1971 if "_offset" in self.source.variables:
1972 variables.add_reference("_source_offset", self.source, "_offset")
1973 abstract_code += "_real_sources = sources + _source_offset\n"
1974 else:
1975 abstract_code += "_real_sources = sources\n"
1976 if "_offset" in self.target.variables:
1977 variables.add_reference("_target_offset", self.target, "_offset")
1978 abstract_code += "_real_targets = targets + _target_offset\n"
1979 else:
1980 abstract_code += "_real_targets = targets"
1981 logger.debug(
1982 f"Creating synapses from group '{self.source.name}' to group "
1983 f"'{self.target.name}', using pre-defined arrays)"
1984 )
1985
1986 codeobj = create_runner_codeobj(
1987 self,
1988 abstract_code,
1989 "synapses_create_array",
1990 additional_variables=variables,
1991 template_kwds=template_kwds,
1992 needed_variables=needed_variables,
1993 check_units=False,
1994 run_namespace={},
1995 )
1996 codeobj()
1997
1998 def _expression_index_dependence(self, expr, namespace, additional_indices=None):
1999 """
2000 Returns the set of synaptic indices that expr depends on
2001 """
2002 nr = NodeRenderer()
2003 expr = nr.render_expr(expr)
2004 deps = set()
2005 if additional_indices is None:
2006 additional_indices = {}
2007 identifiers = get_identifiers_recursively([expr], self.variables)
2008 variables = self.resolve_all(
2009 {name for name in identifiers if name not in additional_indices}, namespace
2010 )
2011 if any(getattr(var, "auto_vectorise", False) for var in variables.values()):
2012 identifiers.add("_vectorisation_idx")
2013
2014 for varname in identifiers:
2015 # Special handling of i and j -- they do not actually use pre-/
2016 # postsynaptic indices (except for subgroups), they *are* the
2017 # pre-/postsynaptic indices
2018 if varname == "i":
2019 deps.add("_presynaptic_idx")
2020 elif varname == "j":
2021 deps.add("_iterator_idx")
2022 elif varname in additional_indices:
2023 deps.add(additional_indices[varname])
2024 else:
2025 deps.add(self.variables.indices[varname])
2026 if "0" in deps:
2027 deps.remove("0")
2028 return deps
2029
2030 def _add_synapses_generator(
2031 self,
2032 gen,
2033 n,
2034 skip_if_invalid=False,
2035 over_presynaptic=True,
2036 namespace=None,
2037 level=0,
2038 ):
2039 # Get the local namespace
2040 if namespace is None:
2041 namespace = get_local_namespace(level=level + 1)
2042
2043 parsed = parse_synapse_generator(gen)
2044 self._check_parsed_synapses_generator(parsed, namespace)
2045
2046 # Referring to N_incoming/N_outgoing in the connect statement is
2047 # ill-defined (see github issue #1227)
2048 identifiers = get_identifiers_recursively([gen], self.variables)
2049 for var in ["N_incoming", "N_outgoing"]:
2050 if var in identifiers:
2051 raise ValueError(f"The connect statement cannot refer to '{var}'.")
2052
2053 template_kwds, needed_variables = self._get_multisynaptic_indices()
2054 template_kwds.update(parsed)
2055 template_kwds["skip_if_invalid"] = skip_if_invalid
2056 # To support both i='...' and j='...' syntax, we provide additional keywords
2057 # to the template
2058 outer_index = "i" if over_presynaptic else "j"
2059 outer_index_size = "N_pre" if over_presynaptic else "N_post"
2060 outer_index_array = "_pre_idx" if over_presynaptic else "_post_idx"
2061 outer_index_offset = "_source_offset" if over_presynaptic else "_target_offset"
2062 result_index = "j" if over_presynaptic else "i"
2063 result_index_size = "N_post" if over_presynaptic else "N_pre"
2064 target_idx = "_postsynaptic_idx" if over_presynaptic else "_presynaptic_idx"
2065 result_index_array = "_post_idx" if over_presynaptic else "_pre_idx"
2066 result_index_offset = "_target_offset" if over_presynaptic else "_source_offset"
2067 result_index_name = "postsynaptic" if over_presynaptic else "presynaptic"
2068 template_kwds.update(
2069 {
2070 "outer_index": outer_index,
2071 "outer_index_size": outer_index_size,
2072 "outer_index_array": outer_index_array,
2073 "outer_index_offset": outer_index_offset,
2074 "result_index": result_index,
2075 "result_index_size": result_index_size,
2076 "result_index_name": result_index_name,
2077 "result_index_array": result_index_array,
2078 "result_index_offset": result_index_offset,
2079 }
2080 )
2081 abstract_code = {
2082 "setup_iterator": "",
2083 "generator_expr": "",
2084 "create_cond": "",
2085 "update": "",
2086 }
2087
2088 additional_indices = {parsed["inner_variable"]: "_iterator_idx"}
2089
2090 setupiter = ""
2091 for k, v in parsed["iterator_kwds"].items():
2092 if v is not None and k != "sample_size":
2093 deps = self._expression_index_dependence(
2094 v, namespace=namespace, additional_indices=additional_indices
2095 )
2096 if f"_{result_index_name}_idx" in deps or "_iterator_idx" in deps:
2097 raise ValueError(
2098 f'Expression "{v}" depends on {result_index_name} '
2099 "index or iterator"
2100 )
2101 setupiter += f"_iter_{k} = {v}\n"
2102
2103 # rand() in the if condition depends on _vectorisation_idx, but not if
2104 # its in the range expression (handled above)
2105 additional_indices["_vectorisation_idx"] = "_iterator_idx"
2106
2107 result_index_condition = False
2108 result_index_used = False
2109 if parsed["if_expression"] is not None:
2110 deps = self._expression_index_dependence(
2111 parsed["if_expression"],
2112 namespace=namespace,
2113 additional_indices=additional_indices,
2114 )
2115 if target_idx in deps:
2116 result_index_condition = True
2117 result_index_used = True
2118 elif "_iterator_idx" in deps:
2119 result_index_condition = True
2120 template_kwds["result_index_condition"] = result_index_condition
2121 template_kwds["result_index_used"] = result_index_used
2122
2123 abstract_code["setup_iterator"] += setupiter
2124 abstract_code["generator_expr"] += (
2125 f"{outer_index_array} = _raw{outer_index_array} \n"
2126 )
2127 abstract_code["generator_expr"] += f"_{result_index} = {parsed['element']}\n"
2128
2129 if result_index_condition:
2130 abstract_code["create_cond"] += (
2131 f"{result_index_array} = _raw{result_index_array} \n"
2132 )
2133 if parsed["if_expression"] is not None:
2134 abstract_code["create_cond"] += "_cond = " + parsed["if_expression"] + "\n"
2135 abstract_code["update"] += (
2136 f"{result_index_array} = _raw{result_index_array} \n"
2137 )
2138 abstract_code["update"] += "_n = " + str(n) + "\n"
2139
2140 # This overwrites 'i' and 'j' in the synapses' variables dictionary
2141 # This is necessary because in the context of synapse creation, i
2142 # and j do not correspond to the sources/targets of the existing
2143 # synapses but to all the possible sources/targets
2144 variables = Variables(None)
2145 # Will be set in the template
2146 variables.add_auxiliary_variable("_i", dtype=np.int32)
2147 variables.add_auxiliary_variable("_j", dtype=np.int32)
2148 variables.add_auxiliary_variable("_iter_low", dtype=np.int32)
2149 variables.add_auxiliary_variable("_iter_high", dtype=np.int32)
2150 variables.add_auxiliary_variable("_iter_step", dtype=np.int32)
2151 variables.add_auxiliary_variable("_iter_p")
2152 variables.add_auxiliary_variable("_iter_size", dtype=np.int32)
2153 variables.add_auxiliary_variable(parsed["inner_variable"], dtype=np.int32)
2154 # Make sure that variables have the correct type in the code
2155 variables.add_auxiliary_variable("_pre_idx", dtype=np.int32)
2156 variables.add_auxiliary_variable("_post_idx", dtype=np.int32)
2157 if parsed["if_expression"] is not None:
2158 variables.add_auxiliary_variable("_cond", dtype=bool)
2159 variables.add_auxiliary_variable("_n", dtype=np.int32)
2160
2161 if "_offset" in self.source.variables:
2162 variables.add_reference("_source_offset", self.source, "_offset")
2163 else:
2164 variables.add_constant("_source_offset", value=0)
2165
2166 if "_offset" in self.target.variables:
2167 variables.add_reference("_target_offset", self.target, "_offset")
2168 else:
2169 variables.add_constant("_target_offset", value=0)
2170
2171 variables.add_auxiliary_variable("_raw_pre_idx", dtype=np.int32)
2172 variables.add_auxiliary_variable("_raw_post_idx", dtype=np.int32)
2173
2174 variable_indices = defaultdict(lambda: "_idx")
2175 for varname in self.variables:
2176 if self.variables.indices[varname] == "_presynaptic_idx":
2177 variable_indices[varname] = "_raw_pre_idx"
2178 elif self.variables.indices[varname] == "_postsynaptic_idx":
2179 variable_indices[varname] = "_raw_post_idx"
2180
2181 if self.variables["i"] is self.variables["_synaptic_pre"]:
2182 variables.add_subexpression("i", "_i", dtype=self.variables["i"].dtype)
2183 if self.variables["j"] is self.variables["_synaptic_post"]:
2184 variables.add_subexpression("j", "_j", dtype=self.variables["j"].dtype)
2185 logger.debug(
2186 f"Creating synapses from group '{self.source.name}' to group "
2187 f"'{self.target.name}', using generator "
2188 f"'{parsed['original_expression']}'"
2189 )
2190
2191 codeobj = create_runner_codeobj(
2192 self,
2193 abstract_code,
2194 "synapses_create_generator",
2195 variable_indices=variable_indices,
2196 additional_variables=variables,
2197 template_kwds=template_kwds,
2198 needed_variables=needed_variables,
2199 check_units=False,
2200 run_namespace=namespace,
2201 )
2202 codeobj()
2203
2204 def _check_parsed_synapses_generator(self, parsed, namespace):
2205 """
2206 Type-check the parsed synapses generator. This function will raise a
2207 TypeError if any of the arguments to the iterator function are of an
2208 invalid type.
2209 """
2210 if parsed["iterator_func"] == "range":
2211 # We expect all arguments of the range function to be integers
2212 for argname, arg in parsed["iterator_kwds"].items():
2213 identifiers = get_identifiers(arg)
2214 variables = self.resolve_all(
2215 identifiers, run_namespace=namespace, user_identifiers=identifiers
2216 )
2217 annotated = brian_ast(arg, variables)
2218 if annotated.dtype != "integer":
2219 raise TypeError(
2220 f"The '{argname}' argument of the range function was "
2221 f"'{arg}', but it needs to be an integer."
2222 )
2223
2224 def _finalize_generator_expression(
2225 self,
2226 generator_expression,
2227 iteration_index,
2228 p,
2229 target_index_name,
2230 iteration_index_name,
2231 ):
2232 if iteration_index is not None:
2233 raise TypeError(
2234 f"Generator syntax for {target_index_name} cannot be combined with "
2235 f"{iteration_index_name} argument"
2236 )
2237 if isinstance(p, str) or p != 1:
2238 raise ValueError("Generator syntax cannot be combined with p argument")
2239 if not re.search(r"\bfor\b", generator_expression):
2240 if_split = generator_expression.split(" if ")
2241 if len(if_split) == 1:
2242 generator_expression = f"{generator_expression} for _ in range(1)"
2243 elif len(if_split) == 2:
2244 generator_expression = (
2245 f"{if_split[0]} for _ in range(1) if {if_split[1]}"
2246 )
2247 else:
2248 raise SyntaxError(
2249 f"Error parsing expression '{generator_expression}'. "
2250 "Expression must have generator "
2251 "syntax, for example 'k for k in "
2252 f"range({iteration_index_name}-10, {iteration_index_name}+10)'"
2253 )
2254 return generator_expression