Debian Codegraph @

brian2/core/operations.py

raw
1 import inspect
2
3 from brian2.core.base import BrianObject
4
5 __all__ = ["NetworkOperation", "network_operation"]
6
7
8 class NetworkOperation(BrianObject):
9 """Object with function that is called every time step.
10
11 Parameters
12 ----------
13
14 function : function
15 The function to call every time step, should take either no arguments
16 in which case it is called as ``function()`` or one argument, in which
17 case it is called with the current `Clock` time (`Quantity`).
18 dt : `Quantity`, optional
19 The time step to be used for the simulation. Cannot be combined with
20 the `clock` argument.
21 clock : `Clock`, optional
22 The update clock to be used. If neither a clock, nor the `dt` argument
23 is specified, the `defaultclock` will be used.
24 when : str, optional
25 In which scheduling slot to execute the operation during a time step.
26 Defaults to ``'start'``. See :ref:`scheduling` for possible values.
27 order : int, optional
28 The priority of this operation for operations occurring at the same time
29 step and in the same scheduling slot. Defaults to 0.
30
31 See Also
32 --------
33
34 network_operation, Network, BrianObject
35 """
36
37 add_to_magic_network = True
38
39 def __init__(
40 self,
41 function,
42 dt=None,
43 clock=None,
44 when="start",
45 order=0,
46 name="networkoperation*",
47 ):
48 BrianObject.__init__(
49 self, dt=dt, clock=clock, when=when, order=order, name=name
50 )
51
52 #: The function to be called each time step
53 self.function = function
54
55 is_method = inspect.ismethod(function)
56
57 if hasattr(function, "__code__"):
58 argcount = function.__code__.co_argcount
59 if is_method:
60 if argcount == 2:
61 self._has_arg = True
62 elif argcount == 1:
63 self._has_arg = False
64 else:
65 raise TypeError(
66 f"Method '{function.__name__}' cannot be used as a "
67 "network operation, it needs to have either "
68 "only 'self' or 'self, t' as arguments, but it "
69 f"has {argcount} arguments."
70 )
71 else:
72 if argcount >= 1 and function.__code__.co_varnames[0] == "self":
73 raise TypeError(
74 "The first argument of the function "
75 "'{function.__name__}' is 'self', suggesting it "
76 "is an instance method and not a function. Did "
77 "you use @network_operation on a class method? "
78 "This will not work, explicitly create a "
79 "NetworkOperation object instead -- see "
80 "the documentation for more "
81 "details."
82 )
83 if argcount == 1:
84 self._has_arg = True
85 elif argcount == 0:
86 self._has_arg = False
87 else:
88 raise TypeError(
89 f"Function '{function.__name__}' cannot be used as "
90 "a network operation, it needs to have either "
91 "only 't' as an argument or have no arguments, "
92 f"but it has {argcount} arguments."
93 )
94 else:
95 self._has_arg = False
96
97 def run(self):
98 if self._has_arg:
99 self.function(self._clock.t)
100 else:
101 self.function()
102
103
104 def network_operation(*args, **kwds):
105 """
106 network_operation(when=None)
107
108 Decorator to make a function get called every time step of a simulation.
109
110 The function being decorated should either have no arguments, or a single
111 argument which will be called with the current time ``t``.
112
113 Parameters
114 ----------
115 dt : `Quantity`, optional
116 The time step to be used for the simulation. Cannot be combined with
117 the `clock` argument.
118 clock : `Clock`, optional
119 The update clock to be used. If neither a clock, nor the `dt` argument
120 is specified, the `defaultclock` will be used.
121 when : str, optional
122 In which scheduling slot to execute the operation during a time step.
123 Defaults to ``'start'``. See :ref:`scheduling` for possible values.
124 order : int, optional
125 The priority of this operation for operations occurring at the same time
126 step and in the same scheduling slot. Defaults to 0.
127
128 Examples
129 --------
130
131 Print something each time step:
132 >>> from brian2 import *
133 >>> @network_operation
134 ... def f():
135 ... print('something')
136 ...
137 >>> net = Network(f)
138
139 Print the time each time step:
140
141 >>> @network_operation
142 ... def f(t):
143 ... print('The time is', t)
144 ...
145 >>> net = Network(f)
146
147 Specify a dt, etc.:
148
149 >>> @network_operation(dt=0.5*ms, when='end')
150 ... def f():
151 ... print('This will happen at the end of each timestep.')
152 ...
153 >>> net = Network(f)
154
155 Notes
156 -----
157
158 Converts the function into a `NetworkOperation`.
159
160 If using the form::
161
162 @network_operations(when='end')
163 def f():
164 ...
165
166 Then the arguments to network_operation must be keyword arguments.
167
168 See Also
169 --------
170
171 NetworkOperation, Network, BrianObject
172 """
173
174 # Notes on this decorator:
175 # Normally, a decorator comes in two types, with or without arguments. If
176 # it has no arguments, e.g.
177 # @decorator
178 # def f():
179 # ...
180 # then the decorator function is defined with an argument, and that
181 # argument is the function f. In this case, the decorator function
182 # returns a new function in place of f.
183 #
184 # However, you can also define:
185 # @decorator(arg)
186 # def f():
187 # ...
188 # in which case the argument to the decorator function is arg, and the
189 # decorator function returns a 'function factory', that is a callable
190 # object that takes a function as argument and returns a new function.
191 #
192 # It might be clearer just to note that the first form above is equivalent
193 # to:
194 # f = decorator(f)
195 # and the second to:
196 # f = decorator(arg)(f)
197 #
198 # In this case, we're allowing the decorator to be called either with or
199 # without an argument, so we have to look at the arguments and determine
200 # if it's a function argument (in which case we do the first case above),
201 # or if the arguments are arguments to the decorator, in which case we
202 # do the second case above.
203 #
204 # Here, the 'function factory' is the locally defined class
205 # do_network_operation, which is a callable object that takes a function
206 # as argument and returns a NetworkOperation object.
207 class do_network_operation:
208 def __init__(self, **kwds):
209 self.kwds = kwds
210
211 def __call__(self, f):
212 new_network_operation = NetworkOperation(f, **self.kwds)
213 # Depending on whether we were called as @network_operation or
214 # @network_operation(...) we need different levels, the level is
215 # 2 in the first case and 1 in the second case (because in the
216 # first case we go originalcaller->network_operation->do_network_operation
217 # and in the second case we go originalcaller->do_network_operation
218 # at the time when this method is called).
219 new_network_operation.__name__ = f.__name__
220 new_network_operation.__doc__ = f.__doc__
221 new_network_operation.__dict__.update(f.__dict__)
222 return new_network_operation
223
224 if len(args) == 1 and callable(args[0]):
225 # We're in case (1), the user has written:
226 # @network_operation
227 # def f():
228 # ...
229 # and the single argument to the decorator is the function f
230 return do_network_operation()(args[0])
231 else:
232 # We're in case (2), the user has written:
233 # @network_operation(...)
234 # def f():
235 # ...
236 # and the arguments must be keyword arguments
237 return do_network_operation(**kwds)