| 1 |
import copy |
| 2 |
import logging |
| 3 |
import os |
| 4 |
import tempfile |
| 5 |
import uuid |
| 6 |
import weakref |
| 7 |
|
| 8 |
import numpy as np |
| 9 |
import pytest |
| 10 |
from numpy.testing import assert_array_equal, assert_equal |
| 11 |
|
| 12 |
from brian2 import ( |
| 13 |
BrianLogger, |
| 14 |
BrianObject, |
| 15 |
Clock, |
| 16 |
Hz, |
| 17 |
MagicError, |
| 18 |
MagicNetwork, |
| 19 |
Network, |
| 20 |
NetworkOperation, |
| 21 |
NeuronGroup, |
| 22 |
PoissonGroup, |
| 23 |
PopulationRateMonitor, |
| 24 |
Quantity, |
| 25 |
SpikeGeneratorGroup, |
| 26 |
SpikeMonitor, |
| 27 |
StateMonitor, |
| 28 |
Synapses, |
| 29 |
TimedArray, |
| 30 |
collect, |
| 31 |
defaultclock, |
| 32 |
magic_network, |
| 33 |
ms, |
| 34 |
network_operation, |
| 35 |
prefs, |
| 36 |
profiling_summary, |
| 37 |
restore, |
| 38 |
run, |
| 39 |
second, |
| 40 |
start_scope, |
| 41 |
stop, |
| 42 |
store, |
| 43 |
us, |
| 44 |
) |
| 45 |
from brian2.core.network import schedule_propagation_offset, scheduling_summary |
| 46 |
from brian2.devices.device import ( |
| 47 |
Device, |
| 48 |
RuntimeDevice, |
| 49 |
all_devices, |
| 50 |
device, |
| 51 |
get_device, |
| 52 |
reinit_and_delete, |
| 53 |
reset_device, |
| 54 |
set_device, |
| 55 |
) |
| 56 |
from brian2.tests.utils import assert_allclose |
| 57 |
from brian2.utils.logger import catch_logs |
| 58 |
|
| 59 |
|
| 60 |
@pytest.mark.codegen_independent |
| 61 |
def test_incorrect_network_use(): |
| 62 |
"""Test some wrong uses of `Network` and `MagicNetwork`""" |
| 63 |
with pytest.raises(TypeError): |
| 64 |
Network(name="mynet", anotherkwd="does not exist") |
| 65 |
with pytest.raises(TypeError): |
| 66 |
Network("not a BrianObject") |
| 67 |
net = Network() |
| 68 |
with pytest.raises(TypeError): |
| 69 |
net.add("not a BrianObject") |
| 70 |
with pytest.raises(ValueError): |
| 71 |
MagicNetwork() |
| 72 |
G = NeuronGroup(10, "v:1") |
| 73 |
net.add(G) |
| 74 |
with pytest.raises(TypeError): |
| 75 |
net.remove(object()) |
| 76 |
with pytest.raises(MagicError): |
| 77 |
magic_network.add(G) |
| 78 |
with pytest.raises(MagicError): |
| 79 |
magic_network.remove(G) |
| 80 |
|
| 81 |
|
| 82 |
@pytest.mark.codegen_independent |
| 83 |
def test_network_contains(): |
| 84 |
""" |
| 85 |
Test `Network.__contains__`. |
| 86 |
""" |
| 87 |
G = NeuronGroup(1, "v:1", name="mygroup") |
| 88 |
net = Network(G) |
| 89 |
assert "mygroup" in net |
| 90 |
assert "neurongroup" not in net |
| 91 |
|
| 92 |
|
| 93 |
@pytest.mark.codegen_independent |
| 94 |
def test_empty_network(): |
| 95 |
# Check that an empty network functions correctly |
| 96 |
net = Network() |
| 97 |
net.run(1 * second) |
| 98 |
|
| 99 |
|
| 100 |
class Counter(BrianObject): |
| 101 |
add_to_magic_network = True |
| 102 |
|
| 103 |
def __init__(self, **kwds): |
| 104 |
super().__init__(**kwds) |
| 105 |
self.count = 0 |
| 106 |
self.state = {"state": 0} |
| 107 |
|
| 108 |
def get_states(self, *args, **kwds): |
| 109 |
return dict(self.state) |
| 110 |
|
| 111 |
def set_states(self, values, *args, **kwds): |
| 112 |
for k, v in values.items(): |
| 113 |
self.state[k] = v |
| 114 |
|
| 115 |
def run(self): |
| 116 |
self.count += 1 |
| 117 |
|
| 118 |
|
| 119 |
class CounterWithContained(Counter): |
| 120 |
add_to_magic_network = True |
| 121 |
|
| 122 |
def __init__(self, **kwds): |
| 123 |
super().__init__(**kwds) |
| 124 |
self.sub_counter = Counter() |
| 125 |
self.contained_objects.append(self.sub_counter) |
| 126 |
|
| 127 |
|
| 128 |
@pytest.mark.codegen_independent |
| 129 |
def test_network_single_object(): |
| 130 |
# Check that a network with a single object functions correctly |
| 131 |
x = Counter() |
| 132 |
net = Network(x) |
| 133 |
net.run(1 * ms) |
| 134 |
assert_equal(x.count, 10) |
| 135 |
|
| 136 |
|
| 137 |
@pytest.mark.codegen_independent |
| 138 |
def test_network_two_objects(): |
| 139 |
# Check that a network with two objects and the same clock function correctly |
| 140 |
x = Counter(order=5) |
| 141 |
y = Counter(order=6) |
| 142 |
net = Network() |
| 143 |
net.add([x, [y]]) # check that a funky way of adding objects work correctly |
| 144 |
net.run(1 * ms) |
| 145 |
assert_equal(len(net.objects), 2) |
| 146 |
assert_equal(x.count, 10) |
| 147 |
assert_equal(y.count, 10) |
| 148 |
|
| 149 |
|
| 150 |
@pytest.mark.codegen_independent |
| 151 |
def test_network_from_dict(): |
| 152 |
# Check that a network from a dictionary works |
| 153 |
x = Counter() |
| 154 |
y = Counter() |
| 155 |
d = dict(a=x, b=y) |
| 156 |
net = Network() |
| 157 |
net.add(d) |
| 158 |
net.run(1 * ms) |
| 159 |
assert_equal(len(net.objects), 2) |
| 160 |
assert_equal(x.count, 10) |
| 161 |
assert_equal(y.count, 10) |
| 162 |
|
| 163 |
|
| 164 |
class NameLister(BrianObject): |
| 165 |
add_to_magic_network = True |
| 166 |
updates = [] |
| 167 |
|
| 168 |
def __init__(self, **kwds): |
| 169 |
super().__init__(**kwds) |
| 170 |
|
| 171 |
def run(self): |
| 172 |
NameLister.updates.append(self.name) |
| 173 |
|
| 174 |
|
| 175 |
@pytest.mark.codegen_independent |
| 176 |
def test_network_different_clocks(): |
| 177 |
NameLister.updates[:] = [] |
| 178 |
# Check that a network with two different clocks functions correctly |
| 179 |
x = NameLister(name="x", dt=0.1 * ms, order=0) |
| 180 |
y = NameLister(name="y", dt=1 * ms, order=1) |
| 181 |
net = Network(x, y) |
| 182 |
net.run(100 * second + defaultclock.dt, report="text") |
| 183 |
updates = "".join(NameLister.updates)[2:] # ignore the first time step |
| 184 |
assert updates == ("xxxxxxxxxxy" * 100000) |
| 185 |
|
| 186 |
|
| 187 |
@pytest.mark.codegen_independent |
| 188 |
def test_network_different_when(): |
| 189 |
# Check that a network with different when attributes functions correctly |
| 190 |
NameLister.updates[:] = [] |
| 191 |
x = NameLister(name="x", when="start") |
| 192 |
y = NameLister(name="y", when="end") |
| 193 |
net = Network(x, y) |
| 194 |
net.run(0.3 * ms) |
| 195 |
assert_equal("".join(NameLister.updates), "xyxyxy") |
| 196 |
|
| 197 |
|
| 198 |
@pytest.mark.codegen_independent |
| 199 |
def test_network_default_schedule(): |
| 200 |
net = Network() |
| 201 |
assert net.schedule == [ |
| 202 |
"start", |
| 203 |
"groups", |
| 204 |
"thresholds", |
| 205 |
"synapses", |
| 206 |
"resets", |
| 207 |
"end", |
| 208 |
] |
| 209 |
# Set the preference and check that the change is taken into account |
| 210 |
prefs.core.network.default_schedule = list( |
| 211 |
reversed(["start", "groups", "thresholds", "synapses", "resets", "end"]) |
| 212 |
) |
| 213 |
assert net.schedule == list( |
| 214 |
reversed(["start", "groups", "thresholds", "synapses", "resets", "end"]) |
| 215 |
) |
| 216 |
|
| 217 |
|
| 218 |
@pytest.mark.codegen_independent |
| 219 |
def test_network_schedule_change(): |
| 220 |
# Check that a changed schedule is taken into account correctly |
| 221 |
NameLister.updates[:] = [] |
| 222 |
x = NameLister(name="x", when="thresholds") |
| 223 |
y = NameLister(name="y", when="resets") |
| 224 |
net = Network(x, y) |
| 225 |
net.run(0.3 * ms) |
| 226 |
assert_equal("".join(NameLister.updates), "xyxyxy") |
| 227 |
NameLister.updates[:] = [] |
| 228 |
net.schedule = ["start", "groups", "synapses", "resets", "thresholds", "end"] |
| 229 |
net.run(0.3 * ms) |
| 230 |
assert_equal("".join(NameLister.updates), "yxyxyx") |
| 231 |
|
| 232 |
|
| 233 |
@pytest.mark.codegen_independent |
| 234 |
def test_network_before_after_schedule(): |
| 235 |
# Test that before... and after... slot names can be used |
| 236 |
NameLister.updates[:] = [] |
| 237 |
x = NameLister(name="x", when="before_resets") |
| 238 |
y = NameLister(name="y", when="after_thresholds") |
| 239 |
net = Network(x, y) |
| 240 |
net.schedule = ["thresholds", "resets", "end"] |
| 241 |
net.run(0.3 * ms) |
| 242 |
assert_equal("".join(NameLister.updates), "yxyxyx") |
| 243 |
|
| 244 |
|
| 245 |
@pytest.mark.codegen_independent |
| 246 |
def test_network_custom_slots(): |
| 247 |
# Check that custom slots can be inserted into the schedule |
| 248 |
NameLister.updates[:] = [] |
| 249 |
x = NameLister(name="x", when="thresholds") |
| 250 |
y = NameLister(name="y", when="in_between") |
| 251 |
z = NameLister(name="z", when="resets") |
| 252 |
net = Network(x, y, z) |
| 253 |
net.schedule = [ |
| 254 |
"start", |
| 255 |
"groups", |
| 256 |
"thresholds", |
| 257 |
"in_between", |
| 258 |
"synapses", |
| 259 |
"resets", |
| 260 |
"end", |
| 261 |
] |
| 262 |
net.run(0.3 * ms) |
| 263 |
assert_equal("".join(NameLister.updates), "xyzxyzxyz") |
| 264 |
|
| 265 |
|
| 266 |
@pytest.mark.codegen_independent |
| 267 |
def test_network_incorrect_schedule(): |
| 268 |
# Test that incorrect arguments provided to schedule raise errors |
| 269 |
net = Network() |
| 270 |
# net.schedule = object() |
| 271 |
with pytest.raises(TypeError): |
| 272 |
net.schedule = object() |
| 273 |
# net.schedule = 1 |
| 274 |
with pytest.raises(TypeError): |
| 275 |
net.schedule = 1 |
| 276 |
# net.schedule = {'slot1', 'slot2'} |
| 277 |
with pytest.raises(TypeError): |
| 278 |
net.schedule = {"slot1", "slot2"} |
| 279 |
# net.schedule = ['slot', 1] |
| 280 |
with pytest.raises(TypeError): |
| 281 |
net.schedule = ["slot", 1] |
| 282 |
# net.schedule = ['start', 'after_start'] |
| 283 |
with pytest.raises(ValueError): |
| 284 |
net.schedule = ["start", "after_start"] |
| 285 |
# net.schedule = ['before_start', 'start'] |
| 286 |
with pytest.raises(ValueError): |
| 287 |
net.schedule = ["before_start", "start"] |
| 288 |
|
| 289 |
|
| 290 |
@pytest.mark.codegen_independent |
| 291 |
def test_schedule_warning(): |
| 292 |
previous_device = get_device() |
| 293 |
from uuid import uuid4 |
| 294 |
|
| 295 |
# TestDevice1 supports arbitrary schedules, TestDevice2 does not |
| 296 |
class TestDevice1(Device): |
| 297 |
# These functions are needed during the setup of the defaultclock |
| 298 |
def get_value(self, var): |
| 299 |
return np.array([0.0001]) |
| 300 |
|
| 301 |
def add_array(self, var): |
| 302 |
pass |
| 303 |
|
| 304 |
def init_with_zeros(self, var, dtype): |
| 305 |
pass |
| 306 |
|
| 307 |
def fill_with_array(self, var, arr): |
| 308 |
pass |
| 309 |
|
| 310 |
class TestDevice2(TestDevice1): |
| 311 |
def __init__(self): |
| 312 |
super().__init__() |
| 313 |
self.network_schedule = [ |
| 314 |
"start", |
| 315 |
"groups", |
| 316 |
"synapses", |
| 317 |
"thresholds", |
| 318 |
"resets", |
| 319 |
"end", |
| 320 |
] |
| 321 |
|
| 322 |
# Unique names are important for getting the warnings again for multiple |
| 323 |
# runs of the test suite |
| 324 |
name1 = f"testdevice_{str(uuid4())}" |
| 325 |
name2 = f"testdevice_{str(uuid4())}" |
| 326 |
all_devices[name1] = TestDevice1() |
| 327 |
all_devices[name2] = TestDevice2() |
| 328 |
|
| 329 |
set_device(name1) |
| 330 |
assert schedule_propagation_offset() == 0 * ms |
| 331 |
net = Network() |
| 332 |
assert schedule_propagation_offset(net) == 0 * ms |
| 333 |
|
| 334 |
# Any schedule should work |
| 335 |
net.schedule = list(reversed(net.schedule)) |
| 336 |
with catch_logs() as l: |
| 337 |
net.run(0 * ms) |
| 338 |
assert len(l) == 0, "did not expect a warning" |
| 339 |
|
| 340 |
assert schedule_propagation_offset(net) == defaultclock.dt |
| 341 |
|
| 342 |
set_device(name2) |
| 343 |
assert schedule_propagation_offset() == defaultclock.dt |
| 344 |
|
| 345 |
# Using the correct schedule should work |
| 346 |
net.schedule = ["start", "groups", "synapses", "thresholds", "resets", "end"] |
| 347 |
with catch_logs() as l: |
| 348 |
net.run(0 * ms) |
| 349 |
assert len(l) == 0, "did not expect a warning" |
| 350 |
assert schedule_propagation_offset(net) == defaultclock.dt |
| 351 |
|
| 352 |
# Using another (e.g. the default) schedule should raise a warning |
| 353 |
net.schedule = None |
| 354 |
with catch_logs() as l: |
| 355 |
net.run(0 * ms) |
| 356 |
assert len(l) == 1 and l[0][1].endswith("schedule_conflict") |
| 357 |
reset_device(previous_device) |
| 358 |
|
| 359 |
|
| 360 |
@pytest.mark.codegen_independent |
| 361 |
def test_scheduling_summary_magic(): |
| 362 |
basename = f"name{str(uuid.uuid4()).replace('-', '_')}" |
| 363 |
group = NeuronGroup( |
| 364 |
10, "dv/dt = -v/(10*ms) : 1", threshold="v>1", reset="v=1", name=basename |
| 365 |
) |
| 366 |
group.run_regularly("v = rand()", dt=defaultclock.dt * 10, when="end") |
| 367 |
state_mon = StateMonitor(group, "v", record=True, name=f"{basename}_sm") |
| 368 |
inactive_state_mon = StateMonitor( |
| 369 |
group, "v", record=True, name=f"{basename}_sm_ia", when="after_end" |
| 370 |
) |
| 371 |
inactive_state_mon.active = False |
| 372 |
summary_before = scheduling_summary() |
| 373 |
|
| 374 |
assert [entry.name for entry in summary_before.entries] == [ |
| 375 |
f"{basename}_sm", |
| 376 |
f"{basename}_stateupdater", |
| 377 |
f"{basename}_spike_thresholder", |
| 378 |
f"{basename}_spike_resetter", |
| 379 |
f"{basename}_run_regularly", |
| 380 |
f"{basename}_sm_ia", |
| 381 |
] |
| 382 |
assert [entry.when for entry in summary_before.entries] == [ |
| 383 |
"start", |
| 384 |
"groups", |
| 385 |
"thresholds", |
| 386 |
"resets", |
| 387 |
"end", |
| 388 |
"after_end", |
| 389 |
] |
| 390 |
assert [entry.dt for entry in summary_before.entries] == [ |
| 391 |
defaultclock.dt, |
| 392 |
defaultclock.dt, |
| 393 |
defaultclock.dt, |
| 394 |
defaultclock.dt, |
| 395 |
defaultclock.dt * 10, |
| 396 |
defaultclock.dt, |
| 397 |
] |
| 398 |
assert [entry.active for entry in summary_before.entries] == [ |
| 399 |
True, |
| 400 |
True, |
| 401 |
True, |
| 402 |
True, |
| 403 |
True, |
| 404 |
False, |
| 405 |
] |
| 406 |
assert len(str(summary_before)) |
| 407 |
assert len(summary_before._repr_html_()) |
| 408 |
run(defaultclock.dt) |
| 409 |
summary_after = scheduling_summary() |
| 410 |
assert str(summary_after) == str(summary_before) |
| 411 |
assert summary_after._repr_html_() == summary_before._repr_html_() |
| 412 |
|
| 413 |
|
| 414 |
@pytest.mark.codegen_independent |
| 415 |
def test_scheduling_summary(): |
| 416 |
basename = f"name{str(uuid.uuid4()).replace('-', '_')}" |
| 417 |
group = NeuronGroup( |
| 418 |
10, "dv/dt = -v/(10*ms) : 1", threshold="v>1", reset="v=1", name=basename |
| 419 |
) |
| 420 |
group.run_regularly("v = rand()", dt=defaultclock.dt * 10, when="end") |
| 421 |
state_mon = StateMonitor(group, "v", record=True, name=f"{basename}_sm") |
| 422 |
inactive_state_mon = StateMonitor( |
| 423 |
group, "v", record=True, name=f"{basename}_sm_ia", when="after_end" |
| 424 |
) |
| 425 |
inactive_state_mon.active = False |
| 426 |
|
| 427 |
@network_operation(name=f"{basename}_net_op", when="before_end") |
| 428 |
def foo(): |
| 429 |
pass |
| 430 |
|
| 431 |
net = Network(group, state_mon, inactive_state_mon, foo) |
| 432 |
summary_before = scheduling_summary(net) |
| 433 |
assert [entry.name for entry in summary_before.entries] == [ |
| 434 |
f"{basename}_sm", |
| 435 |
f"{basename}_stateupdater", |
| 436 |
f"{basename}_spike_thresholder", |
| 437 |
f"{basename}_spike_resetter", |
| 438 |
f"{basename}_net_op", |
| 439 |
f"{basename}_run_regularly", |
| 440 |
f"{basename}_sm_ia", |
| 441 |
] |
| 442 |
assert [entry.when for entry in summary_before.entries] == [ |
| 443 |
"start", |
| 444 |
"groups", |
| 445 |
"thresholds", |
| 446 |
"resets", |
| 447 |
"before_end", |
| 448 |
"end", |
| 449 |
"after_end", |
| 450 |
] |
| 451 |
assert [entry.dt for entry in summary_before.entries] == [ |
| 452 |
defaultclock.dt, |
| 453 |
defaultclock.dt, |
| 454 |
defaultclock.dt, |
| 455 |
defaultclock.dt, |
| 456 |
defaultclock.dt, |
| 457 |
defaultclock.dt * 10, |
| 458 |
defaultclock.dt, |
| 459 |
] |
| 460 |
assert [entry.active for entry in summary_before.entries] == [ |
| 461 |
True, |
| 462 |
True, |
| 463 |
True, |
| 464 |
True, |
| 465 |
True, |
| 466 |
True, |
| 467 |
False, |
| 468 |
] |
| 469 |
assert len(str(summary_before)) |
| 470 |
assert len(summary_before._repr_html_()) |
| 471 |
run(defaultclock.dt) |
| 472 |
summary_after = scheduling_summary(net) |
| 473 |
assert str(summary_after) == str(summary_before) |
| 474 |
assert summary_after._repr_html_() == summary_before._repr_html_() |
| 475 |
|
| 476 |
|
| 477 |
class Preparer(BrianObject): |
| 478 |
add_to_magic_network = True |
| 479 |
|
| 480 |
def __init__(self, **kwds): |
| 481 |
super().__init__(**kwds) |
| 482 |
self.did_reinit = False |
| 483 |
self.did_pre_run = False |
| 484 |
self.did_post_run = False |
| 485 |
|
| 486 |
def reinit(self, level=0): |
| 487 |
self.did_reinit = True |
| 488 |
|
| 489 |
def before_run(self, namespace=None, level=0): |
| 490 |
self.did_pre_run = True |
| 491 |
|
| 492 |
def after_run(self): |
| 493 |
self.did_post_run = True |
| 494 |
|
| 495 |
|
| 496 |
@pytest.mark.codegen_independent |
| 497 |
def test_magic_network(): |
| 498 |
# test that magic network functions correctly |
| 499 |
x = Counter() |
| 500 |
y = Counter() |
| 501 |
run(10 * ms) |
| 502 |
assert_equal(x.count, 100) |
| 503 |
assert_equal(y.count, 100) |
| 504 |
|
| 505 |
assert len(repr(magic_network)) # very basic test... |
| 506 |
assert len(str(magic_network)) # very basic test... |
| 507 |
|
| 508 |
|
| 509 |
class Stopper(BrianObject): |
| 510 |
add_to_magic_network = True |
| 511 |
|
| 512 |
def __init__(self, stoptime, stopfunc, **kwds): |
| 513 |
super().__init__(**kwds) |
| 514 |
self.stoptime = stoptime |
| 515 |
self.stopfunc = stopfunc |
| 516 |
|
| 517 |
def run(self): |
| 518 |
self.stoptime -= 1 |
| 519 |
if self.stoptime <= 0: |
| 520 |
self.stopfunc() |
| 521 |
|
| 522 |
|
| 523 |
@pytest.mark.codegen_independent |
| 524 |
def test_network_stop(): |
| 525 |
# test that Network.stop and global stop() work correctly |
| 526 |
net = Network() |
| 527 |
x = Stopper(10, net.stop) |
| 528 |
net.add(x) |
| 529 |
net.run(10 * ms) |
| 530 |
assert_equal(defaultclock.t, 1 * ms) |
| 531 |
|
| 532 |
x = Stopper(10, stop) |
| 533 |
net = Network(x) |
| 534 |
net.run(10 * ms) |
| 535 |
assert_equal(defaultclock.t, 1 * ms) |
| 536 |
|
| 537 |
|
| 538 |
@pytest.mark.codegen_independent |
| 539 |
def test_network_operations(): |
| 540 |
# test NetworkOperation and network_operation |
| 541 |
seq = [] |
| 542 |
|
| 543 |
def f1(): |
| 544 |
seq.append("a") |
| 545 |
|
| 546 |
op1 = NetworkOperation(f1, when="start", order=1) |
| 547 |
|
| 548 |
@network_operation |
| 549 |
def f2(): |
| 550 |
seq.append("b") |
| 551 |
|
| 552 |
@network_operation(when="end", order=1) |
| 553 |
def f3(): |
| 554 |
seq.append("c") |
| 555 |
|
| 556 |
# In complex frameworks, network operations might be object methods that |
| 557 |
# access some common data |
| 558 |
class Container: |
| 559 |
def __init__(self): |
| 560 |
self.g1_data = "B" |
| 561 |
self.g2_data = "C" |
| 562 |
|
| 563 |
def g1(self): |
| 564 |
seq.append(self.g1_data) |
| 565 |
|
| 566 |
def g2(self): |
| 567 |
seq.append(self.g2_data) |
| 568 |
|
| 569 |
c = Container() |
| 570 |
c_op1 = NetworkOperation(c.g1) |
| 571 |
c_op2 = NetworkOperation(c.g2, when="end", order=1) |
| 572 |
net = Network(op1, f2, f3, c_op1, c_op2) |
| 573 |
net.run(1 * ms) |
| 574 |
|
| 575 |
assert_equal("".join(seq), "bBacC" * 10) |
| 576 |
|
| 577 |
|
| 578 |
@pytest.mark.codegen_independent |
| 579 |
def test_incorrect_network_operations(): |
| 580 |
# Network operations with more than one argument are not allowed |
| 581 |
def func(x, y): |
| 582 |
pass |
| 583 |
|
| 584 |
class Container: |
| 585 |
def func(self, x, y): |
| 586 |
pass |
| 587 |
|
| 588 |
c = Container() |
| 589 |
|
| 590 |
with pytest.raises(TypeError): |
| 591 |
NetworkOperation(func) |
| 592 |
with pytest.raises(TypeError): |
| 593 |
NetworkOperation(c.func) |
| 594 |
|
| 595 |
# Incorrect use of @network_operation -- it does not work on an instance |
| 596 |
# method |
| 597 |
try: |
| 598 |
|
| 599 |
class Container: |
| 600 |
@network_operation |
| 601 |
def func(self): |
| 602 |
pass |
| 603 |
|
| 604 |
raise AssertionError("expected a TypeError") |
| 605 |
except TypeError: |
| 606 |
pass # this is what we expected |
| 607 |
|
| 608 |
|
| 609 |
@pytest.mark.codegen_independent |
| 610 |
def test_network_operations_name(): |
| 611 |
# test NetworkOperation name input |
| 612 |
seq = [] |
| 613 |
|
| 614 |
def f1(): |
| 615 |
seq.append("a") |
| 616 |
|
| 617 |
def f2(): |
| 618 |
seq.append("b") |
| 619 |
|
| 620 |
def x(): |
| 621 |
pass |
| 622 |
|
| 623 |
op = NetworkOperation(lambda: x) |
| 624 |
assert_equal(op.name, "networkoperation") |
| 625 |
|
| 626 |
op0 = NetworkOperation(lambda: x, name="named_network") |
| 627 |
assert_equal(op0.name, "named_network") |
| 628 |
|
| 629 |
op1 = NetworkOperation(f1, name="networkoperation_1") |
| 630 |
op2 = NetworkOperation(f1, name="networkoperation_3") |
| 631 |
op3 = NetworkOperation(f2, name="networkoperation_2") |
| 632 |
|
| 633 |
net = Network(op1, op2, op3) |
| 634 |
net.run(1 * ms) |
| 635 |
|
| 636 |
assert_equal("".join(seq), "aba" * 10) |
| 637 |
|
| 638 |
|
| 639 |
@pytest.mark.codegen_independent |
| 640 |
def test_network_active_flag(): |
| 641 |
# test that the BrianObject.active flag is recognised by Network.run |
| 642 |
x = Counter() |
| 643 |
y = Counter() |
| 644 |
y.active = False |
| 645 |
run(1 * ms) |
| 646 |
assert_equal(x.count, 10) |
| 647 |
assert_equal(y.count, 0) |
| 648 |
|
| 649 |
|
| 650 |
@pytest.mark.standalone_compatible |
| 651 |
@pytest.mark.multiple_runs |
| 652 |
def test_spikes_after_deactivating(): |
| 653 |
# Make sure that a spike in the last time step gets cleared. See #1319 |
| 654 |
always_spike = NeuronGroup(1, "", threshold="True", reset="") |
| 655 |
spike_mon = SpikeMonitor(always_spike) |
| 656 |
run(defaultclock.dt) |
| 657 |
always_spike.active = False |
| 658 |
run(defaultclock.dt) |
| 659 |
device.build(direct_call=False, **device.build_options) |
| 660 |
assert_equal(spike_mon.t[:], [0] * second) |
| 661 |
|
| 662 |
|
| 663 |
@pytest.mark.codegen_independent |
| 664 |
def test_network_t(): |
| 665 |
# test that Network.t works as expected |
| 666 |
x = Counter(dt=1 * ms) |
| 667 |
y = Counter(dt=2 * ms) |
| 668 |
net = Network(x, y) |
| 669 |
net.run(4 * ms) |
| 670 |
assert_equal(net.t, 4 * ms) |
| 671 |
net.run(1 * ms) |
| 672 |
assert_equal(net.t, 5 * ms) |
| 673 |
assert_equal(x.count, 5) |
| 674 |
assert_equal(y.count, 3) |
| 675 |
net.run(0.5 * ms) # should only update x |
| 676 |
assert_equal(net.t, 5.5 * ms) |
| 677 |
assert_equal(x.count, 6) |
| 678 |
assert_equal(y.count, 3) |
| 679 |
net.run(0.5 * ms) # shouldn't do anything |
| 680 |
assert_equal(net.t, 6 * ms) |
| 681 |
assert_equal(x.count, 6) |
| 682 |
assert_equal(y.count, 3) |
| 683 |
net.run(0.5 * ms) # should update x and y |
| 684 |
assert_equal(net.t, 6.5 * ms) |
| 685 |
assert_equal(x.count, 7) |
| 686 |
assert_equal(y.count, 4) |
| 687 |
|
| 688 |
del x, y, net |
| 689 |
|
| 690 |
# now test with magic run |
| 691 |
x = Counter(dt=1 * ms) |
| 692 |
y = Counter(dt=2 * ms) |
| 693 |
run(4 * ms) |
| 694 |
assert_equal(magic_network.t, 4 * ms) |
| 695 |
assert_equal(x.count, 4) |
| 696 |
assert_equal(y.count, 2) |
| 697 |
run(4 * ms) |
| 698 |
assert_equal(magic_network.t, 8 * ms) |
| 699 |
assert_equal(x.count, 8) |
| 700 |
assert_equal(y.count, 4) |
| 701 |
run(1 * ms) |
| 702 |
assert_equal(magic_network.t, 9 * ms) |
| 703 |
assert_equal(x.count, 9) |
| 704 |
assert_equal(y.count, 5) |
| 705 |
|
| 706 |
|
| 707 |
@pytest.mark.codegen_independent |
| 708 |
def test_incorrect_dt_defaultclock(): |
| 709 |
defaultclock.dt = 0.5 * ms |
| 710 |
G = NeuronGroup(1, "dv/dt = -v / (10*ms) : 1") |
| 711 |
net = Network(G) |
| 712 |
net.run(0.5 * ms) |
| 713 |
defaultclock.dt = 1 * ms |
| 714 |
with pytest.raises(ValueError): |
| 715 |
net.run(0 * ms) |
| 716 |
|
| 717 |
|
| 718 |
@pytest.mark.codegen_independent |
| 719 |
def test_incorrect_dt_custom_clock(): |
| 720 |
clock = Clock(dt=0.5 * ms) |
| 721 |
G = NeuronGroup(1, "dv/dt = -v / (10*ms) : 1", clock=clock) |
| 722 |
net = Network(G) |
| 723 |
net.run(0.5 * ms) |
| 724 |
clock.dt = 1 * ms |
| 725 |
with pytest.raises(ValueError): |
| 726 |
net.run(0 * ms) |
| 727 |
|
| 728 |
|
| 729 |
@pytest.mark.codegen_independent |
| 730 |
def test_network_remove(): |
| 731 |
x = Counter() |
| 732 |
y = Counter() |
| 733 |
net = Network(x, y) |
| 734 |
net.remove(y) |
| 735 |
net.run(1 * ms) |
| 736 |
assert_equal(x.count, 10) |
| 737 |
assert_equal(y.count, 0) |
| 738 |
# the relevance of this test is when we use weakref.proxy objects in |
| 739 |
# Network.objects, we should be able to add and remove these from |
| 740 |
# the Network just as much as the original objects |
| 741 |
# TODO: Does this test make sense now that Network does not store weak |
| 742 |
# references by default? |
| 743 |
for obj in copy.copy(net.objects): |
| 744 |
net.remove(obj) |
| 745 |
net.run(1 * ms) |
| 746 |
assert_equal(x.count, 10) |
| 747 |
assert_equal(y.count, 0) |
| 748 |
|
| 749 |
|
| 750 |
@pytest.mark.codegen_independent |
| 751 |
def test_contained_objects(): |
| 752 |
obj = CounterWithContained() |
| 753 |
net = Network(obj) |
| 754 |
# The contained object should not be stored explicitly |
| 755 |
assert len(net.objects) == 1 |
| 756 |
# It should be accessible via the network interface, though |
| 757 |
assert len(net) == 2 |
| 758 |
net.run(defaultclock.dt) |
| 759 |
|
| 760 |
# The contained object should be executed during the run |
| 761 |
assert obj.count == 1 |
| 762 |
assert obj.sub_counter.count == 1 |
| 763 |
|
| 764 |
# contained objects should be accessible via get_states/set_states |
| 765 |
states = net.get_states() |
| 766 |
assert len(states) == 2 |
| 767 |
assert set(states.keys()) == {obj.name, obj.sub_counter.name} |
| 768 |
assert set(states[obj.name].keys()) == {"state"} |
| 769 |
assert set(states[obj.sub_counter.name].keys()) == {"state"} |
| 770 |
net[obj.name].set_states({"state": 1}) |
| 771 |
net[obj.sub_counter.name].set_states({"state": 2}) |
| 772 |
|
| 773 |
net.remove(obj) |
| 774 |
assert len(net.objects) == 0 |
| 775 |
assert len(net) == 0 |
| 776 |
assert len(net.get_states()) == 0 |
| 777 |
net.run(defaultclock.dt) |
| 778 |
assert obj.count == 1 |
| 779 |
assert obj.sub_counter.count == 1 |
| 780 |
|
| 781 |
|
| 782 |
class NoninvalidatingCounter(Counter): |
| 783 |
add_to_magic_network = True |
| 784 |
invalidates_magic_network = False |
| 785 |
|
| 786 |
|
| 787 |
@pytest.mark.codegen_independent |
| 788 |
def test_invalid_magic_network(): |
| 789 |
x = Counter() |
| 790 |
run(1 * ms) |
| 791 |
assert_equal(x.count, 10) |
| 792 |
y = Counter() |
| 793 |
try: |
| 794 |
run(1 * ms) |
| 795 |
raise AssertionError("Expected a MagicError") |
| 796 |
except MagicError: |
| 797 |
pass # this is expected |
| 798 |
del x, y |
| 799 |
x = Counter() |
| 800 |
run(1 * ms) |
| 801 |
y = NoninvalidatingCounter() |
| 802 |
run(1 * ms) |
| 803 |
assert_equal(x.count, 20) |
| 804 |
assert_equal(y.count, 10) |
| 805 |
del y |
| 806 |
run(1 * ms) |
| 807 |
assert_equal(x.count, 30) |
| 808 |
del x |
| 809 |
x = Counter() |
| 810 |
run(1 * ms) |
| 811 |
assert_equal(magic_network.t, 1 * ms) |
| 812 |
del x |
| 813 |
x = Counter() |
| 814 |
y = Counter() |
| 815 |
run(1 * ms) |
| 816 |
assert_equal(x.count, 10) |
| 817 |
assert_equal(y.count, 10) |
| 818 |
|
| 819 |
|
| 820 |
@pytest.mark.codegen_independent |
| 821 |
def test_multiple_networks_invalid(): |
| 822 |
x = Counter() |
| 823 |
net = Network(x) |
| 824 |
net.run(1 * ms) |
| 825 |
try: |
| 826 |
run(1 * ms) |
| 827 |
raise AssertionError("Expected a RuntimeError") |
| 828 |
except RuntimeError: |
| 829 |
pass # this is expected |
| 830 |
|
| 831 |
try: |
| 832 |
net2 = Network(x) |
| 833 |
raise AssertionError("Expected a RuntimeError") |
| 834 |
except RuntimeError: |
| 835 |
pass # this is expected |
| 836 |
|
| 837 |
|
| 838 |
@pytest.mark.codegen_independent |
| 839 |
def test_magic_weak_reference(): |
| 840 |
""" |
| 841 |
Test that holding a weak reference to an object does not make it get |
| 842 |
simulated.""" |
| 843 |
|
| 844 |
G1 = NeuronGroup(1, "v:1") |
| 845 |
|
| 846 |
# this object should not be included |
| 847 |
G2 = weakref.ref(NeuronGroup(1, "v:1")) |
| 848 |
|
| 849 |
with catch_logs(log_level=logging.DEBUG) as l: |
| 850 |
run(1 * ms) |
| 851 |
# Check the debug messages for the number of included objects |
| 852 |
magic_objects = [ |
| 853 |
msg[2] for msg in l if msg[1] == "brian2.core.magic.magic_objects" |
| 854 |
][0] |
| 855 |
assert "2 objects" in magic_objects, f"Unexpected log message: {magic_objects}" |
| 856 |
|
| 857 |
|
| 858 |
@pytest.mark.codegen_independent |
| 859 |
def test_magic_unused_object(): |
| 860 |
"""Test that creating unused objects does not affect the magic system.""" |
| 861 |
|
| 862 |
def create_group(): |
| 863 |
# Produce two objects but return only one |
| 864 |
G1 = NeuronGroup(1, "v:1") # no Thresholder or Resetter |
| 865 |
G2 = NeuronGroup(1, "v:1") # This object should be garbage collected |
| 866 |
return G1 |
| 867 |
|
| 868 |
G = create_group() |
| 869 |
with catch_logs(log_level=logging.DEBUG) as l: |
| 870 |
run(1 * ms) |
| 871 |
|
| 872 |
# Check the debug messages for the number of included objects |
| 873 |
magic_objects = [ |
| 874 |
msg[2] for msg in l if msg[1] == "brian2.core.magic.magic_objects" |
| 875 |
][0] |
| 876 |
assert "2 objects" in magic_objects, f"Unexpected log message: {magic_objects}" |
| 877 |
|
| 878 |
|
| 879 |
@pytest.mark.codegen_independent |
| 880 |
def test_network_access(): |
| 881 |
x = Counter(name="counter") |
| 882 |
net = Network(x) |
| 883 |
assert len(net) == 1 |
| 884 |
assert len(repr(net)) # very basic test... |
| 885 |
assert len(str(net)) # very basic test... |
| 886 |
|
| 887 |
# accessing objects |
| 888 |
assert net["counter"] is x |
| 889 |
with pytest.raises(TypeError): |
| 890 |
net[123] |
| 891 |
with pytest.raises(TypeError): |
| 892 |
net[1:3] |
| 893 |
with pytest.raises(KeyError): |
| 894 |
net["non-existing"] |
| 895 |
|
| 896 |
objects = [obj for obj in net] |
| 897 |
assert set(objects) == set(net.objects) |
| 898 |
|
| 899 |
# deleting objects |
| 900 |
del net["counter"] |
| 901 |
with pytest.raises(TypeError): |
| 902 |
net.__delitem__(123) |
| 903 |
with pytest.raises(TypeError): |
| 904 |
net.__delitem__(slice(1, 3)) |
| 905 |
with pytest.raises(KeyError): |
| 906 |
net.__delitem__("counter") |
| 907 |
|
| 908 |
|
| 909 |
@pytest.mark.codegen_independent |
| 910 |
def test_dependency_check(): |
| 911 |
def create_net(): |
| 912 |
G = NeuronGroup(10, "v: 1", threshold="False") |
| 913 |
dependent_objects = [ |
| 914 |
StateMonitor(G, "v", record=True), |
| 915 |
SpikeMonitor(G), |
| 916 |
PopulationRateMonitor(G), |
| 917 |
Synapses(G, G, on_pre="v+=1"), |
| 918 |
] |
| 919 |
return dependent_objects |
| 920 |
|
| 921 |
dependent_objects = create_net() |
| 922 |
# Trying to simulate the monitors/synapses without the group should fail |
| 923 |
for obj in dependent_objects: |
| 924 |
with pytest.raises(ValueError): |
| 925 |
Network(obj).run(0 * ms) |
| 926 |
|
| 927 |
# simulation with a magic network should work when we have an explicit |
| 928 |
# reference to one of the objects, but the object should be inactive and |
| 929 |
# we should get a warning |
| 930 |
assert all(obj.active for obj in dependent_objects) |
| 931 |
for obj in dependent_objects: # obj is our explicit reference |
| 932 |
with catch_logs() as l: |
| 933 |
run(0 * ms) |
| 934 |
dependency_warnings = [ |
| 935 |
msg[2] for msg in l if msg[1] == "brian2.core.magic.dependency_warning" |
| 936 |
] |
| 937 |
assert len(dependency_warnings) == 1 |
| 938 |
assert not obj.active |
| 939 |
|
| 940 |
|
| 941 |
def test_loop(): |
| 942 |
""" |
| 943 |
Somewhat realistic test with a loop of magic networks |
| 944 |
""" |
| 945 |
|
| 946 |
def run_simulation(): |
| 947 |
G = NeuronGroup(10, "dv/dt = -v / (10*ms) : 1", reset="v=0", threshold="v>1") |
| 948 |
G.v = np.linspace(0, 1, 10) |
| 949 |
run(1 * ms) |
| 950 |
# We return potentially problematic references to a VariableView |
| 951 |
return G.v |
| 952 |
|
| 953 |
# First run |
| 954 |
with catch_logs(log_level=logging.DEBUG) as l: |
| 955 |
v = run_simulation() |
| 956 |
assert v[0] == 0 and 0 < v[-1] < 1 |
| 957 |
# Check the debug messages for the number of included objects |
| 958 |
magic_objects = [ |
| 959 |
msg[2] for msg in l if msg[1] == "brian2.core.magic.magic_objects" |
| 960 |
][0] |
| 961 |
assert "4 objects" in magic_objects |
| 962 |
|
| 963 |
# Second run |
| 964 |
with catch_logs(log_level=logging.DEBUG) as l: |
| 965 |
v = run_simulation() |
| 966 |
assert v[0] == 0 and 0 < v[-1] < 1 |
| 967 |
# Check the debug messages for the number of included objects |
| 968 |
magic_objects = [ |
| 969 |
msg[2] for msg in l if msg[1] == "brian2.core.magic.magic_objects" |
| 970 |
][0] |
| 971 |
assert "4 objects" in magic_objects |
| 972 |
|
| 973 |
|
| 974 |
@pytest.mark.codegen_independent |
| 975 |
def test_magic_collect(): |
| 976 |
""" |
| 977 |
Make sure all expected objects are collected in a magic network |
| 978 |
""" |
| 979 |
P = PoissonGroup(10, rates=100 * Hz) |
| 980 |
G = NeuronGroup(10, "v:1", threshold="False") |
| 981 |
S = Synapses(G, G, "") |
| 982 |
|
| 983 |
state_mon = StateMonitor(G, "v", record=True) |
| 984 |
spike_mon = SpikeMonitor(G) |
| 985 |
rate_mon = PopulationRateMonitor(G) |
| 986 |
|
| 987 |
objects = collect() |
| 988 |
|
| 989 |
assert len(objects) == 6, f"expected {6} objects, got {len(objects)}" |
| 990 |
|
| 991 |
|
| 992 |
import sys |
| 993 |
from contextlib import contextmanager |
| 994 |
from io import StringIO |
| 995 |
|
| 996 |
|
| 997 |
@contextmanager |
| 998 |
def captured_output(): |
| 999 |
new_out, new_err = StringIO(), StringIO() |
| 1000 |
old_out, old_err = sys.stdout, sys.stderr |
| 1001 |
try: |
| 1002 |
sys.stdout, sys.stderr = new_out, new_err |
| 1003 |
yield sys.stdout, sys.stderr |
| 1004 |
finally: |
| 1005 |
sys.stdout, sys.stderr = old_out, old_err |
| 1006 |
|
| 1007 |
|
| 1008 |
@pytest.mark.codegen_independent |
| 1009 |
def test_progress_report(): |
| 1010 |
""" |
| 1011 |
Very basic test of progress reporting |
| 1012 |
""" |
| 1013 |
G = NeuronGroup(1, "") |
| 1014 |
net = Network(G) |
| 1015 |
|
| 1016 |
# No output |
| 1017 |
with captured_output() as (out, err): |
| 1018 |
net.run(1 * ms, report=None) |
| 1019 |
# There should be at least two lines of output |
| 1020 |
out, err = out.getvalue(), err.getvalue() |
| 1021 |
assert len(out) == 0 and len(err) == 0 |
| 1022 |
|
| 1023 |
with captured_output() as (out, err): |
| 1024 |
net.run(1 * ms) |
| 1025 |
# There should be at least two lines of output |
| 1026 |
out, err = out.getvalue(), err.getvalue() |
| 1027 |
assert len(out) == 0 and len(err) == 0 |
| 1028 |
|
| 1029 |
# Progress should go to stdout |
| 1030 |
with captured_output() as (out, err): |
| 1031 |
net.run(1 * ms, report="text") |
| 1032 |
# There should be at least two lines of output |
| 1033 |
out, err = out.getvalue(), err.getvalue() |
| 1034 |
assert len(out.split("\n")) >= 2 and len(err) == 0 |
| 1035 |
|
| 1036 |
with captured_output() as (out, err): |
| 1037 |
net.run(1 * ms, report="stdout") |
| 1038 |
# There should be at least two lines of output |
| 1039 |
out, err = out.getvalue(), err.getvalue() |
| 1040 |
assert len(out.split("\n")) >= 2 and len(err) == 0 |
| 1041 |
|
| 1042 |
# Progress should go to stderr |
| 1043 |
with captured_output() as (out, err): |
| 1044 |
net.run(1 * ms, report="stderr") |
| 1045 |
# There should be at least two lines of output |
| 1046 |
out, err = out.getvalue(), err.getvalue() |
| 1047 |
assert len(err.split("\n")) >= 2 and len(out) == 0 |
| 1048 |
|
| 1049 |
# Custom function |
| 1050 |
calls = [] |
| 1051 |
|
| 1052 |
def capture_progress(elapsed, complete, start, duration): |
| 1053 |
calls.append((elapsed, complete, start, duration)) |
| 1054 |
|
| 1055 |
with captured_output() as (out, err): |
| 1056 |
net.run(1 * ms, report=capture_progress) |
| 1057 |
out, err = out.getvalue(), err.getvalue() |
| 1058 |
|
| 1059 |
assert len(err) == 0 and len(out) == 0 |
| 1060 |
# There should be at least a call for the start and the end |
| 1061 |
assert len(calls) >= 2 and calls[0][1] == 0.0 and calls[-1][1] == 1.0 |
| 1062 |
|
| 1063 |
|
| 1064 |
@pytest.mark.codegen_independent |
| 1065 |
def test_progress_report_incorrect(): |
| 1066 |
""" |
| 1067 |
Test wrong use of the report option |
| 1068 |
""" |
| 1069 |
G = NeuronGroup(1, "") |
| 1070 |
net = Network(G) |
| 1071 |
with pytest.raises(ValueError): |
| 1072 |
net.run(1 * ms, report="unknown") |
| 1073 |
with pytest.raises(TypeError): |
| 1074 |
net.run(1 * ms, report=object()) |
| 1075 |
|
| 1076 |
|
| 1077 |
@pytest.mark.standalone_compatible |
| 1078 |
@pytest.mark.multiple_runs |
| 1079 |
def test_multiple_runs_report_standalone(): |
| 1080 |
group = NeuronGroup(1, "dv/dt = 1*Hz : 1") |
| 1081 |
run(1 * ms, report="text") |
| 1082 |
run(1 * ms) |
| 1083 |
device.build(direct_call=False, **device.build_options) |
| 1084 |
|
| 1085 |
|
| 1086 |
@pytest.mark.standalone_compatible |
| 1087 |
@pytest.mark.multiple_runs |
| 1088 |
def test_multiple_runs_report_standalone_2(): |
| 1089 |
group = NeuronGroup(1, "dv/dt = 1*Hz : 1") |
| 1090 |
run(1 * ms) |
| 1091 |
run(1 * ms, report="text") |
| 1092 |
device.build(direct_call=False, **device.build_options) |
| 1093 |
|
| 1094 |
|
| 1095 |
@pytest.mark.standalone_compatible |
| 1096 |
@pytest.mark.multiple_runs |
| 1097 |
def test_multiple_runs_report_standalone_3(): |
| 1098 |
group = NeuronGroup(1, "dv/dt = 1*Hz : 1") |
| 1099 |
run(1 * ms, report="text") |
| 1100 |
run(1 * ms, report="text") |
| 1101 |
device.build(direct_call=False, **device.build_options) |
| 1102 |
|
| 1103 |
|
| 1104 |
# This tests a specific limitation of the C++ standalone mode (cannot mix |
| 1105 |
# multiple report methods) |
| 1106 |
@pytest.mark.cpp_standalone |
| 1107 |
@pytest.mark.standalone_only |
| 1108 |
def test_multiple_runs_report_standalone_incorrect(): |
| 1109 |
set_device("cpp_standalone", build_on_run=False) |
| 1110 |
group = NeuronGroup(1, "dv/dt = 1*Hz : 1") |
| 1111 |
run(1 * ms, report="text") |
| 1112 |
with pytest.raises(NotImplementedError): |
| 1113 |
run(1 * ms, report="stderr") |
| 1114 |
|
| 1115 |
|
| 1116 |
@pytest.mark.codegen_independent |
| 1117 |
def test_store_restore(): |
| 1118 |
source = NeuronGroup( |
| 1119 |
10, |
| 1120 |
"""dv/dt = rates : 1 |
| 1121 |
rates : Hz""", |
| 1122 |
threshold="v>1", |
| 1123 |
reset="v=0", |
| 1124 |
) |
| 1125 |
source.rates = "i*100*Hz" |
| 1126 |
target = NeuronGroup(10, "v:1") |
| 1127 |
synapses = Synapses(source, target, model="w:1", on_pre="v+=w") |
| 1128 |
synapses.connect(j="i") |
| 1129 |
synapses.w = "i*1.0" |
| 1130 |
synapses.delay = "i*ms" |
| 1131 |
state_mon = StateMonitor(target, "v", record=True) |
| 1132 |
spike_mon = SpikeMonitor(source) |
| 1133 |
net = Network(source, target, synapses, state_mon, spike_mon) |
| 1134 |
net.store() # default time slot |
| 1135 |
net.run(10 * ms) |
| 1136 |
net.store("second") |
| 1137 |
net.run(10 * ms) |
| 1138 |
v_values = state_mon.v[:, :] |
| 1139 |
spike_indices, spike_times = spike_mon.it_ |
| 1140 |
net.restore() # Go back to beginning |
| 1141 |
assert defaultclock.t == 0 * ms |
| 1142 |
assert net.t == 0 * ms |
| 1143 |
net.run(20 * ms) |
| 1144 |
assert_equal(v_values, state_mon.v[:, :]) |
| 1145 |
assert_equal(spike_indices, spike_mon.i[:]) |
| 1146 |
assert_equal(spike_times, spike_mon.t_[:]) |
| 1147 |
|
| 1148 |
# Go back to middle |
| 1149 |
net.restore("second") |
| 1150 |
assert defaultclock.t == 10 * ms |
| 1151 |
assert net.t == 10 * ms |
| 1152 |
net.run(10 * ms) |
| 1153 |
assert_equal(v_values, state_mon.v[:, :]) |
| 1154 |
assert_equal(spike_indices, spike_mon.i[:]) |
| 1155 |
assert_equal(spike_times, spike_mon.t_[:]) |
| 1156 |
|
| 1157 |
# Go back again (see github issue #681) |
| 1158 |
net.restore("second") |
| 1159 |
assert defaultclock.t == 10 * ms |
| 1160 |
assert net.t == 10 * ms |
| 1161 |
|
| 1162 |
|
| 1163 |
@pytest.mark.codegen_independent |
| 1164 |
def test_restore_from_python_spikequeue(): |
| 1165 |
""" |
| 1166 |
Now we do a regression test for backwards compatibility to test restore from Python spike queue format |
| 1167 |
using the old Python spike queue implementation (before pythonSpikeQueue was completely removed). |
| 1168 |
|
| 1169 |
The challenge: The two implementations store spike queues differently: |
| 1170 |
- Python format: (time, spike_array, dimensions) where spike_array is |
| 1171 |
a 2D numpy array of [delay_slot, synapse_index] pairs |
| 1172 |
- Cython format: (offset, spike_lists) where spike_lists is a list of |
| 1173 |
lists, one per delay time slot |
| 1174 |
|
| 1175 |
Our conversion code in `Synapses._convert_queue_state_if_needed` handles |
| 1176 |
the translation from Python to Cython format during restore. |
| 1177 |
""" |
| 1178 |
import os |
| 1179 |
|
| 1180 |
test_file = os.path.join( |
| 1181 |
os.path.dirname(__file__), |
| 1182 |
"data", |
| 1183 |
"python_spikequeue_test_network_test_store_restore_named.pkl", |
| 1184 |
) |
| 1185 |
|
| 1186 |
if not os.path.exists(test_file): |
| 1187 |
pytest.skip( |
| 1188 |
"Cannot test restore from a pickle file with old SpikeQueue state - " |
| 1189 |
"file does not exist." |
| 1190 |
) |
| 1191 |
|
| 1192 |
# First we run a reference simulation to get expected behavior |
| 1193 |
source_ref = NeuronGroup( |
| 1194 |
10, |
| 1195 |
"""dv/dt = rates : 1 |
| 1196 |
rates : Hz""", |
| 1197 |
threshold="v>1", |
| 1198 |
reset="v=0", |
| 1199 |
) |
| 1200 |
source_ref.rates = "i*100*Hz" |
| 1201 |
target_ref = NeuronGroup(10, "v:1") |
| 1202 |
synapses_ref = Synapses(source_ref, target_ref, model="w:1", on_pre="v+=w") |
| 1203 |
synapses_ref.connect(j="i") |
| 1204 |
synapses_ref.w = "i*1.0" |
| 1205 |
synapses_ref.delay = "i*ms" |
| 1206 |
net_ref = Network(source_ref, target_ref, synapses_ref) |
| 1207 |
|
| 1208 |
# Run reference to 20ms and capture final state |
| 1209 |
net_ref.run(20 * ms) |
| 1210 |
ref_target_v = target_ref.v[:].copy() |
| 1211 |
ref_source_v = source_ref.v[:].copy() |
| 1212 |
|
| 1213 |
# Now we test restoration from Python spike queue using our pickle file we created using older pythonSpikeQueue |
| 1214 |
# Create network with explicit names matching the ones in pickle ( note we did this to avoid auto naming brian does ) |
| 1215 |
source2 = NeuronGroup( |
| 1216 |
10, |
| 1217 |
"""dv/dt = rates : 1 |
| 1218 |
rates : Hz""", |
| 1219 |
threshold="v>1", |
| 1220 |
reset="v=0", |
| 1221 |
name="source_for_restore", |
| 1222 |
) |
| 1223 |
source2.rates = "i*100*Hz" |
| 1224 |
target2 = NeuronGroup(10, "v:1", name="target_for_restore") |
| 1225 |
synapses2 = Synapses( |
| 1226 |
source2, target2, model="w:1", on_pre="v+=w", name="synapses_for_restore" |
| 1227 |
) |
| 1228 |
synapses2.connect(j="i") |
| 1229 |
synapses2.w = "i*1.0" |
| 1230 |
synapses2.delay = "i*ms" |
| 1231 |
net2 = Network(source2, target2, synapses2) |
| 1232 |
|
| 1233 |
# Restore from Python spike queue format (at t=10ms) |
| 1234 |
net2.restore(filename=test_file) |
| 1235 |
assert net2.t == 10 * ms |
| 1236 |
assert defaultclock.t == 10 * ms |
| 1237 |
|
| 1238 |
# Continue to 20ms |
| 1239 |
net2.run(10 * ms) |
| 1240 |
|
| 1241 |
# After running to 20ms, the final states should match the reference |
| 1242 |
# If spike queue conversion failed, spikes wouldn't be delivered |
| 1243 |
# correctly and final states would differ |
| 1244 |
assert_allclose( |
| 1245 |
ref_target_v, |
| 1246 |
target2.v[:], |
| 1247 |
err_msg="Python spike queue restoration: target final state doesn't match", |
| 1248 |
) |
| 1249 |
assert_allclose( |
| 1250 |
ref_source_v, |
| 1251 |
source2.v[:], |
| 1252 |
err_msg="Python spike queue restoration: source final state doesn't match", |
| 1253 |
) |
| 1254 |
|
| 1255 |
|
| 1256 |
@pytest.mark.codegen_independent |
| 1257 |
def test_store_restore_to_file(): |
| 1258 |
filename = tempfile.mktemp(suffix="state", prefix="brian_test") |
| 1259 |
source = NeuronGroup( |
| 1260 |
10, |
| 1261 |
""" |
| 1262 |
dv/dt = rates : 1 |
| 1263 |
rates : Hz |
| 1264 |
""", |
| 1265 |
threshold="v>1", |
| 1266 |
reset="v=0", |
| 1267 |
) |
| 1268 |
source.rates = "i*100*Hz" |
| 1269 |
target = NeuronGroup(10, "v:1") |
| 1270 |
synapses = Synapses(source, target, model="w:1", on_pre="v+=w") |
| 1271 |
synapses.connect(j="i") |
| 1272 |
synapses.w = "i*1.0" |
| 1273 |
synapses.delay = "i*ms" |
| 1274 |
state_mon = StateMonitor(target, "v", record=True) |
| 1275 |
spike_mon = SpikeMonitor(source) |
| 1276 |
net = Network(source, target, synapses, state_mon, spike_mon) |
| 1277 |
net.store(filename=filename) # default time slot |
| 1278 |
net.run(10 * ms) |
| 1279 |
net.store("second", filename=filename) |
| 1280 |
net.run(10 * ms) |
| 1281 |
v_values = state_mon.v[:, :] |
| 1282 |
spike_indices, spike_times = spike_mon.it_ |
| 1283 |
|
| 1284 |
net.restore(filename=filename) # Go back to beginning |
| 1285 |
assert defaultclock.t == 0 * ms |
| 1286 |
assert net.t == 0 * ms |
| 1287 |
net.run(20 * ms) |
| 1288 |
assert_equal(v_values, state_mon.v[:, :]) |
| 1289 |
assert_equal(spike_indices, spike_mon.i[:]) |
| 1290 |
assert_equal(spike_times, spike_mon.t_[:]) |
| 1291 |
|
| 1292 |
# Go back to middle |
| 1293 |
net.restore("second", filename=filename) |
| 1294 |
assert defaultclock.t == 10 * ms |
| 1295 |
assert net.t == 10 * ms |
| 1296 |
net.run(10 * ms) |
| 1297 |
assert_equal(v_values, state_mon.v[:, :]) |
| 1298 |
assert_equal(spike_indices, spike_mon.i[:]) |
| 1299 |
assert_equal(spike_times, spike_mon.t_[:]) |
| 1300 |
try: |
| 1301 |
os.remove(filename) |
| 1302 |
except OSError: |
| 1303 |
pass |
| 1304 |
|
| 1305 |
|
| 1306 |
@pytest.mark.codegen_independent |
| 1307 |
def test_store_restore_to_file_new_objects(): |
| 1308 |
# A more realistic test where the objects are completely re-created |
| 1309 |
filename = tempfile.mktemp(suffix="state", prefix="brian_test") |
| 1310 |
|
| 1311 |
def create_net(): |
| 1312 |
# Use a bit of a complicated spike and connection pattern with |
| 1313 |
# heterogeneous delays |
| 1314 |
|
| 1315 |
# Note: it is important that all objects have the same name, this would |
| 1316 |
# be the case if we were running this in a new process but to not rely |
| 1317 |
# on garbage collection we will assign explicit names here |
| 1318 |
source = SpikeGeneratorGroup( |
| 1319 |
5, |
| 1320 |
np.arange(5).repeat(3), |
| 1321 |
[3, 4, 1, 2, 3, 7, 5, 4, 1, 0, 5, 9, 7, 8, 9] * ms, |
| 1322 |
name="source", |
| 1323 |
) |
| 1324 |
target = NeuronGroup(10, "v:1", name="target") |
| 1325 |
synapses = Synapses(source, target, model="w:1", on_pre="v+=w", name="synapses") |
| 1326 |
synapses.connect("j>=i") |
| 1327 |
synapses.w = "i*1.0 + j*2.0" |
| 1328 |
synapses.delay = "(5-i)*ms" |
| 1329 |
state_mon = StateMonitor(target, "v", record=True, name="statemonitor") |
| 1330 |
input_spikes = SpikeMonitor(source, name="input_spikes") |
| 1331 |
net = Network(source, target, synapses, state_mon, input_spikes) |
| 1332 |
return net |
| 1333 |
|
| 1334 |
net = create_net() |
| 1335 |
net.store(filename=filename) # default time slot |
| 1336 |
net.run(5 * ms) |
| 1337 |
net.store("second", filename=filename) |
| 1338 |
net.run(5 * ms) |
| 1339 |
input_spike_indices = np.array(net["input_spikes"].i) |
| 1340 |
input_spike_times = Quantity(net["input_spikes"].t, copy=True) |
| 1341 |
v_values_full_sim = Quantity(net["statemonitor"].v[:, :], copy=True) |
| 1342 |
|
| 1343 |
net = create_net() |
| 1344 |
net.restore(filename=filename) # Go back to beginning |
| 1345 |
net.run(10 * ms) |
| 1346 |
assert_equal(input_spike_indices, net["input_spikes"].i) |
| 1347 |
assert_equal(input_spike_times, net["input_spikes"].t) |
| 1348 |
assert_equal(v_values_full_sim, net["statemonitor"].v[:, :]) |
| 1349 |
|
| 1350 |
net = create_net() |
| 1351 |
net.restore("second", filename=filename) # Go back to middle |
| 1352 |
net.run(5 * ms) |
| 1353 |
assert_equal(input_spike_indices, net["input_spikes"].i) |
| 1354 |
assert_equal(input_spike_times, net["input_spikes"].t) |
| 1355 |
assert_equal(v_values_full_sim, net["statemonitor"].v[:, :]) |
| 1356 |
|
| 1357 |
try: |
| 1358 |
os.remove(filename) |
| 1359 |
except OSError: |
| 1360 |
pass |
| 1361 |
|
| 1362 |
|
| 1363 |
@pytest.mark.codegen_independent |
| 1364 |
def test_store_restore_to_file_differing_nets(): |
| 1365 |
# Check that the store/restore mechanism is not used with differing |
| 1366 |
# networks |
| 1367 |
filename = tempfile.mktemp(suffix="state", prefix="brian_test") |
| 1368 |
|
| 1369 |
source = SpikeGeneratorGroup( |
| 1370 |
5, [0, 1, 2, 3, 4], [0, 1, 2, 3, 4] * ms, name="source_1" |
| 1371 |
) |
| 1372 |
mon = SpikeMonitor(source, name="monitor") |
| 1373 |
net = Network(source, mon) |
| 1374 |
net.store(filename=filename) |
| 1375 |
|
| 1376 |
source_2 = SpikeGeneratorGroup( |
| 1377 |
5, [0, 1, 2, 3, 4], [0, 1, 2, 3, 4] * ms, name="source_2" |
| 1378 |
) |
| 1379 |
mon = SpikeMonitor(source_2, name="monitor") |
| 1380 |
net = Network(source_2, mon) |
| 1381 |
with pytest.raises(KeyError): |
| 1382 |
net.restore(filename=filename) |
| 1383 |
|
| 1384 |
net = Network(source) # Without the monitor |
| 1385 |
with pytest.raises(KeyError): |
| 1386 |
net.restore(filename=filename) |
| 1387 |
|
| 1388 |
|
| 1389 |
@pytest.mark.codegen_independent |
| 1390 |
def test_store_restore_magic(): |
| 1391 |
source = NeuronGroup( |
| 1392 |
10, |
| 1393 |
""" |
| 1394 |
dv/dt = rates : 1 |
| 1395 |
rates : Hz |
| 1396 |
""", |
| 1397 |
threshold="v>1", |
| 1398 |
reset="v=0", |
| 1399 |
) |
| 1400 |
source.rates = "i*100*Hz" |
| 1401 |
target = NeuronGroup(10, "v:1") |
| 1402 |
synapses = Synapses(source, target, model="w:1", on_pre="v+=w") |
| 1403 |
synapses.connect(j="i") |
| 1404 |
synapses.w = "i*1.0" |
| 1405 |
synapses.delay = "i*ms" |
| 1406 |
state_mon = StateMonitor(target, "v", record=True) |
| 1407 |
spike_mon = SpikeMonitor(source) |
| 1408 |
store() # default time slot |
| 1409 |
run(10 * ms) |
| 1410 |
store("second") |
| 1411 |
run(10 * ms) |
| 1412 |
v_values = state_mon.v[:, :] |
| 1413 |
spike_indices, spike_times = spike_mon.it_ |
| 1414 |
|
| 1415 |
restore() # Go back to beginning |
| 1416 |
assert magic_network.t == 0 * ms |
| 1417 |
run(20 * ms) |
| 1418 |
assert defaultclock.t == 20 * ms |
| 1419 |
assert_equal(v_values, state_mon.v[:, :]) |
| 1420 |
assert_equal(spike_indices, spike_mon.i[:]) |
| 1421 |
assert_equal(spike_times, spike_mon.t_[:]) |
| 1422 |
|
| 1423 |
# Go back to middle |
| 1424 |
restore("second") |
| 1425 |
assert magic_network.t == 10 * ms |
| 1426 |
run(10 * ms) |
| 1427 |
assert defaultclock.t == 20 * ms |
| 1428 |
assert_equal(v_values, state_mon.v[:, :]) |
| 1429 |
assert_equal(spike_indices, spike_mon.i[:]) |
| 1430 |
assert_equal(spike_times, spike_mon.t_[:]) |
| 1431 |
|
| 1432 |
|
| 1433 |
@pytest.mark.codegen_independent |
| 1434 |
def test_store_restore_magic_to_file(): |
| 1435 |
filename = tempfile.mktemp(suffix="state", prefix="brian_test") |
| 1436 |
source = NeuronGroup( |
| 1437 |
10, |
| 1438 |
""" |
| 1439 |
dv/dt = rates : 1 |
| 1440 |
rates : Hz |
| 1441 |
""", |
| 1442 |
threshold="v>1", |
| 1443 |
reset="v=0", |
| 1444 |
) |
| 1445 |
source.rates = "i*100*Hz" |
| 1446 |
target = NeuronGroup(10, "v:1") |
| 1447 |
synapses = Synapses(source, target, model="w:1", on_pre="v+=w") |
| 1448 |
synapses.connect(j="i") |
| 1449 |
synapses.w = "i*1.0" |
| 1450 |
synapses.delay = "i*ms" |
| 1451 |
state_mon = StateMonitor(target, "v", record=True) |
| 1452 |
spike_mon = SpikeMonitor(source) |
| 1453 |
store(filename=filename) # default time slot |
| 1454 |
run(10 * ms) |
| 1455 |
store("second", filename=filename) |
| 1456 |
run(10 * ms) |
| 1457 |
v_values = state_mon.v[:, :] |
| 1458 |
spike_indices, spike_times = spike_mon.it_ |
| 1459 |
|
| 1460 |
restore(filename=filename) # Go back to beginning |
| 1461 |
assert magic_network.t == 0 * ms |
| 1462 |
run(20 * ms) |
| 1463 |
assert defaultclock.t == 20 * ms |
| 1464 |
assert_equal(v_values, state_mon.v[:, :]) |
| 1465 |
assert_equal(spike_indices, spike_mon.i[:]) |
| 1466 |
assert_equal(spike_times, spike_mon.t_[:]) |
| 1467 |
|
| 1468 |
# Go back to middle |
| 1469 |
restore("second", filename=filename) |
| 1470 |
assert magic_network.t == 10 * ms |
| 1471 |
run(10 * ms) |
| 1472 |
assert defaultclock.t == 20 * ms |
| 1473 |
assert_equal(v_values, state_mon.v[:, :]) |
| 1474 |
assert_equal(spike_indices, spike_mon.i[:]) |
| 1475 |
assert_equal(spike_times, spike_mon.t_[:]) |
| 1476 |
try: |
| 1477 |
os.remove(filename) |
| 1478 |
except OSError: |
| 1479 |
pass |
| 1480 |
|
| 1481 |
|
| 1482 |
@pytest.mark.codegen_independent |
| 1483 |
def test_store_restore_spikequeue(): |
| 1484 |
# See github issue #938 |
| 1485 |
source = SpikeGeneratorGroup(1, [0], [0] * ms) |
| 1486 |
target = NeuronGroup(1, "v : 1") |
| 1487 |
conn = Synapses(source, target, on_pre="v += 1", delay=2 * defaultclock.dt) |
| 1488 |
conn.connect() |
| 1489 |
run(defaultclock.dt) # Spike is not yet delivered |
| 1490 |
store() |
| 1491 |
run(2 * defaultclock.dt) |
| 1492 |
assert target.v[0] == 1 |
| 1493 |
restore() |
| 1494 |
run(2 * defaultclock.dt) |
| 1495 |
assert target.v[0] == 1 |
| 1496 |
restore() |
| 1497 |
run(2 * defaultclock.dt) |
| 1498 |
assert target.v[0] == 1 |
| 1499 |
|
| 1500 |
|
| 1501 |
@pytest.mark.codegen_independent |
| 1502 |
def test_store_restore_delays(): |
| 1503 |
group = NeuronGroup(5, "v:1", threshold="False") |
| 1504 |
syn = Synapses(group, group, on_pre="v+=1") |
| 1505 |
syn.connect() |
| 1506 |
syn.delay = np.arange(25) * 0.1 * ms |
| 1507 |
store() |
| 1508 |
syn.delay = 0 * ms |
| 1509 |
restore() |
| 1510 |
assert_allclose(syn.delay[:], np.arange(25) * 0.1 * ms) |
| 1511 |
|
| 1512 |
|
| 1513 |
@pytest.mark.skipif( |
| 1514 |
not isinstance(get_device(), RuntimeDevice), |
| 1515 |
reason="Getting/setting random number state only supported for runtime device.", |
| 1516 |
) |
| 1517 |
def test_restore_with_random_state(): |
| 1518 |
group = NeuronGroup(10, "dv/dt = -v/(10*ms) + (10*ms)**-0.5*xi : 1", method="euler") |
| 1519 |
group.v = "rand()" |
| 1520 |
mon = StateMonitor(group, "v", record=True) |
| 1521 |
store() |
| 1522 |
run(10 * ms) |
| 1523 |
old_v = np.array(group.v) |
| 1524 |
|
| 1525 |
restore() # Random state is not restored |
| 1526 |
run(10 * ms) |
| 1527 |
assert np.var(old_v - group.v) > 0 # very basic test for difference |
| 1528 |
|
| 1529 |
restore(restore_random_state=True) # Random state is restored |
| 1530 |
run(10 * ms) |
| 1531 |
assert_equal(old_v, group.v) |
| 1532 |
|
| 1533 |
|
| 1534 |
@pytest.mark.codegen_independent |
| 1535 |
def test_store_restore_restore_synapses(): |
| 1536 |
group = NeuronGroup(10, "x : 1", threshold="False", reset="", name="group") |
| 1537 |
synapses = Synapses(group, group, on_pre="x += 1", name="synapses") |
| 1538 |
synapses.connect(i=[1, 3, 5], j=[6, 4, 2]) |
| 1539 |
net = Network(group, synapses) |
| 1540 |
|
| 1541 |
tmp_file = tempfile.mktemp() |
| 1542 |
net.store(filename=tmp_file) |
| 1543 |
|
| 1544 |
# clear up |
| 1545 |
del net |
| 1546 |
del synapses |
| 1547 |
del group |
| 1548 |
|
| 1549 |
# Recreate the network without connecting the synapses |
| 1550 |
group = NeuronGroup(10, "x: 1", threshold="False", reset="", name="group") |
| 1551 |
synapses = Synapses(group, group, "", on_pre="x += 1", name="synapses") |
| 1552 |
net = Network(group, synapses) |
| 1553 |
try: |
| 1554 |
net.restore(filename=tmp_file) |
| 1555 |
|
| 1556 |
assert len(synapses) == 3 |
| 1557 |
assert_array_equal(synapses.i, [1, 3, 5]) |
| 1558 |
assert_array_equal(synapses.j, [6, 4, 2]) |
| 1559 |
|
| 1560 |
# Tunning the network should not raise an error, despite the lack |
| 1561 |
# of Synapses.connect |
| 1562 |
net.run(0 * ms) |
| 1563 |
finally: |
| 1564 |
os.remove(tmp_file) |
| 1565 |
|
| 1566 |
|
| 1567 |
@pytest.mark.codegen_independent |
| 1568 |
def test_defaultclock_dt_changes(): |
| 1569 |
BrianLogger.suppress_name("resolution_conflict") |
| 1570 |
for dt in [0.1 * ms, 0.01 * ms, 0.5 * ms, 1 * ms, 3.3 * ms]: |
| 1571 |
defaultclock.dt = dt |
| 1572 |
G = NeuronGroup(1, "v:1") |
| 1573 |
mon = StateMonitor(G, "v", record=True) |
| 1574 |
net = Network(G, mon) |
| 1575 |
net.run(2 * dt) |
| 1576 |
assert_equal(mon.t[:], [0, dt / ms] * ms) |
| 1577 |
|
| 1578 |
|
| 1579 |
@pytest.mark.standalone_compatible |
| 1580 |
@pytest.mark.multiple_runs |
| 1581 |
def test_dt_changes_between_runs(): |
| 1582 |
defaultclock.dt = 0.1 * ms |
| 1583 |
G = NeuronGroup(1, "v:1") |
| 1584 |
mon = StateMonitor(G, "v", record=True) |
| 1585 |
run(0.5 * ms) |
| 1586 |
defaultclock.dt = 0.5 * ms |
| 1587 |
run(0.5 * ms) |
| 1588 |
defaultclock.dt = 0.1 * ms |
| 1589 |
run(0.5 * ms) |
| 1590 |
device.build(direct_call=False, **device.build_options) |
| 1591 |
assert len(mon.t[:]) == 5 + 1 + 5 |
| 1592 |
assert_allclose( |
| 1593 |
mon.t[:], [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 1.0, 1.1, 1.2, 1.3, 1.4] * ms |
| 1594 |
) |
| 1595 |
|
| 1596 |
|
| 1597 |
@pytest.mark.codegen_independent |
| 1598 |
def test_dt_restore(): |
| 1599 |
defaultclock.dt = 0.5 * ms |
| 1600 |
G = NeuronGroup(1, "dv/dt = -v/(10*ms) : 1") |
| 1601 |
mon = StateMonitor(G, "v", record=True) |
| 1602 |
net = Network(G, mon) |
| 1603 |
net.store() |
| 1604 |
|
| 1605 |
net.run(1 * ms) |
| 1606 |
assert_equal(mon.t[:], [0, 0.5] * ms) |
| 1607 |
defaultclock.dt = 1 * ms |
| 1608 |
net.run(2 * ms) |
| 1609 |
assert_equal(mon.t[:], [0, 0.5, 1, 2] * ms) |
| 1610 |
net.restore() |
| 1611 |
assert_equal(mon.t[:], []) |
| 1612 |
net.run(1 * ms) |
| 1613 |
assert defaultclock.dt == 0.5 * ms |
| 1614 |
assert_equal(mon.t[:], [0, 0.5] * ms) |
| 1615 |
|
| 1616 |
|
| 1617 |
@pytest.mark.codegen_independent |
| 1618 |
def test_continuation(): |
| 1619 |
defaultclock.dt = 1 * ms |
| 1620 |
G = NeuronGroup(1, "dv/dt = -v / (10*ms) : 1") |
| 1621 |
G.v = 1 |
| 1622 |
mon = StateMonitor(G, "v", record=True) |
| 1623 |
net = Network(G, mon) |
| 1624 |
net.run(2 * ms) |
| 1625 |
|
| 1626 |
# Run the same simulation but with two runs that use sub-dt run times |
| 1627 |
G2 = NeuronGroup(1, "dv/dt = -v / (10*ms) : 1") |
| 1628 |
G2.v = 1 |
| 1629 |
mon2 = StateMonitor(G2, "v", record=True) |
| 1630 |
net2 = Network(G2, mon2) |
| 1631 |
net2.run(0.5 * ms) |
| 1632 |
net2.run(1.5 * ms) |
| 1633 |
|
| 1634 |
assert_equal(mon.t[:], mon2.t[:]) |
| 1635 |
assert_equal(mon.v[:], mon2.v[:]) |
| 1636 |
|
| 1637 |
|
| 1638 |
@pytest.mark.codegen_independent |
| 1639 |
def test_get_set_states(): |
| 1640 |
G = NeuronGroup(10, "v:1", name="a_neurongroup") |
| 1641 |
G.v = "i" |
| 1642 |
net = Network(G) |
| 1643 |
states1 = net.get_states() |
| 1644 |
states2 = magic_network.get_states() |
| 1645 |
states3 = net.get_states(read_only_variables=False) |
| 1646 |
assert ( |
| 1647 |
set(states1.keys()) |
| 1648 |
== set(states2.keys()) |
| 1649 |
== set(states3.keys()) |
| 1650 |
== {"a_neurongroup"} |
| 1651 |
) |
| 1652 |
assert ( |
| 1653 |
set(states1["a_neurongroup"].keys()) |
| 1654 |
== set(states2["a_neurongroup"].keys()) |
| 1655 |
== {"i", "dt", "N", "t", "v", "t_in_timesteps"} |
| 1656 |
) |
| 1657 |
assert set(states3["a_neurongroup"]) == {"v"} |
| 1658 |
|
| 1659 |
# Try re-setting the state |
| 1660 |
G.v = 0 |
| 1661 |
net.set_states(states3) |
| 1662 |
assert_equal(G.v, np.arange(10)) |
| 1663 |
|
| 1664 |
|
| 1665 |
@pytest.mark.codegen_independent |
| 1666 |
def test_multiple_runs_defaultclock(): |
| 1667 |
defaultclock.dt = 0.1 * ms |
| 1668 |
G = NeuronGroup(1, "dv/dt = -v / (10*ms) : 1") |
| 1669 |
net = Network(G) |
| 1670 |
net.run(0.5 * ms) |
| 1671 |
|
| 1672 |
# The new dt is not compatible with the previous time but it should not |
| 1673 |
# raise an error because we start a new simulation at time 0 |
| 1674 |
defaultclock.dt = 1 * ms |
| 1675 |
G = NeuronGroup(1, "dv/dt = -v / (10*ms) : 1") |
| 1676 |
net = Network(G) |
| 1677 |
net.run(1 * ms) |
| 1678 |
|
| 1679 |
|
| 1680 |
@pytest.mark.codegen_independent |
| 1681 |
def test_multiple_runs_defaultclock_incorrect(): |
| 1682 |
defaultclock.dt = 0.1 * ms |
| 1683 |
G = NeuronGroup(1, "dv/dt = -v / (10*ms) : 1") |
| 1684 |
net = Network(G) |
| 1685 |
net.run(0.5 * ms) |
| 1686 |
|
| 1687 |
# The new dt is not compatible with the previous time since we cannot |
| 1688 |
# continue at 0.5ms with a dt of 1ms |
| 1689 |
defaultclock.dt = 1 * ms |
| 1690 |
with pytest.raises(ValueError): |
| 1691 |
net.run(1 * ms) |
| 1692 |
|
| 1693 |
|
| 1694 |
@pytest.mark.standalone_compatible |
| 1695 |
def test_profile(): |
| 1696 |
G = NeuronGroup( |
| 1697 |
10, |
| 1698 |
"dv/dt = -v / (10*ms) : 1", |
| 1699 |
threshold="v>1", |
| 1700 |
reset="v=0", |
| 1701 |
name="profile_test", |
| 1702 |
) |
| 1703 |
G.v = 1.1 |
| 1704 |
net = Network(G) |
| 1705 |
net.run(1 * ms, profile=True) |
| 1706 |
# The should be four simulated CodeObjects, one for the group and one each |
| 1707 |
# for state update, threshold and reset + 1 for the clock |
| 1708 |
info = net.profiling_info |
| 1709 |
info_dict = dict(info) |
| 1710 |
# Standalone does not include the NeuronGroup object (which is not doing |
| 1711 |
# anything during the run) in the profiling information, while runtime |
| 1712 |
# does |
| 1713 |
assert 3 <= len(info) <= 4 |
| 1714 |
assert len(info) == 3 or "profile_test" in info_dict |
| 1715 |
for obj in ["stateupdater", "spike_thresholder", "spike_resetter"]: |
| 1716 |
name = f"profile_test_{obj}" |
| 1717 |
assert name in info_dict or f"{name}_codeobject" in info_dict |
| 1718 |
assert all([t >= 0 * second for _, t in info]) |
| 1719 |
|
| 1720 |
|
| 1721 |
@pytest.mark.standalone_compatible |
| 1722 |
def test_profile_off(): |
| 1723 |
G = NeuronGroup( |
| 1724 |
10, |
| 1725 |
"dv/dt = -v / (10*ms) : 1", |
| 1726 |
threshold="v>1", |
| 1727 |
reset="v=0", |
| 1728 |
name="profile_test", |
| 1729 |
) |
| 1730 |
net = Network(G) |
| 1731 |
net.run(1 * ms, profile=False) |
| 1732 |
with pytest.raises(ValueError): |
| 1733 |
profiling_summary(net) |
| 1734 |
|
| 1735 |
|
| 1736 |
@pytest.mark.codegen_independent |
| 1737 |
def test_profile_ipython_html(): |
| 1738 |
G = NeuronGroup( |
| 1739 |
10, |
| 1740 |
"dv/dt = -v / (10*ms) : 1", |
| 1741 |
threshold="v>1", |
| 1742 |
reset="v=0", |
| 1743 |
name="profile_test", |
| 1744 |
) |
| 1745 |
G.v = 1.1 |
| 1746 |
net = Network(G) |
| 1747 |
net.run(1 * ms, profile=True) |
| 1748 |
summary = profiling_summary(net) |
| 1749 |
assert len(summary._repr_html_()) |
| 1750 |
|
| 1751 |
|
| 1752 |
@pytest.mark.codegen_independent |
| 1753 |
def test_magic_scope(): |
| 1754 |
""" |
| 1755 |
Check that `start_scope` works as expected. |
| 1756 |
""" |
| 1757 |
G1 = NeuronGroup(1, "v:1", name="G1") |
| 1758 |
G2 = NeuronGroup(1, "v:1", name="G2") |
| 1759 |
objs1 = {obj.name for obj in collect()} |
| 1760 |
start_scope() |
| 1761 |
G3 = NeuronGroup(1, "v:1", name="G3") |
| 1762 |
G4 = NeuronGroup(1, "v:1", name="G4") |
| 1763 |
objs2 = {obj.name for obj in collect()} |
| 1764 |
assert objs1 == {"G1", "G2"} |
| 1765 |
assert objs2 == {"G3", "G4"} |
| 1766 |
|
| 1767 |
|
| 1768 |
@pytest.mark.standalone_compatible |
| 1769 |
def test_runtime_rounding(): |
| 1770 |
# Test that runtime and standalone round in the same way, see github issue |
| 1771 |
# #695 for details |
| 1772 |
defaultclock.dt = 20.000000000020002 * us |
| 1773 |
G = NeuronGroup(1, "v:1") |
| 1774 |
mon = StateMonitor(G, "v", record=True) |
| 1775 |
run(defaultclock.dt * 250) |
| 1776 |
assert len(mon.t) == 250 |
| 1777 |
|
| 1778 |
|
| 1779 |
@pytest.mark.codegen_independent |
| 1780 |
def test_small_runs(): |
| 1781 |
# One long run and multiple small runs should give the same results |
| 1782 |
group_1 = NeuronGroup(10, "dv/dt = -v / (10*ms) : 1") |
| 1783 |
group_1.v = "(i + 1) / N" |
| 1784 |
group_1.run_at("v += 0.1", times=[100 * ms, 300 * ms]) |
| 1785 |
mon_1 = StateMonitor(group_1, "v", record=True) |
| 1786 |
net_1 = Network(group_1, mon_1) |
| 1787 |
net_1.run(1 * second) |
| 1788 |
|
| 1789 |
group_2 = NeuronGroup(10, "dv/dt = -v / (10*ms) : 1") |
| 1790 |
group_2.v = "(i + 1) / N" |
| 1791 |
group_2.run_at("v += 0.1", times=[100 * ms, 300 * ms]) |
| 1792 |
mon_2 = StateMonitor(group_2, "v", record=True) |
| 1793 |
net_2 = Network(group_2, mon_2) |
| 1794 |
runtime = 1 * ms |
| 1795 |
while True: |
| 1796 |
runtime *= 3 |
| 1797 |
runtime = min([runtime, 1 * second - net_2.t]) |
| 1798 |
net_2.run(runtime) |
| 1799 |
if net_2.t >= 1 * second: |
| 1800 |
break |
| 1801 |
|
| 1802 |
assert_allclose(mon_1.t_[:], mon_2.t_[:]) |
| 1803 |
assert_allclose(mon_1.v_[:], mon_2.v_[:]) |
| 1804 |
|
| 1805 |
|
| 1806 |
@pytest.mark.standalone_compatible |
| 1807 |
@pytest.mark.multiple_runs |
| 1808 |
def test_both_equal(): |
| 1809 |
# check all objects added by Network.add() also have their contained_objects added to 'Network' |
| 1810 |
tau = 10 * ms |
| 1811 |
diff_eqn = """dv/dt = (1-v)/tau : 1""" |
| 1812 |
chg_code = """v = 2*v""" |
| 1813 |
|
| 1814 |
Ng = NeuronGroup(1, diff_eqn, method="exact") |
| 1815 |
M1 = StateMonitor(Ng, "v", record=True) |
| 1816 |
netObj = Network(Ng, M1) |
| 1817 |
Ng.run_regularly(chg_code, dt=20 * ms) |
| 1818 |
netObj.run(100 * ms) |
| 1819 |
|
| 1820 |
start_scope() |
| 1821 |
Ng = NeuronGroup(1, diff_eqn, method="exact") |
| 1822 |
M2 = StateMonitor(Ng, "v", record=True) |
| 1823 |
Ng.run_regularly(chg_code, dt=20 * ms) |
| 1824 |
run(100 * ms) |
| 1825 |
|
| 1826 |
device.build(direct_call=False, **device.build_options) |
| 1827 |
|
| 1828 |
assert (M1.v == M2.v).all() |
| 1829 |
|
| 1830 |
|
| 1831 |
@pytest.mark.standalone_compatible |
| 1832 |
@pytest.mark.multiple_runs |
| 1833 |
def test_long_run(): |
| 1834 |
defaultclock.dt = 0.1 * ms |
| 1835 |
group = NeuronGroup(1, "x : 1") |
| 1836 |
group.run_regularly("x += 1") |
| 1837 |
# Timesteps are internally stored as 64bit integers, but previous versions |
| 1838 |
# converted them into 32bit integers along the way. We'll make sure that |
| 1839 |
# this is not the case and everything runs fine. To not actually run such a |
| 1840 |
# long simulation we run a single huge time step |
| 1841 |
start_step = 2**31 - 5 |
| 1842 |
defaultclock.dt = 0.1 * ms |
| 1843 |
start_time = start_step * defaultclock.dt |
| 1844 |
defaultclock.dt = start_time |
| 1845 |
run(start_time) # A single, *very* long time step |
| 1846 |
defaultclock.dt = 0.1 * ms |
| 1847 |
run(6 * defaultclock.dt) |
| 1848 |
device.build(direct_call=False, **device.build_options) |
| 1849 |
assert group.x == 7 |
| 1850 |
|
| 1851 |
|
| 1852 |
@pytest.mark.codegen_independent |
| 1853 |
def test_long_run_dt_change(): |
| 1854 |
# Check that the dt check is not too restrictive, see issue #730 for details |
| 1855 |
group = NeuronGroup(1, "") # does nothing... |
| 1856 |
defaultclock.dt = 0.1 * ms |
| 1857 |
run(100 * second) |
| 1858 |
# print profiling_summary() |
| 1859 |
defaultclock.dt = 0.01 * ms |
| 1860 |
run(1 * second) |
| 1861 |
|
| 1862 |
|
| 1863 |
@pytest.mark.standalone_compatible |
| 1864 |
@pytest.mark.multiple_runs |
| 1865 |
def test_multiple_runs_constant_change(): |
| 1866 |
const_v = 1 |
| 1867 |
group = NeuronGroup(1, "v = const_v : 1") |
| 1868 |
mon = StateMonitor(group, "v", record=0) |
| 1869 |
run(defaultclock.dt) |
| 1870 |
const_v = 2 |
| 1871 |
run(defaultclock.dt) |
| 1872 |
device.build(direct_call=False, **device.build_options) |
| 1873 |
assert_equal(mon.v[0], [1, 2]) |
| 1874 |
|
| 1875 |
|
| 1876 |
@pytest.mark.standalone_compatible |
| 1877 |
@pytest.mark.multiple_runs |
| 1878 |
def test_multiple_runs_function_change(): |
| 1879 |
inp = TimedArray([1, 2], dt=defaultclock.dt) |
| 1880 |
group = NeuronGroup(1, "v = inp(t) : 1") |
| 1881 |
mon = StateMonitor(group, "v", record=0) |
| 1882 |
run(2 * defaultclock.dt) |
| 1883 |
inp = TimedArray([0, 0, 3, 4], dt=defaultclock.dt) |
| 1884 |
run(2 * defaultclock.dt) |
| 1885 |
device.build(direct_call=False, **device.build_options) |
| 1886 |
assert_equal(mon.v[0], [1, 2, 3, 4]) |
| 1887 |
|
| 1888 |
|
| 1889 |
@pytest.mark.codegen_independent |
| 1890 |
def test_unused_object_warning(): |
| 1891 |
# Make sure that the warnings are activated for this test |
| 1892 |
_old_pref = prefs.logging.warn_for_unused_objects |
| 1893 |
prefs.logging.warn_for_unused_objects = True |
| 1894 |
try: |
| 1895 |
with catch_logs() as logs: |
| 1896 |
# Create a NeuronGroup that is not used in the network |
| 1897 |
NeuronGroup(1, "v:1", name="never_used") |
| 1898 |
# Make sure that it gets garbage collected |
| 1899 |
import gc |
| 1900 |
|
| 1901 |
gc.collect() |
| 1902 |
assert len(logs) == 1 |
| 1903 |
assert logs[0][0] == "WARNING" |
| 1904 |
assert logs[0][1].endswith("unused_brian_object") |
| 1905 |
assert "never_used" in logs[0][2] |
| 1906 |
finally: |
| 1907 |
prefs.logging.warn_for_unused_objects = _old_pref |
| 1908 |
|
| 1909 |
|
| 1910 |
@pytest.mark.codegen_independent |
| 1911 |
def test_negative_duration_in_run(): |
| 1912 |
G = NeuronGroup(1, "v:1") |
| 1913 |
with pytest.raises(ValueError): |
| 1914 |
run(-1 * second) |
| 1915 |
|
| 1916 |
|
| 1917 |
@pytest.mark.codegen_independent |
| 1918 |
def test_negative_duration_in_net_run(): |
| 1919 |
G = NeuronGroup(1, "v:1") |
| 1920 |
net = Network(G) |
| 1921 |
with pytest.raises(ValueError): |
| 1922 |
net.run(-1 * second) |
| 1923 |
|
| 1924 |
|
| 1925 |
if __name__ == "__main__": |
| 1926 |
BrianLogger.log_level_warn() |
| 1927 |
for t in [ |
| 1928 |
test_incorrect_network_use, |
| 1929 |
test_network_contains, |
| 1930 |
test_empty_network, |
| 1931 |
test_network_single_object, |
| 1932 |
test_network_two_objects, |
| 1933 |
test_network_from_dict, |
| 1934 |
test_network_different_clocks, |
| 1935 |
test_network_different_when, |
| 1936 |
test_network_default_schedule, |
| 1937 |
test_network_schedule_change, |
| 1938 |
test_network_before_after_schedule, |
| 1939 |
test_network_custom_slots, |
| 1940 |
test_network_incorrect_schedule, |
| 1941 |
test_schedule_warning, |
| 1942 |
test_scheduling_summary_magic, |
| 1943 |
test_scheduling_summary, |
| 1944 |
test_magic_network, |
| 1945 |
test_network_stop, |
| 1946 |
test_network_operations, |
| 1947 |
test_incorrect_network_operations, |
| 1948 |
test_network_operations_name, |
| 1949 |
test_network_active_flag, |
| 1950 |
test_network_t, |
| 1951 |
test_incorrect_dt_defaultclock, |
| 1952 |
test_incorrect_dt_custom_clock, |
| 1953 |
test_network_remove, |
| 1954 |
test_magic_weak_reference, |
| 1955 |
test_magic_unused_object, |
| 1956 |
test_invalid_magic_network, |
| 1957 |
test_multiple_networks_invalid, |
| 1958 |
test_network_access, |
| 1959 |
test_loop, |
| 1960 |
test_magic_collect, |
| 1961 |
test_progress_report, |
| 1962 |
test_progress_report_incorrect, |
| 1963 |
test_multiple_runs_report_standalone, |
| 1964 |
test_multiple_runs_report_standalone_2, |
| 1965 |
test_multiple_runs_report_standalone_3, |
| 1966 |
test_multiple_runs_report_standalone_incorrect, |
| 1967 |
test_store_restore, |
| 1968 |
test_restore_from_python_spikequeue, |
| 1969 |
test_store_restore_to_file, |
| 1970 |
test_store_restore_to_file_new_objects, |
| 1971 |
test_store_restore_to_file_differing_nets, |
| 1972 |
test_store_restore_magic, |
| 1973 |
test_store_restore_magic_to_file, |
| 1974 |
test_store_restore_spikequeue, |
| 1975 |
test_store_restore_restore_synapses, |
| 1976 |
test_defaultclock_dt_changes, |
| 1977 |
test_dt_changes_between_runs, |
| 1978 |
test_dt_restore, |
| 1979 |
test_continuation, |
| 1980 |
test_get_set_states, |
| 1981 |
test_multiple_runs_defaultclock, |
| 1982 |
test_multiple_runs_defaultclock_incorrect, |
| 1983 |
test_profile, |
| 1984 |
test_profile_off, |
| 1985 |
test_profile_ipython_html, |
| 1986 |
test_magic_scope, |
| 1987 |
test_runtime_rounding, |
| 1988 |
test_small_runs, |
| 1989 |
test_both_equal, |
| 1990 |
test_long_run, |
| 1991 |
test_long_run_dt_change, |
| 1992 |
test_multiple_runs_constant_change, |
| 1993 |
test_multiple_runs_function_change, |
| 1994 |
]: |
| 1995 |
set_device(all_devices["runtime"]) |
| 1996 |
t() |
| 1997 |
reinit_and_delete() |