-
Notifications
You must be signed in to change notification settings - Fork 12
/
brian2.diff
756 lines (718 loc) · 34.1 KB
/
brian2.diff
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
diff --git a/brian2/devices/cpp_standalone/device.py b/brian2/devices/cpp_standalone/device.py
index b79ce460..7b114602 100644
--- a/brian2/devices/cpp_standalone/device.py
+++ b/brian2/devices/cpp_standalone/device.py
@@ -1003,6 +1003,7 @@ def run(self, directory, with_output, run_args):
with open('results/last_run_info.txt', 'r') as f:
last_run_info = f.read()
self._last_run_time, self._last_run_completed_fraction = map(float, last_run_info.split())
+ print("INFO _last_run_time = {} s".format(self._last_run_time))
# Make sure that integration did not create NaN or very large values
owners = [var.owner for var in self.arrays]
@@ -1189,6 +1190,12 @@ def network_run(self, net, duration, report=None, report_period=10*second,
# We store this as an instance variable for later access by the
# `code_object` method
self.enable_profiling = profile
+ # To profile SpeedTests, we need to be able to set `profile` in
+ # `set_device`. Here we catch that case.
+ if 'profile' in self.build_options:
+ build_profile = self.build_options.pop('profile')
+ if build_profile:
+ self.enable_profiling = True
net._clocks = {obj.clock for obj in net.objects}
t_end = net.t+duration
diff --git a/brian2/input/timedarray.py b/brian2/input/timedarray.py
index d12e9c00..59f11cb6 100644
--- a/brian2/input/timedarray.py
+++ b/brian2/input/timedarray.py
@@ -2,6 +2,7 @@
Implementation of `TimedArray`.
'''
+
import numpy as np
from brian2.core.clocks import defaultclock
@@ -32,6 +33,99 @@ def _find_K(group_dt, dt):
return K
+def _generate_cpp_code_1d(values, dt, name):
+ def cpp_impl(owner):
+ K = _find_K(owner.clock.dt_, dt)
+ code = '''
+ static inline double %NAME%(const double t)
+ {
+ const double epsilon = %DT% / %K%;
+ int i = (int)((t/epsilon + 0.5)/%K%);
+ if(i < 0)
+ i = 0;
+ if(i >= %NUM_VALUES%)
+ i = %NUM_VALUES%-1;
+ return _namespace%NAME%_values[i];
+ }
+ '''.replace('%NAME%', name).replace('%DT%', '%.18f' % dt).replace(
+ '%K%', str(K)).replace('%NUM_VALUES%', str(len(values)))
+
+ return code
+
+ return cpp_impl
+
+
+def _generate_cpp_code_2d(values, dt, name):
+ def cpp_impl(owner):
+ K = _find_K(owner.clock.dt_, dt)
+ support_code = '''
+ static inline double %NAME%(const double t, const int i)
+ {
+ const double epsilon = %DT% / %K%;
+ if (i < 0 || i >= %COLS%)
+ return NAN;
+ int timestep = (int)((t/epsilon + 0.5)/%K%);
+ if(timestep < 0)
+ timestep = 0;
+ else if(timestep >= %ROWS%)
+ timestep = %ROWS%-1;
+ return _namespace%NAME%_values[timestep*%COLS% + i];
+ }
+ '''
+ code = replace(support_code, {'%NAME%': name,
+ '%DT%': '%.18f' % dt,
+ '%K%': str(K),
+ '%COLS%': str(values.shape[1]),
+ '%ROWS%': str(values.shape[0])})
+ return code
+ return cpp_impl
+
+
+def _generate_cython_code_1d(values, dt, name):
+ def cython_impl(owner):
+ K = _find_K(owner.clock.dt_, dt)
+ code = '''
+ cdef double %NAME%(const double t):
+ global _namespace%NAME%_values
+ cdef double epsilon = %DT% / %K%
+ cdef int i = (int)((t/epsilon + 0.5)/%K%)
+ if i < 0:
+ i = 0
+ if i >= %NUM_VALUES%:
+ i = %NUM_VALUES% - 1
+ return _namespace%NAME%_values[i]
+ '''.replace('%NAME%', name).replace('%DT%', '%.18f' % dt).replace(
+ '%K%', str(K)).replace('%NUM_VALUES%', str(len(values)))
+
+ return code
+ return cython_impl
+
+
+def _generate_cython_code_2d(values, dt, name):
+ def cython_impl(owner):
+ K = _find_K(owner.clock.dt_, dt)
+ code = '''
+ cdef double %NAME%(const double t, const int i):
+ global _namespace%NAME%_values
+ cdef double epsilon = %DT% / %K%
+ if i < 0 or i >= %COLS%:
+ return _numpy.nan
+ cdef int timestep = (int)((t/epsilon + 0.5)/%K%)
+ if timestep < 0:
+ timestep = 0
+ elif timestep >= %ROWS%:
+ timestep = %ROWS%-1
+ return _namespace%NAME%_values[timestep*%COLS% + i]
+ '''
+ code = replace(code, {'%NAME%': name,
+ '%DT%': '%.18f' % dt,
+ '%K%': str(K),
+ '%COLS%': str(values.shape[1]),
+ '%ROWS%': str(values.shape[0])})
+ return code
+ return cython_impl
+
+
class TimedArray(Function, Nameable, CacheKey):
'''
TimedArray(values, dt, name=None)
@@ -77,7 +171,7 @@ class TimedArray(Function, Nameable, CacheKey):
>>> net = Network(G, mon)
>>> net.run(0.2*ms) # doctest: +ELLIPSIS
...
- >>> print mon.v[:]
+ >>> print(mon.v[:])
[[ 1. 3.]
[ 2. 4.]
[ 1. 3.]
@@ -85,6 +179,21 @@ class TimedArray(Function, Nameable, CacheKey):
'''
_cache_irrelevant_attributes = {'_id', 'values', 'pyfunc',
'implementations'}
+
+ #: Container for implementing functions for different targets
+ #: This container can be extended by other codegeneration targets/devices
+ #: The key has to be the name of the target, the value is a tuple of
+ #: functions, the first for a 1d array, the second for a 2d array.
+ #: The functions have to take three parameters: (values, dt, name), i.e. the
+ #: array values, their physical dimensions, the dt of the TimedArray, and
+ #: the name of the TimedArray. The functions have to return *a function*
+ #: that takes the `owner` argument (out of which they can get the context's
+ #: dt as `owner.clock.dt_`) and returns the code.
+ implementations = {
+ 'cpp': (_generate_cpp_code_1d, _generate_cpp_code_2d),
+ 'cython': (_generate_cython_code_1d, _generate_cython_code_2d)
+ }
+
@check_units(dt=second)
def __init__(self, values, dt, name=None):
if name is None:
@@ -143,58 +252,15 @@ def unitless_timed_array_func(t):
self.implementations.add_dynamic_implementation('numpy',
create_numpy_implementation)
+ namespace = lambda owner: {'%s_values' % self.name: self.values}
- def create_cpp_implementation(owner):
- group_dt = owner.clock.dt_
- K = _find_K(group_dt, dt)
- support_code = '''
- static inline double %NAME%(const double t)
- {
- const double epsilon = %DT% / %K%;
- int i = (int)((t/epsilon + 0.5)/%K%);
- if(i < 0)
- i = 0;
- if(i >= %NUM_VALUES%)
- i = %NUM_VALUES%-1;
- return _namespace%NAME%_values[i];
- }
- '''.replace('%NAME%', self.name).replace('%DT%', '%.18f' % dt).replace('%K%', str(K)).replace('%NUM_VALUES%', str(len(self.values)))
- cpp_code = {'support_code': support_code}
-
- return cpp_code
-
- def create_cpp_namespace(owner):
- return {'%s_values' % self.name: self.values}
-
- self.implementations.add_dynamic_implementation('cpp',
- code=create_cpp_implementation,
- namespace=create_cpp_namespace,
- name=self.name)
- def create_cython_implementation(owner):
- group_dt = owner.clock.dt_
- K = _find_K(group_dt, dt)
- code = '''
- cdef double %NAME%(const double t):
- global _namespace%NAME%_values
- cdef double epsilon = %DT% / %K%
- cdef int i = (int)((t/epsilon + 0.5)/%K%)
- if i < 0:
- i = 0
- if i >= %NUM_VALUES%:
- i = %NUM_VALUES% - 1
- return _namespace%NAME%_values[i]
- '''.replace('%NAME%', self.name).replace('%DT%', '%.18f' % dt).replace('%K%', str(K)).replace('%NUM_VALUES%', str(len(self.values)))
-
- return code
-
- def create_cython_namespace(owner):
- return {'%s_values' % self.name: self.values}
-
- self.implementations.add_dynamic_implementation('cython',
- code=create_cython_implementation,
- namespace=create_cython_namespace,
- name=self.name)
-
+ for target, (func_1d, _) in TimedArray.implementations.items():
+ self.implementations.add_dynamic_implementation(target,
+ func_1d(self.values,
+ self.dt,
+ self.name),
+ namespace=namespace,
+ name=self.name)
def _init_2d(self):
dimensions = self.dim
@@ -235,77 +301,18 @@ def unitless_timed_array_func(t, i):
self.implementations.add_dynamic_implementation('numpy',
create_numpy_implementation)
-
-
- def create_cpp_implementation(owner):
- group_dt = owner.clock.dt_
- K = _find_K(group_dt, dt)
- support_code = '''
- static inline double %NAME%(const double t, const int i)
- {
- const double epsilon = %DT% / %K%;
- if (i < 0 || i >= %COLS%)
- return NAN;
- int timestep = (int)((t/epsilon + 0.5)/%K%);
- if(timestep < 0)
- timestep = 0;
- else if(timestep >= %ROWS%)
- timestep = %ROWS%-1;
- return _namespace%NAME%_values[timestep*%COLS% + i];
- }
- '''
- support_code = replace(support_code, {'%NAME%': self.name,
- '%DT%': '%.18f' % dt,
- '%K%': str(K),
- '%COLS%': str(self.values.shape[1]),
- '%ROWS%': str(self.values.shape[0])})
- cpp_code = {'support_code': support_code}
-
- return cpp_code
-
- def create_cpp_namespace(owner):
- return {'%s_values' % self.name: self.values.astype(np.double,
- order='C',
- copy=False).ravel()}
-
- self.implementations.add_dynamic_implementation('cpp',
- code=create_cpp_implementation,
- namespace=create_cpp_namespace,
- name=self.name)
-
- def create_cython_implementation(owner):
- group_dt = owner.clock.dt_
- K = _find_K(group_dt, dt)
- code = '''
- cdef double %NAME%(const double t, const int i):
- global _namespace%NAME%_values
- cdef double epsilon = %DT% / %K%
- if i < 0 or i >= %COLS%:
- return _numpy.nan
- cdef int timestep = (int)((t/epsilon + 0.5)/%K%)
- if timestep < 0:
- timestep = 0
- elif timestep >= %ROWS%:
- timestep = %ROWS%-1
- return _namespace%NAME%_values[timestep*%COLS% + i]
- '''
- code = replace(code, {'%NAME%': self.name,
- '%DT%': '%.18f' % dt,
- '%K%': str(K),
- '%COLS%': str(self.values.shape[1]),
- '%ROWS%': str(self.values.shape[0])})
-
- return code
-
- def create_cython_namespace(owner):
- return {'%s_values' % self.name: self.values.astype(np.double,
- order='C',
- copy=False).ravel()}
-
- self.implementations.add_dynamic_implementation('cython',
- code=create_cython_implementation,
- namespace=create_cython_namespace,
- name=self.name)
+ values_flat = self.values.astype(np.double,
+ order='C',
+ copy=False).ravel()
+ namespace = lambda owner: {'%s_values' % self.name: values_flat}
+
+ for target, (_, func_2d) in TimedArray.implementations.items():
+ self.implementations.add_dynamic_implementation(target,
+ func_2d(self.values,
+ self.dt,
+ self.name),
+ namespace=namespace,
+ name=self.name)
def is_locally_constant(self, dt):
if dt > self.dt:
diff --git a/brian2/tests/features/base.py b/brian2/tests/features/base.py
index 2fc47aa2..27efc691 100644
--- a/brian2/tests/features/base.py
+++ b/brian2/tests/features/base.py
@@ -10,6 +10,7 @@
import re
from brian2.utils.stringtools import indent
+from brian2.core.base import BrianObjectException
from collections import defaultdict
@@ -226,8 +227,10 @@ def after_run(self):
with_output=False)
-def results(configuration, feature, n=None, maximum_run_time=1e7*brian2.second):
- tempfilename = tempfile.mktemp('exception')
+def results(configuration, feature, n=None, maximum_run_time=1e7*brian2.second,
+ profile_only_active=False, return_lrcf=False):
+ tempfilename = 'my_file_1'#tempfile.mktemp('exception')
+ tempfilename_net_obj = 'my_file_2'#tempfile.mktemp('network_objects')
if n is None:
init_args = ''
else:
@@ -235,9 +238,9 @@ def results(configuration, feature, n=None, maximum_run_time=1e7*brian2.second):
code_string = '''
__file__ = '{fname}'
import brian2
-from {config_module} import {config_name}
+import {config_module}
from {feature_module} import {feature_name}
-configuration = {config_name}()
+configuration = {config_module}.{config_name}()
feature = {feature_name}({init_args})
import warnings, traceback, pickle, sys, os, time
warnings.simplefilter('ignore')
@@ -246,6 +249,12 @@ def results(configuration, feature, n=None, maximum_run_time=1e7*brian2.second):
configuration.before_run()
brian2.device._set_maximum_run_time({maximum_run_time})
feature.run()
+ if {prof_active}:
+ code_objects = []
+ for obj in brian2.magic_network.objects:
+ if obj.active:
+ for codeobj in obj._code_objects:
+ code_objects.append(codeobj.name)
configuration.after_run()
results = feature.results()
run_time = time.time()-start_time
@@ -256,39 +265,80 @@ def results(configuration, feature, n=None, maximum_run_time=1e7*brian2.second):
pass
lrcf = configuration.get_last_run_completed_fraction()
run_time = run_time/lrcf
- prof_info = brian2.magic_network.profiling_info
new_prof_info = []
- for n, t in prof_info:
- new_prof_info.append((n, t/lrcf))
+ try:
+ prof_info = brian2.magic_network.profiling_info
+ for n, t in prof_info:
+ new_prof_info.append((n, t/lrcf))
+ except ValueError:
+ pass
f = open(r'{tempfname}', 'wb')
- pickle.dump((None, results, run_time, new_prof_info), f, -1)
+ pickle.dump((None, results, run_time, new_prof_info, lrcf), f, -1)
f.close()
+ if {prof_active}:
+ f2 = open(r'{tempfname_net_obj}', 'wb')
+ pickle.dump(code_objects, f2, -1)
+ f2.close()
except Exception, ex:
#traceback.print_exc(file=sys.stdout)
tb = traceback.format_exc()
f = open(r'{tempfname}', 'wb')
- pickle.dump((tb, ex, 0.0, []), f, -1)
+ try:
+ pickle.dump((tb, ex, 0.0, [], 0.0), f, -1)
+ except pickle.PicklingError:
+ print tb
+ raise
f.close()
+ if {prof_active}:
+ f2 = open(r'{tempfname_net_obj}', 'wb')
+ pickle.dump([], f2, -1)
+ f2.close()
'''.format(config_module=configuration.__module__,
config_name=configuration.__name__,
feature_module=feature.__module__,
feature_name=feature.__name__,
tempfname=tempfilename,
+ tempfname_net_obj=tempfilename_net_obj,
fname=__file__,
init_args=init_args,
maximum_run_time=float(maximum_run_time),
+ prof_active=str(profile_only_active)
)
args = [sys.executable, '-c',
code_string]
+ if hasattr(configuration, 'git_commit') and configuration.git_commit is not None:
+ # checkout the commit specified in the DynamicConfigCreator
+ configuration.git_checkout()
+ # checkout the original version of the module defining the feature
+ configuration.git_checkout_feature(feature.__module__)
+ configuration.git_checkout_feature(configuration.__module__)
# Run the example in a new process and make sure that stdout gets
# redirected into the capture plugin
p = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
- #sys.stdout.write(stdout)
- #sys.stderr.write(stderr)
+ if p.returncode:
+ sys.stdout.write(stdout)
+ sys.stderr.write(stderr)
with open(tempfilename, 'rb') as f:
- tb, res, runtime, profiling_info = pickle.load(f)
+ tb, res, runtime, profiling_info, lrcf = pickle.load(f)
+ if isinstance(res, Exception):
+ tb = stdout + '\n' + stderr + '\n' + tb
+ else:
+ tb = stdout + '\n' + stderr
+ if profile_only_active:
+ with open(tempfilename_net_obj, 'rb') as f:
+ network_codeobjects = pickle.load(f)
+ profiling_info = [(codeobj, time)
+ for (codeobj, time) in profiling_info
+ if codeobj in network_codeobjects]
+ if hasattr(configuration, 'git_commit') and configuration.git_commit is not None:
+ # reset the current changes before checking out original commit
+ configuration.git_reset()
+ # check out the original commit
+ configuration.git_checkout(reverse=True)
+ if return_lrcf:
+ return tb, res, runtime, profiling_info, lrcf
return tb, res, runtime, profiling_info
@@ -333,7 +383,7 @@ def run_feature_tests(configurations=None, feature_tests=None,
txt = 'OK'
sym = '.'
exc = None
- tb, res, runtime, prof_info = results(configuration, ft, maximum_run_time=maximum_run_time)
+ tb, res, runtime, prof_info, lrcf = results(configuration, ft, maximum_run_time=maximum_run_time)
if isinstance(res, Exception):
if isinstance(res, NotImplementedError):
sym = 'N'
@@ -477,7 +527,8 @@ def __str__(self):
def run_speed_tests(configurations=None, speed_tests=None, run_twice=True, verbose=True,
- n_slice=slice(None), maximum_run_time=1e7*brian2.second):
+ n_slice=slice(None), maximum_run_time=1e7*brian2.second,
+ profile_only_active=True, mark_not_completed=False):
if configurations is None:
# some configurations to attempt to import
try:
@@ -495,15 +546,27 @@ def run_speed_tests(configurations=None, speed_tests=None, run_twice=True, verbo
full_results = {}
tag_results = defaultdict(lambda:defaultdict(list))
for ft in speed_tests:
+ traceback = {}
+ brian_stdouts = {}
+ result = {}
if verbose:
print ft.fullname()+': ',
+ sys.stdout.flush()
for n in ft.n_range[n_slice]:
if verbose:
print 'n=%d [' % n,
+ sys.stdout.flush()
for configuration in configurations:
sym = '.'
+ brian_stdout = ''
for _ in xrange(1+int(run_twice)):
- tb, res, runtime, prof_info = results(configuration, ft, n, maximum_run_time=maximum_run_time)
+ if mark_not_completed:
+ tb, res, runtime, prof_info, lrcf = results(configuration, ft, n, maximum_run_time=maximum_run_time,
+ profile_only_active=profile_only_active,
+ return_lrcf=mark_not_completed)
+ else:
+ tb, res, runtime, prof_info = results(configuration, ft, n, maximum_run_time=maximum_run_time,
+ profile_only_active=profile_only_active)
if isinstance(res, Exception):
if isinstance(res, NotImplementedError):
sym = 'N'
@@ -512,8 +575,28 @@ def run_speed_tests(configurations=None, speed_tests=None, run_twice=True, verbo
if configuration is DefaultConfiguration:
raise res
runtime = numpy.NAN
+ proj_dir = ''
+ if configuration.name.startswith("CUDA"):
+ proj_dir = 'cuda_standalone'
+ elif configuration.name.startswith("CPP"):
+ proj_dir = 'cpp_standalone'
+ elif configuration.name.startswith("GeNN"):
+ proj_dir = 'GeNNWorkspace'
+ stdout_file = os.path.join(os.getcwd(), proj_dir, 'results/stdout.txt')
+ if os.path.exists(stdout_file):
+ with open(stdout_file, 'r') as sfile:
+ brian_stdout = sfile.read()
+ else:
+ brian_stdout = 'no stdout file found, cwd = {}'.format(stdout_file)
sys.stdout.write(sym)
+ sys.stdout.flush()
full_results[configuration.name, ft.fullname(), n, 'All'] = runtime
+ if mark_not_completed:
+ # save last run completed fraction
+ full_results[configuration.name, ft.fullname(), n, 'lrcf'] = lrcf
+ traceback[configuration.name, ft.fullname(), n] = tb
+ brian_stdouts[configuration.name, ft.fullname(), n] = brian_stdout
+ result[configuration.name, n] = res
suffixtime = defaultdict(float)
overheadstime = float(runtime)
for codeobjname, proftime in prof_info:
@@ -528,18 +611,27 @@ def run_speed_tests(configurations=None, speed_tests=None, run_twice=True, verbo
full_results[configuration.name, ft.fullname(), n, 'Overheads'] = overheadstime
if verbose:
print ']',
+ sys.stdout.flush()
if verbose:
print
-
- return SpeedTestResults(full_results, configurations, speed_tests)
+ for n in ft.n_range[n_slice]:
+ for conf in configurations:
+ if isinstance(result[conf.name, n], Exception):
+ print("\nTRACEBACK {} N={}\n{}\n{}\n\n".format(conf.name, n,
+ brian_stdouts[conf.name, ft.fullname(), n],
+ traceback[conf.name, ft.fullname(), n]))
+
+ return SpeedTestResults(full_results, configurations, speed_tests, brian_stdouts, traceback)
class SpeedTestResults(object):
- def __init__(self, full_results, configurations, speed_tests):
+ def __init__(self, full_results, configurations, speed_tests, brian_stdouts, tracebacks):
self.full_results = full_results
self.configurations = configurations
self.speed_tests = speed_tests
-
+ self.brian_stdouts = brian_stdouts
+ self.tracebacks = tracebacks
+
def get_ns(self, fullname):
L = [(cn, fn, n, s) for cn, fn, n, s in self.full_results.keys() if fn==fullname]
confignames, fullnames, n, codeobjsuffixes = zip(*L)
@@ -550,7 +642,7 @@ def get_codeobjsuffixes(self, fullname):
confignames, fullnames, n, codeobjsuffixes = zip(*L)
return set(codeobjsuffixes)
- def plot_all_tests(self, relative=False, profiling_minimum=1.0):
+ def plot_all_tests(self, relative=False, profiling_minimum=1.0, print_relative=False):
if relative and profiling_minimum<1:
raise ValueError("Cannot use relative plots with profiling")
import pylab
@@ -561,6 +653,8 @@ def plot_all_tests(self, relative=False, profiling_minimum=1.0):
codeobjsuffixes = self.get_codeobjsuffixes(fullname)
codeobjsuffixes.remove('All')
codeobjsuffixes.remove('Overheads')
+ if 'lrcf' in codeobjsuffixes:
+ codeobjsuffixes.remove('lrcf')
codeobjsuffixes = ['All', 'Overheads']+sorted(codeobjsuffixes)
if relative or profiling_minimum==1:
codeobjsuffixes = ['All']
@@ -570,31 +664,46 @@ def plot_all_tests(self, relative=False, profiling_minimum=1.0):
dashes = {}
markerstyles = {}
for isuffix, suffix in enumerate(codeobjsuffixes):
- cols = itertools.cycle(pylab.rcParams['axes.color_cycle'])
- for (iconfig, config), col in zip(enumerate(self.configurations), cols):
+ props = itertools.cycle(pylab.rcParams['axes.prop_cycle'])
+ for (iconfig, config), prop in zip(enumerate(self.configurations), props):
configname = config.name
runtimes = []
+ not_finished = []
skip = True
for n in ns:
runtime = self.full_results.get((configname, fullname, n, 'All'), numpy.nan)
+ if 'lrcf' in codeobjsuffixes:
+ lrcf = self.full_results.get((configname, fullname, n, 'lrcf'), numpy.nan)
+ not_finished.append(lrcf != 1.0)
+ else:
+ not_finished = [0] # no plotting
thistime = self.full_results.get((configname, fullname, n, suffix), numpy.nan)
if float(thistime/runtime)>=profiling_minimum:
skip = False
runtimes.append(thistime)
+ #overheadstime = self.full_results.get((configname, fullname, n, 'Overheads'), numpy.nan)
+ #if (profiling_minimum<1 and overheadstime == runtime:
+ # skip = True
if skip:
continue
runtimes = numpy.array(runtimes)
- if relative:
+ if relative or print_relative:
if baseline is None:
baseline = runtimes
+ if relative:
runtimes = baseline/runtimes
+ if print_relative:
+ rel = baseline/runtimes
+ for ni, n in enumerate(ns):
+ print("INFO relative performance for {ft} N={n} {conf}: {factor}".format(
+ ft=fullname, n=n, conf=config.name, factor=rel[ni]))
if suffix=='All':
lw = 2
label = configname
else:
lw = 1
label = suffix
- plottable = sum(-numpy.isnan(runtimes[1:]+runtimes[:-1]))
+ plottable = sum(~numpy.isnan(runtimes[1:]+runtimes[:-1]))
if plottable:
if label in havelabel:
label = None
@@ -616,8 +725,12 @@ def plot_all_tests(self, relative=False, profiling_minimum=1.0):
dash = dash+(4, 2)
dashes[suffix] = dash
markerstyles[suffix] = msty = markerstyles_cycle.next()
- line = pylab.plot(ns, runtimes, lw=lw, color=col, marker=msty,
+ line = pylab.plot(ns, runtimes, lw=lw, color=prop['color'], marker=msty,
mec='none', ms=8, label=label)[0]
+ if suffix == 'All' and sum(not_finished) != 0:
+ pylab.plot(ns[not_finished], runtimes[not_finished],
+ linestyle='None', marker=r'$\circlearrowleft$',
+ ms=15, color=prop['color'], label='linear runtime interpolation')
if dash is not None:
line.set_dashes(dash)
pylab.title(fullname)
@@ -627,6 +740,7 @@ def plot_all_tests(self, relative=False, profiling_minimum=1.0):
pylab.gca().set_xscale('log')
if st.time_axis_log:
pylab.gca().set_yscale('log')
+ pylab.grid(True, which='both')
# Code below auto generates restructured text tables, copied from:
# http://stackoverflow.com/questions/11347505/what-are-some-approaches-to-outputting-a-python-data-structure-to-restructuredte
diff --git a/brian2/tests/features/speed.py b/brian2/tests/features/speed.py
index 75f3410c..9e58abdc 100644
--- a/brian2/tests/features/speed.py
+++ b/brian2/tests/features/speed.py
@@ -22,7 +22,7 @@ class LinearNeuronsOnly(SpeedTest):
category = "Neurons only"
name = "Linear 1D"
tags = ["Neurons"]
- n_range = [10, 100, 1000, 10000, 100000, 1000000]
+ n_range = [10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 261015625] #fail: 262031250
n_label = 'Num neurons'
# configuration options
@@ -41,7 +41,7 @@ class HHNeuronsOnly(SpeedTest):
category = "Neurons only"
name = "Hodgkin-Huxley"
tags = ["Neurons"]
- n_range = [10, 100, 1000, 10000, 100000]
+ n_range = [10, 100, 1000, 10000, 100000, 1000000, 10000000, 102750000] #fail: 103125000
n_label = 'Num neurons'
# configuration options
@@ -85,7 +85,7 @@ class CUBAFixedConnectivity(SpeedTest):
category = "Full examples"
name = "CUBA fixed connectivity"
tags = ["Neurons", "Synapses", "SpikeMonitor"]
- n_range = [10, 100, 1000, 10000, 100000]
+ n_range = [10, 100, 1000, 10000, 100000, 1000000, 3546875] #fail: 3562500
n_label = 'Num neurons'
# configuration options
@@ -131,7 +131,7 @@ class COBAHHFixedConnectivity(SpeedTest):
category = "Full examples"
name = "COBAHH fixed connectivity"
tags = ["Neurons", "Synapses", "SpikeMonitor"]
- n_range = [100, 500, 1000, 5000, 10000, 50000, 100000, 500000, 1000000]
+ n_range = [100, 500, 1000, 5000, 10000, 50000, 100000, 500000, 1000000, 3781250] #fail: 3812500
n_label = 'Num neurons'
# configuration options
@@ -254,7 +254,7 @@ def run(self):
class SynapsesOnly(object):
category = "Synapses only"
tags = ["Synapses"]
- n_range = [10, 100, 1000, 10000]
+ n_range = [10, 100, 1000, 10000, 100000, 1000000]
n_label = 'Num neurons'
duration = 1 * second
# memory usage will be approximately p**2*rate*dt*N**2*bytes_per_synapse/1024**3 GB
@@ -281,7 +281,7 @@ class VerySparseMediumRateSynapsesOnly(SynapsesOnly, SpeedTest):
name = "Very sparse, medium rate (10s duration)"
rate = 10 * Hz
p = 0.02
- n_range = [10, 100, 1000, 10000, 100000] # weave max CPU time should be about 20s
+ n_range = [10, 100, 1000, 10000, 100000, 500000, 1000000, 3875000] #fail: 3906250 # weave max CPU time should be about 20s
duration = 10 * second
@@ -289,21 +289,21 @@ class SparseMediumRateSynapsesOnly(SynapsesOnly, SpeedTest):
name = "Sparse, medium rate (1s duration)"
rate = 10 * Hz
p = 0.2
- n_range = [10, 100, 1000, 10000, 100000] # weave max CPU time should be about 5m
+ n_range = [10, 100, 1000, 10000, 100000, 500000, 1000000, 1234375] #fail: 1242187 # weave max CPU time should be about 5m
class DenseMediumRateSynapsesOnly(SynapsesOnly, SpeedTest):
name = "Dense, medium rate (1s duration)"
rate = 10 * Hz
p = 1.0
- n_range = [10, 100, 1000, 10000, 40000] # weave max CPU time should be about 4m
+ n_range = [10, 100, 1000, 10000, 100000, 500000, 546875] #fail: 554687 # weave max CPU time should be about 4m
class SparseLowRateSynapsesOnly(SynapsesOnly, SpeedTest):
name = "Sparse, low rate (10s duration)"
rate = 1 * Hz
p = 0.2
- n_range = [10, 100, 1000, 10000, 100000] # weave max CPU time should be about 20s
+ n_range = [10, 100, 1000, 10000, 100000, 500000, 1000000, 3875000] #fail: 3906250 # weave max CPU time should be about 20s
duration = 10 * second
@@ -311,7 +311,7 @@ class SparseHighRateSynapsesOnly(SynapsesOnly, SpeedTest):
name = "Sparse, high rate (1s duration)"
rate = 100 * Hz
p = 0.2
- n_range = [10, 100, 1000, 10000] # weave max CPU time should be about 5m
+ n_range = [10, 100, 1000, 10000, 100000, 387500] #fail: 393750 # weave max CPU time should be about 5m
if __name__ == '__main__':