| 1 |
""" |
| 2 |
Implementation of `TimedArray`. |
| 3 |
""" |
| 4 |
|
| 5 |
import numpy as np |
| 6 |
|
| 7 |
from brian2.core.clocks import defaultclock |
| 8 |
from brian2.core.functions import Function |
| 9 |
from brian2.core.names import Nameable |
| 10 |
from brian2.units.allunits import second |
| 11 |
from brian2.units.fundamentalunits import ( |
| 12 |
Quantity, |
| 13 |
check_units, |
| 14 |
get_dimensions, |
| 15 |
get_unit, |
| 16 |
) |
| 17 |
from brian2.utils.caching import CacheKey |
| 18 |
from brian2.utils.logger import get_logger |
| 19 |
from brian2.utils.stringtools import replace |
| 20 |
|
| 21 |
__all__ = ["TimedArray"] |
| 22 |
|
| 23 |
|
| 24 |
logger = get_logger(__name__) |
| 25 |
|
| 26 |
|
| 27 |
def _find_K(group_dt, dt): |
| 28 |
dt_ratio = dt / group_dt |
| 29 |
if dt_ratio > 1 and np.floor(dt_ratio) != dt_ratio: |
| 30 |
logger.warn( |
| 31 |
"Group uses a dt of %s while TimedArray uses dt " |
| 32 |
"of %s (ratio: 1/%s) → time grids not aligned" |
| 33 |
% (group_dt * second, dt * second, dt_ratio), |
| 34 |
once=True, |
| 35 |
) |
| 36 |
# Find an upsampling factor that should avoid rounding issues even |
| 37 |
# for multistep methods |
| 38 |
K = max(int(2 ** np.ceil(np.log2(8 / group_dt * dt))), 1) |
| 39 |
return K |
| 40 |
|
| 41 |
|
| 42 |
def _generate_cpp_code_1d(values, dt, name): |
| 43 |
def cpp_impl(owner): |
| 44 |
K = _find_K(owner.clock.dt_, dt) |
| 45 |
code = ( |
| 46 |
""" |
| 47 |
static inline double %NAME%(const double t) |
| 48 |
{ |
| 49 |
const double epsilon = %DT% / %K%; |
| 50 |
int i = (int)((t/epsilon + 0.5)/%K%); |
| 51 |
if(i < 0) |
| 52 |
i = 0; |
| 53 |
if(i >= %NUM_VALUES%) |
| 54 |
i = %NUM_VALUES%-1; |
| 55 |
return _namespace%NAME%_values[i]; |
| 56 |
} |
| 57 |
""".replace("%NAME%", name) |
| 58 |
.replace("%DT%", f"{dt:.18f}") |
| 59 |
.replace("%K%", str(K)) |
| 60 |
.replace("%NUM_VALUES%", str(len(values))) |
| 61 |
) |
| 62 |
|
| 63 |
return code |
| 64 |
|
| 65 |
return cpp_impl |
| 66 |
|
| 67 |
|
| 68 |
def _generate_cpp_code_2d(values, dt, name): |
| 69 |
def cpp_impl(owner): |
| 70 |
K = _find_K(owner.clock.dt_, dt) |
| 71 |
support_code = """ |
| 72 |
static inline double %NAME%(const double t, const int i) |
| 73 |
{ |
| 74 |
const double epsilon = %DT% / %K%; |
| 75 |
if (i < 0 || i >= %COLS%) |
| 76 |
return NAN; |
| 77 |
int timestep = (int)((t/epsilon + 0.5)/%K%); |
| 78 |
if(timestep < 0) |
| 79 |
timestep = 0; |
| 80 |
else if(timestep >= %ROWS%) |
| 81 |
timestep = %ROWS%-1; |
| 82 |
return _namespace%NAME%_values[timestep*%COLS% + i]; |
| 83 |
} |
| 84 |
""" |
| 85 |
code = replace( |
| 86 |
support_code, |
| 87 |
{ |
| 88 |
"%NAME%": name, |
| 89 |
"%DT%": f"{dt:.18f}", |
| 90 |
"%K%": str(K), |
| 91 |
"%COLS%": str(values.shape[1]), |
| 92 |
"%ROWS%": str(values.shape[0]), |
| 93 |
}, |
| 94 |
) |
| 95 |
return code |
| 96 |
|
| 97 |
return cpp_impl |
| 98 |
|
| 99 |
|
| 100 |
def _generate_cython_code_1d(values, dt, name): |
| 101 |
def cython_impl(owner): |
| 102 |
K = _find_K(owner.clock.dt_, dt) |
| 103 |
code = ( |
| 104 |
""" |
| 105 |
cdef double %NAME%(const double t): |
| 106 |
global _namespace%NAME%_values |
| 107 |
cdef double epsilon = %DT% / %K% |
| 108 |
cdef int i = (int)((t/epsilon + 0.5)/%K%) |
| 109 |
if i < 0: |
| 110 |
i = 0 |
| 111 |
if i >= %NUM_VALUES%: |
| 112 |
i = %NUM_VALUES% - 1 |
| 113 |
return _namespace%NAME%_values[i] |
| 114 |
""".replace("%NAME%", name) |
| 115 |
.replace("%DT%", f"{dt:.18f}") |
| 116 |
.replace("%K%", str(K)) |
| 117 |
.replace("%NUM_VALUES%", str(len(values))) |
| 118 |
) |
| 119 |
|
| 120 |
return code |
| 121 |
|
| 122 |
return cython_impl |
| 123 |
|
| 124 |
|
| 125 |
def _generate_cython_code_2d(values, dt, name): |
| 126 |
def cython_impl(owner): |
| 127 |
K = _find_K(owner.clock.dt_, dt) |
| 128 |
code = """ |
| 129 |
cdef double %NAME%(const double t, const int i): |
| 130 |
global _namespace%NAME%_values |
| 131 |
cdef double epsilon = %DT% / %K% |
| 132 |
if i < 0 or i >= %COLS%: |
| 133 |
return _numpy.nan |
| 134 |
cdef int timestep = (int)((t/epsilon + 0.5)/%K%) |
| 135 |
if timestep < 0: |
| 136 |
timestep = 0 |
| 137 |
elif timestep >= %ROWS%: |
| 138 |
timestep = %ROWS%-1 |
| 139 |
return _namespace%NAME%_values[timestep*%COLS% + i] |
| 140 |
""" |
| 141 |
code = replace( |
| 142 |
code, |
| 143 |
{ |
| 144 |
"%NAME%": name, |
| 145 |
"%DT%": f"{dt:.18f}", |
| 146 |
"%K%": str(K), |
| 147 |
"%COLS%": str(values.shape[1]), |
| 148 |
"%ROWS%": str(values.shape[0]), |
| 149 |
}, |
| 150 |
) |
| 151 |
return code |
| 152 |
|
| 153 |
return cython_impl |
| 154 |
|
| 155 |
|
| 156 |
class TimedArray(Function, Nameable, CacheKey): |
| 157 |
""" |
| 158 |
TimedArray(values, dt, name=None) |
| 159 |
|
| 160 |
A function of time built from an array of values. The returned object can |
| 161 |
be used as a function, including in model equations etc. The resulting |
| 162 |
function has to be called as `funcion_name(t)` if the provided value array |
| 163 |
is one-dimensional and as `function_name(t, i)` if it is two-dimensional. |
| 164 |
|
| 165 |
Parameters |
| 166 |
---------- |
| 167 |
values : ndarray or `Quantity` |
| 168 |
An array of values providing the values at various points in time. This |
| 169 |
array can either be one- or two-dimensional. If it is two-dimensional |
| 170 |
it's first dimension should be the time. |
| 171 |
dt : `Quantity` |
| 172 |
The time distance between values in the `values` array. |
| 173 |
name : str, optional |
| 174 |
A unique name for this object, see `Nameable` for details. Defaults |
| 175 |
to ``'_timedarray*'``. |
| 176 |
|
| 177 |
Notes |
| 178 |
----- |
| 179 |
For time values corresponding to elements outside of the range of `values` |
| 180 |
provided, the first respectively last element is returned. |
| 181 |
|
| 182 |
Examples |
| 183 |
-------- |
| 184 |
>>> from brian2 import * |
| 185 |
>>> ta = TimedArray([1, 2, 3, 4] * mV, dt=0.1*ms) |
| 186 |
>>> print(ta(0.3*ms)) |
| 187 |
4. mV |
| 188 |
>>> G = NeuronGroup(1, 'v = ta(t) : volt') |
| 189 |
>>> mon = StateMonitor(G, 'v', record=True) |
| 190 |
>>> net = Network(G, mon) |
| 191 |
>>> net.run(1*ms) # doctest: +ELLIPSIS |
| 192 |
... |
| 193 |
>>> print(mon[0].v) |
| 194 |
[ 1. 2. 3. 4. 4. 4. 4. 4. 4. 4.] mV |
| 195 |
>>> ta2d = TimedArray([[1, 2], [3, 4], [5, 6]]*mV, dt=0.1*ms) |
| 196 |
>>> G = NeuronGroup(4, 'v = ta2d(t, i%2) : volt') |
| 197 |
>>> mon = StateMonitor(G, 'v', record=True) |
| 198 |
>>> net = Network(G, mon) |
| 199 |
>>> net.run(0.2*ms) # doctest: +ELLIPSIS |
| 200 |
... |
| 201 |
>>> print(mon.v[:]) |
| 202 |
[[ 1. 3.] |
| 203 |
[ 2. 4.] |
| 204 |
[ 1. 3.] |
| 205 |
[ 2. 4.]] mV |
| 206 |
""" |
| 207 |
|
| 208 |
_cache_irrelevant_attributes = {"_id", "values", "pyfunc", "implementations"} |
| 209 |
|
| 210 |
#: Container for implementing functions for different targets |
| 211 |
#: This container can be extended by other codegeneration targets/devices |
| 212 |
#: The key has to be the name of the target, the value is a tuple of |
| 213 |
#: functions, the first for a 1d array, the second for a 2d array. |
| 214 |
#: The functions have to take three parameters: (values, dt, name), i.e. the |
| 215 |
#: array values, their physical dimensions, the dt of the TimedArray, and |
| 216 |
#: the name of the TimedArray. The functions have to return *a function* |
| 217 |
#: that takes the `owner` argument (out of which they can get the context's |
| 218 |
#: dt as `owner.clock.dt_`) and returns the code. |
| 219 |
implementations = { |
| 220 |
"cpp": (_generate_cpp_code_1d, _generate_cpp_code_2d), |
| 221 |
"cython": (_generate_cython_code_1d, _generate_cython_code_2d), |
| 222 |
} |
| 223 |
|
| 224 |
@check_units(dt=second) |
| 225 |
def __init__(self, values, dt, name=None): |
| 226 |
if name is None: |
| 227 |
name = "_timedarray*" |
| 228 |
Nameable.__init__(self, name) |
| 229 |
dimensions = get_dimensions(values) |
| 230 |
self.dim = dimensions |
| 231 |
values = np.asarray(values, dtype=np.float64) |
| 232 |
self.values = values |
| 233 |
dt = float(dt) |
| 234 |
self.dt = dt |
| 235 |
if values.ndim == 1: |
| 236 |
self._init_1d() |
| 237 |
elif values.ndim == 2: |
| 238 |
self._init_2d() |
| 239 |
else: |
| 240 |
raise NotImplementedError( |
| 241 |
"Only 1d and 2d arrays are supported for TimedArray" |
| 242 |
) |
| 243 |
|
| 244 |
def _init_1d(self): |
| 245 |
dimensions = self.dim |
| 246 |
unit = get_unit(dimensions) |
| 247 |
values = self.values |
| 248 |
dt = self.dt |
| 249 |
|
| 250 |
# Python implementation (with units), used when calling the TimedArray |
| 251 |
# directly, outside of a simulation |
| 252 |
@check_units(t=second, result=unit) |
| 253 |
def timed_array_func(t): |
| 254 |
# We round according to the current defaultclock.dt |
| 255 |
K = _find_K(float(defaultclock.dt), dt) |
| 256 |
epsilon = dt / K |
| 257 |
i = np.clip( |
| 258 |
np.int_(np.round(np.asarray(t / epsilon)) / K), 0, len(values) - 1 |
| 259 |
) |
| 260 |
return Quantity(values[i], dim=dimensions) |
| 261 |
|
| 262 |
Function.__init__(self, pyfunc=timed_array_func) |
| 263 |
|
| 264 |
# we use dynamic implementations because we want to do upsampling |
| 265 |
# in a way that avoids rounding problems with the group's dt |
| 266 |
def create_numpy_implementation(owner): |
| 267 |
group_dt = owner.clock.dt_ |
| 268 |
|
| 269 |
K = _find_K(group_dt, dt) |
| 270 |
n_values = len(values) |
| 271 |
epsilon = dt / K |
| 272 |
|
| 273 |
def unitless_timed_array_func(t): |
| 274 |
timestep = np.clip(np.int_(np.round(t / epsilon) / K), 0, n_values - 1) |
| 275 |
return values[timestep] |
| 276 |
|
| 277 |
unitless_timed_array_func._arg_units = [second] |
| 278 |
unitless_timed_array_func._return_unit = unit |
| 279 |
|
| 280 |
return unitless_timed_array_func |
| 281 |
|
| 282 |
self.implementations.add_dynamic_implementation( |
| 283 |
"numpy", create_numpy_implementation |
| 284 |
) |
| 285 |
namespace = lambda owner: {f"{self.name}_values": self.values} |
| 286 |
|
| 287 |
for target, (func_1d, _) in TimedArray.implementations.items(): |
| 288 |
self.implementations.add_dynamic_implementation( |
| 289 |
target, |
| 290 |
func_1d(self.values, self.dt, self.name), |
| 291 |
namespace=namespace, |
| 292 |
name=self.name, |
| 293 |
) |
| 294 |
|
| 295 |
def _init_2d(self): |
| 296 |
dimensions = self.dim |
| 297 |
unit = get_unit(dimensions) |
| 298 |
values = self.values |
| 299 |
dt = self.dt |
| 300 |
|
| 301 |
# Python implementation (with units), used when calling the TimedArray |
| 302 |
# directly, outside of a simulation |
| 303 |
@check_units(i=1, t=second, result=unit) |
| 304 |
def timed_array_func(t, i): |
| 305 |
# We round according to the current defaultclock.dt |
| 306 |
K = _find_K(float(defaultclock.dt), dt) |
| 307 |
epsilon = dt / K |
| 308 |
time_step = np.clip( |
| 309 |
np.int_(np.round(np.asarray(t / epsilon)) / K), 0, len(values) - 1 |
| 310 |
) |
| 311 |
return Quantity(values[time_step, i], dim=dimensions) |
| 312 |
|
| 313 |
Function.__init__(self, pyfunc=timed_array_func) |
| 314 |
|
| 315 |
# we use dynamic implementations because we want to do upsampling |
| 316 |
# in a way that avoids rounding problems with the group's dt |
| 317 |
def create_numpy_implementation(owner): |
| 318 |
group_dt = owner.clock.dt_ |
| 319 |
|
| 320 |
K = _find_K(group_dt, dt) |
| 321 |
n_values = len(values) |
| 322 |
epsilon = dt / K |
| 323 |
|
| 324 |
def unitless_timed_array_func(t, i): |
| 325 |
timestep = np.clip(np.int_(np.round(t / epsilon) / K), 0, n_values - 1) |
| 326 |
return values[timestep, i] |
| 327 |
|
| 328 |
unitless_timed_array_func._arg_units = [second] |
| 329 |
unitless_timed_array_func._return_unit = unit |
| 330 |
|
| 331 |
return unitless_timed_array_func |
| 332 |
|
| 333 |
self.implementations.add_dynamic_implementation( |
| 334 |
"numpy", create_numpy_implementation |
| 335 |
) |
| 336 |
values_flat = self.values.astype(np.double, order="C", copy=False).ravel() |
| 337 |
namespace = lambda owner: {f"{self.name}_values": values_flat} |
| 338 |
|
| 339 |
for target, (_, func_2d) in TimedArray.implementations.items(): |
| 340 |
self.implementations.add_dynamic_implementation( |
| 341 |
target, |
| 342 |
func_2d(self.values, self.dt, self.name), |
| 343 |
namespace=namespace, |
| 344 |
name=self.name, |
| 345 |
) |
| 346 |
|
| 347 |
def is_locally_constant(self, dt): |
| 348 |
if dt > self.dt: |
| 349 |
return False |
| 350 |
dt_ratio = self.dt / float(dt) |
| 351 |
if np.floor(dt_ratio) != dt_ratio: |
| 352 |
logger.info( |
| 353 |
"dt of the TimedArray is not an integer multiple of " |
| 354 |
"the group's dt, the TimedArray's return value can " |
| 355 |
"therefore not be considered constant over one " |
| 356 |
"timestep, making exact integration impossible.", |
| 357 |
once=True, |
| 358 |
) |
| 359 |
return False |
| 360 |
return True |