Debian Codegraph @

brian2/groups/subgroup.py

raw
1 from brian2.core.base import weakproxy_with_fallback
2 from brian2.core.spikesource import SpikeSource
3 from brian2.core.variables import Variables
4
5 from .group import Group, Indexing
6
7 __all__ = ["Subgroup"]
8
9
10 class Subgroup(Group, SpikeSource):
11 """
12 Subgroup of any `Group`
13
14 Parameters
15 ----------
16 source : SpikeSource
17 The source object to subgroup.
18 start, stop : int
19 Select only spikes with indices from ``start`` to ``stop-1``.
20 name : str, optional
21 A unique name for the group, or use ``source.name+'_subgroup_0'``, etc.
22 """
23
24 def __init__(self, source, start, stop, name=None):
25 # A Subgroup should never be constructed from another Subgroup
26 # Instead, use Subgroup(source.source,
27 # start + source.start, stop + source.start)
28 assert not isinstance(source, Subgroup)
29 self.source = weakproxy_with_fallback(source)
30
31 # Store a reference to the source's equations (if any)
32 self.equations = None
33 if hasattr(self.source, "equations"):
34 self.equations = weakproxy_with_fallback(self.source.equations)
35
36 if name is None:
37 name = f"{source.name}_subgroup*"
38 # We want to update the spikes attribute after it has been updated
39 # by the parent, we do this in slot 'thresholds' with an order
40 # one higher than the parent order to ensure it takes place after the
41 # parent threshold operation
42 Group.__init__(
43 self,
44 clock=source._clock,
45 when="thresholds",
46 order=source.order + 1,
47 name=name,
48 )
49 self._N = stop - start
50 self.start = start
51 self.stop = stop
52
53 self.events = self.source.events
54
55 # All the variables have to go via the _sub_idx to refer to the
56 # appropriate values in the source group
57 self.variables = Variables(self, default_index="_sub_idx")
58
59 # overwrite the meaning of N and i
60 if self.start > 0:
61 self.variables.add_constant("_offset", value=self.start)
62 self.variables.add_reference("_source_i", source, "i")
63 self.variables.add_subexpression(
64 "i",
65 dtype=source.variables["i"].dtype,
66 expr="_source_i - _offset",
67 index="_idx",
68 )
69 else:
70 # no need to calculate anything if this is a subgroup starting at 0
71 self.variables.add_reference("i", source)
72
73 self.variables.add_constant("N", value=self._N)
74 self.variables.add_constant("_source_N", value=len(source))
75 # add references for all variables in the original group
76 self.variables.add_references(source, list(source.variables.keys()))
77
78 # Only the variable _sub_idx itself is stored in the subgroup
79 # and needs the normal index for this group
80 self.variables.add_arange(
81 "_sub_idx", size=self._N, start=self.start, index="_idx"
82 )
83
84 # special indexing for subgroups
85 self._indices = Indexing(self, self.variables["_sub_idx"])
86
87 # Deal with special indices
88 for key, value in self.source.variables.indices.items():
89 if value == "0":
90 self.variables.indices[key] = "0"
91 elif value == "_idx":
92 continue # nothing to do, already uses _sub_idx correctly
93 else:
94 raise ValueError(
95 f"Do not know how to deal with variable '{key}' "
96 f"using index '{value}' in a subgroup."
97 )
98
99 self.namespace = self.source.namespace
100 self.codeobj_class = self.source.codeobj_class
101
102 self._enable_group_attributes()
103
104 spikes = property(lambda self: self.source.spikes)
105
106 def __getitem__(self, item):
107 if not isinstance(item, slice):
108 raise TypeError("Subgroups can only be constructed using slicing syntax")
109 start, stop, step = item.indices(self._N)
110 if step != 1:
111 raise IndexError("Subgroups have to be contiguous")
112 if start >= stop:
113 raise IndexError(
114 f"Illegal start/end values for subgroup, {int(start)}>={int(stop)}"
115 )
116 return Subgroup(self.source, self.start + start, self.start + stop)
117
118 def __repr__(self):
119 classname = self.__class__.__name__
120 return (
121 f"<{classname} {self.name!r} of {self.source.name!r} "
122 f"from {self.start} to {self.stop}>"
123 )
124
125 def __del__(self):
126 # Do not raise a warning if the subgroup gets deleted (subgroups do not need
127 # to be part of a network to be useful)
128 pass