Debian Codegraph @

brian2/tests/features/base.py

raw
1 import itertools
2 import os
3 import pickle
4 import re
5 import shutil
6 import subprocess
7 import sys
8 import tempfile
9 from collections import defaultdict
10
11 import numpy
12
13 import brian2
14 from brian2.utils.stringtools import indent
15
16 __all__ = [
17 "FeatureTest",
18 "SpeedTest",
19 "InaccuracyError",
20 "Configuration",
21 "run_feature_tests",
22 "run_single_feature_test",
23 "run_speed_tests",
24 "DefaultConfiguration",
25 "LocalConfiguration",
26 "NumpyConfiguration",
27 "CythonConfiguration",
28 "CPPStandaloneConfiguration",
29 "CPPStandaloneConfigurationOpenMP",
30 ]
31
32
33 class InaccuracyError(AssertionError):
34 def __init__(self, error, *args):
35 self.error = error
36 AssertionError.__init__(self, *args)
37
38
39 class BaseTest:
40 """ """
41
42 category = None # a string with the category of features
43 name = None # a string with the particular feature name within the category
44 tags = None # a list of tags (strings) of features used
45 # whether or not to allow the device to override the time: this can be used to remove the
46 # compilation overheads on certain devices (but some tests might want to include this)
47 allow_time_override = True
48
49 @classmethod
50 def fullname(cls):
51 return f"{cls.category}: {cls.name}"
52
53 def run(self):
54 """
55 Runs the feature test but do not return results (some devices may
56 require an extra step before results are available).
57 """
58 raise NotImplementedError
59
60 def timed_run(self, duration):
61 """
62 Do a timed run. This means that for RuntimeDevice it will run for defaultclock.dt before running for the
63 rest of the duration. This means total run duration will be duration+defaultclock.dt.
64 For standalone devices, this feature may or may not be implemented.
65 """
66 if isinstance(brian2.get_device(), brian2.devices.RuntimeDevice):
67 brian2.run(brian2.defaultclock.dt, level=1)
68 brian2.run(duration, level=1)
69 else:
70 brian2.run(duration, level=1)
71
72
73 class FeatureTest(BaseTest):
74 """ """
75
76 def results(self):
77 """
78 Return the results after a run call.
79 """
80 raise NotImplementedError
81
82 def compare(self, maxrelerr, results_base, results_test):
83 """
84 Compare results from standard Brian run to another run.
85
86 This method or `check` should be implemented.
87 """
88 raise NotImplementedError
89
90 def check(self, maxrelerr, results):
91 """
92 Check results are valid (e.g. analytically).
93
94 This method or `compare` should be implemented.
95 """
96 raise NotImplementedError
97
98 def compare_arrays(self, maxrelerr, v_base, v_test):
99 """
100 Often you just want to compare the values of some arrays, this does that.
101 """
102 if isinstance(v_base, dict):
103 for k in v_base:
104 self.compare_arrays(maxrelerr, v_base[k], v_test[k])
105 else:
106 I = v_base != 0
107 err = numpy.amax(numpy.abs(v_base[I] - v_test[I]) / v_base[I])
108 if err > maxrelerr:
109 raise InaccuracyError(err)
110 if (v_test[-I] != 0).any():
111 raise InaccuracyError(numpy.inf)
112
113
114 class SpeedTest(BaseTest):
115 n_range = [1]
116 n_label = "n"
117 n_axis_log = True
118 time_axis_log = True
119
120 def __init__(self, n):
121 self.n = n
122
123 def results(self):
124 return self.n
125
126 def compare(self, maxrelerr, results_base, results_test):
127 pass
128
129 def check(self, maxrelerr, results):
130 pass
131
132 def __call__(self):
133 return self
134
135
136 class Configuration:
137 """ """
138
139 name = None # The name of this configuration
140
141 def __init__(self, maximum_run_time=1e7 * brian2.second):
142 maximum_run_time = float(maximum_run_time) * brian2.second
143 self.maximum_run_time = maximum_run_time
144
145 def before_run(self):
146 pass
147
148 def after_run(self):
149 pass
150
151 def get_last_run_time(self):
152 """
153 Implement this to overwrite the measured runtime (e.g. to remove overhead).
154 """
155 if hasattr(brian2.device, "_last_run_time"):
156 return brian2.device._last_run_time
157 raise NotImplementedError
158
159 def get_last_run_completed_fraction(self):
160 """
161 Implement this to overwrite the amount of the last run that was completed (for devices that allow breaking
162 early if the maximum run time is exceeded).
163 """
164 if hasattr(brian2.device, "_last_run_completed_fraction"):
165 return brian2.device._last_run_completed_fraction
166 return 1.0
167
168
169 class DefaultConfiguration(Configuration):
170 name = "Default"
171
172 def before_run(self):
173 brian2.prefs.reset_to_defaults()
174 brian2.set_device("runtime")
175
176
177 class LocalConfiguration(Configuration):
178 name = "Local"
179
180 def before_run(self):
181 brian2.prefs.reset_to_defaults()
182 brian2.set_device("runtime")
183 brian2.prefs.load_preferences()
184
185
186 class NumpyConfiguration(Configuration):
187 name = "Numpy"
188
189 def before_run(self):
190 brian2.prefs.reset_to_defaults()
191 brian2.set_device("runtime")
192 brian2.prefs.codegen.target = "numpy"
193
194
195 class CythonConfiguration(Configuration):
196 name = "Cython"
197
198 def before_run(self):
199 brian2.prefs.reset_to_defaults()
200 brian2.set_device("runtime")
201 brian2.prefs.codegen.target = "cython"
202
203
204 class CPPStandaloneConfiguration(Configuration):
205 name = "C++ standalone"
206
207 def before_run(self):
208 brian2.prefs.reset_to_defaults()
209 brian2.set_device("cpp_standalone", build_on_run=False)
210
211 def after_run(self):
212 if os.path.exists("cpp_standalone"):
213 shutil.rmtree("cpp_standalone")
214 brian2.device.build(
215 directory="cpp_standalone", compile=True, run=True, with_output=False
216 )
217
218
219 class CPPStandaloneConfigurationOpenMP(Configuration):
220 name = "C++ standalone (OpenMP)"
221
222 def before_run(self):
223 brian2.prefs.reset_to_defaults()
224 brian2.set_device("cpp_standalone", build_on_run=False)
225 brian2.prefs.devices.cpp_standalone.openmp_threads = 4
226
227 def after_run(self):
228 if os.path.exists("cpp_standalone"):
229 shutil.rmtree("cpp_standalone")
230 brian2.device.build(
231 directory="cpp_standalone", compile=True, run=True, with_output=False
232 )
233
234
235 def results(configuration, feature, n=None, maximum_run_time=1e7 * brian2.second):
236 tempfilename = tempfile.mktemp("exception")
237 if n is None:
238 init_args = ""
239 else:
240 init_args = str(n)
241 code_string = """
242 __file__ = '{fname}'
243 import brian2
244 from {config_module} import {config_name}
245 from {feature_module} import {feature_name}
246 configuration = {config_name}()
247 feature = {feature_name}({init_args})
248 import warnings, traceback, pickle, sys, os, time
249 warnings.simplefilter('ignore')
250 try:
251 start_time = time.time()
252 configuration.before_run()
253 brian2.device._set_maximum_run_time({maximum_run_time})
254 feature.run()
255 configuration.after_run()
256 results = feature.results()
257 run_time = time.time()-start_time
258 if feature.allow_time_override:
259 try:
260 run_time = configuration.get_last_run_time()
261 except NotImplementedError:
262 pass
263 lrcf = configuration.get_last_run_completed_fraction()
264 run_time = run_time/lrcf
265 prof_info = brian2.magic_network.profiling_info
266 new_prof_info = []
267 for n, t in prof_info:
268 new_prof_info.append((n, t/lrcf))
269 f = open(r'{tempfname}', 'wb')
270 pickle.dump((None, results, run_time, new_prof_info), f, -1)
271 f.close()
272 except Exception, ex:
273 #traceback.print_exc(file=sys.stdout)
274 tb = traceback.format_exc()
275 f = open(r'{tempfname}', 'wb')
276 pickle.dump((tb, ex, 0.0, []), f, -1)
277 f.close()
278 """.format(
279 config_module=configuration.__module__,
280 config_name=configuration.__name__,
281 feature_module=feature.__module__,
282 feature_name=feature.__name__,
283 tempfname=tempfilename,
284 fname=__file__,
285 init_args=init_args,
286 maximum_run_time=float(maximum_run_time),
287 )
288 args = [sys.executable, "-c", code_string]
289 # Run the example in a new process and make sure that stdout gets
290 # redirected into the capture plugin
291 p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
292 stdout, stderr = p.communicate()
293 # sys.stdout.write(stdout)
294 # sys.stderr.write(stderr)
295 with open(tempfilename, "rb") as f:
296 tb, res, runtime, profiling_info = pickle.load(f)
297 return tb, res, runtime, profiling_info
298
299
300 def check_or_compare(feature, res, baseline, maxrelerr):
301 feature = feature()
302 try:
303 feature.check(maxrelerr, res)
304 except NotImplementedError:
305 feature.compare(maxrelerr, baseline, res)
306
307
308 def run_single_feature_test(configuration, feature):
309 return results(configuration, feature)
310
311
312 def run_feature_tests(
313 configurations=None,
314 feature_tests=None,
315 strict=1e-5,
316 tolerant=0.05,
317 verbose=True,
318 maximum_run_time=1e7 * brian2.second,
319 ):
320 if configurations is None:
321 # some configurations to attempt to import
322 try:
323 import brian2genn.correctness_testing
324 except:
325 pass
326 configurations = Configuration.__subclasses__()
327 if feature_tests is None:
328 feature_tests = FeatureTest.__subclasses__()
329 if DefaultConfiguration in configurations:
330 configurations.remove(DefaultConfiguration)
331 configurations = [DefaultConfiguration] + configurations
332 feature_tests.sort(key=lambda ft: ft.fullname())
333 if verbose:
334 print("Running feature tests")
335 print("Configurations:", ", ".join(c.name for c in configurations))
336
337 full_results = {}
338 tag_results = defaultdict(lambda: defaultdict(list))
339 for ft in feature_tests:
340 baseline = None
341 if verbose:
342 print(f"{ft.fullname()}: [", end=" ")
343 for configuration in configurations:
344 txt = "OK"
345 sym = "."
346 exc = None
347 tb, res, runtime, prof_info = results(
348 configuration, ft, maximum_run_time=maximum_run_time
349 )
350 if isinstance(res, Exception):
351 if isinstance(res, NotImplementedError):
352 sym = "N"
353 txt = "Not implemented"
354 else:
355 sym = "E"
356 txt = "Error"
357 if configuration is DefaultConfiguration:
358 raise res
359 else:
360 if configuration is DefaultConfiguration:
361 baseline = res
362 try:
363 check_or_compare(ft, res, baseline, strict)
364 except InaccuracyError as exc:
365 try:
366 check_or_compare(ft, res, baseline, tolerant)
367 sym = "I"
368 txt = f"Poor (error={100.0 * exc.error:.2f}%)"
369 except InaccuracyError as exc:
370 sym = "F"
371 txt = f"Fail (error={100.0 * exc.error:.2f}%)"
372 sys.stdout.write(sym)
373 full_results[configuration.name, ft.fullname()] = (
374 sym,
375 txt,
376 exc,
377 tb,
378 runtime,
379 prof_info,
380 )
381 for tag in ft.tags:
382 tag_results[tag][configuration.name].append(
383 (sym, txt, exc, tb, runtime, prof_info)
384 )
385 if verbose:
386 print("]")
387
388 return FeatureTestResults(full_results, tag_results, configurations, feature_tests)
389
390
391 class FeatureTestResults:
392 def __init__(self, full_results, tag_results, configurations, feature_tests):
393 self.full_results = full_results
394 self.tag_results = tag_results
395 self.configurations = configurations
396 self.feature_tests = feature_tests
397
398 @property
399 def test_table(self):
400 table = []
401 table.append(["Test"] + [c.name for c in self.configurations])
402 curcat = ""
403
404 for ft in self.feature_tests:
405 cat = ft.category
406 if cat != curcat:
407 table.append([cat] + [""] * len(self.configurations))
408 curcat = cat
409 row = [ft.name]
410 for configuration in self.configurations:
411 sym, txt, exc, tb, runtime, prof_info = self.full_results[
412 configuration.name, ft.fullname()
413 ]
414 row.append(txt)
415 table.append(row)
416 return make_table(table)
417
418 @property
419 def tag_table(self):
420 table = []
421 table.append(["Tag"] + [c.name for c in self.configurations])
422 tags = sorted(self.tag_results.keys())
423
424 for tag in tags:
425 row = [tag]
426 for configuration in self.configurations:
427 tag_res = self.tag_results[tag][configuration.name]
428 syms = [sym for sym, txt, exc, tb, runtime, prof_info in tag_res]
429 n = len(syms)
430 okcount = sum(sym == "." for sym in syms)
431 poorcount = sum(sym == "I" for sym in syms)
432 failcount = sum(sym == "F" for sym in syms)
433 errcount = sum(sym == "E" for sym in syms)
434 nicount = sum(sym == "N" for sym in syms)
435 if okcount == n:
436 txt = "OK"
437 elif nicount == n:
438 txt = "Not implemented"
439 elif errcount == n:
440 txt = "Unsupported"
441 elif okcount + poorcount == n:
442 txt = f"Poor ({int(int(poorcount * 100.0 / n))}%)"
443 elif okcount + poorcount + failcount == n:
444 txt = (
445 f"Fail: {int(failcount * 100.0 / n)}%"
446 f" (poor={int(poorcount * 100.0 / n)}%)"
447 )
448 else:
449 txt = (
450 "Fail: OK={ok}%, Poor={poor}%, Fail={fail}%, NotImpl={ni}%"
451 " Error={err}%".format(
452 ok=int(okcount * 100.0 / n),
453 poor=int(poorcount * 100.0 / n),
454 fail=int(failcount * 100.0 / n),
455 err=int(errcount * 100.0 / n),
456 ni=int(nicount * 100.0 / n),
457 )
458 )
459 row.append(txt)
460 table.append(row)
461 return make_table(table)
462
463 @property
464 def tables(self):
465 r = ""
466 s = "Feature test results"
467 r += f"{s}\n{'-' * len(s)}\n\n{self.test_table}\n"
468 s = "Tag results"
469 r += f"{s}\n{'-' * len(s)}\n\n{self.tag_table}\n"
470 return r
471
472 @property
473 def exceptions(self):
474 exc_list = []
475 for configuration in self.configurations:
476 curconfig = []
477 for ft in self.feature_tests:
478 sym, txt, exc, tb, runtime, prof_info = self.full_results[
479 configuration.name, ft.fullname()
480 ]
481 if tb is not None:
482 curconfig.append((ft.fullname(), tb))
483 if len(curconfig):
484 exc_list.append((configuration.name, curconfig))
485 if len(exc_list) == 0:
486 return ""
487 r = ""
488 s = "Exceptions"
489 r += f"{s}\n{'-' * len(s)}\n\n"
490 for config_name, curconfig in exc_list:
491 s = config_name
492 r += f"{s}\n{'^' * len(s)}\n\n"
493 for name, tb in curconfig:
494 r += f"{name}::\n\n{indent(tb)}\n\n"
495 return r
496
497 @property
498 def tables_and_exceptions(self):
499 return f"{self.tables}\n{self.exceptions}"
500
501 def __str__(self):
502 return self.tables
503
504 __repr__ = __str__
505
506
507 def run_speed_tests(
508 configurations=None,
509 speed_tests=None,
510 run_twice=True,
511 verbose=True,
512 n_slice=slice(None),
513 maximum_run_time=1e7 * brian2.second,
514 ):
515 if configurations is None:
516 # some configurations to attempt to import
517 try:
518 import brian2genn.correctness_testing
519 except:
520 pass
521 configurations = Configuration.__subclasses__()
522 if speed_tests is None:
523 speed_tests = SpeedTest.__subclasses__()
524 speed_tests.sort(key=lambda ft: ft.fullname())
525 if verbose:
526 print("Running speed tests")
527 print("Configurations:", ", ".join(c.name for c in configurations))
528
529 full_results = {}
530 tag_results = defaultdict(lambda: defaultdict(list))
531 for ft in speed_tests:
532 if verbose:
533 print(f"{ft.fullname()}: ", end=" ")
534 for n in ft.n_range[n_slice]:
535 if verbose:
536 print(f"n={int(n)} [", end=" ")
537 for configuration in configurations:
538 sym = "."
539 for _ in range(1 + int(run_twice)):
540 tb, res, runtime, prof_info = results(
541 configuration, ft, n, maximum_run_time=maximum_run_time
542 )
543 if isinstance(res, Exception):
544 if isinstance(res, NotImplementedError):
545 sym = "N"
546 else:
547 sym = "E"
548 if configuration is DefaultConfiguration:
549 raise res
550 runtime = numpy.NAN
551 sys.stdout.write(sym)
552 full_results[configuration.name, ft.fullname(), n, "All"] = runtime
553 suffixtime = defaultdict(float)
554 overheadstime = float(runtime)
555 for codeobjname, proftime in prof_info:
556 # parts = codeobjname.split('_')
557 # parts = [part for part in parts if not re.match(r'\d+', part)]
558 # suffix = '_'.join(parts)
559 suffix = codeobjname
560 suffixtime[suffix] += proftime
561 overheadstime -= float(proftime)
562 for suffix, proftime in list(suffixtime.items()):
563 full_results[configuration.name, ft.fullname(), n, suffix] = (
564 proftime
565 )
566 full_results[configuration.name, ft.fullname(), n, "Overheads"] = (
567 overheadstime
568 )
569 if verbose:
570 print("]", end=" ")
571 if verbose:
572 print()
573
574 return SpeedTestResults(full_results, configurations, speed_tests)
575
576
577 class SpeedTestResults:
578 def __init__(self, full_results, configurations, speed_tests):
579 self.full_results = full_results
580 self.configurations = configurations
581 self.speed_tests = speed_tests
582
583 def get_ns(self, fullname):
584 L = [(cn, fn, n, s) for cn, fn, n, s in self.full_results if fn == fullname]
585 confignames, fullnames, n, codeobjsuffixes = zip(*L)
586 return numpy.array(sorted(list(set(n))))
587
588 def get_codeobjsuffixes(self, fullname):
589 L = [(cn, fn, n, s) for cn, fn, n, s in self.full_results if fn == fullname]
590 confignames, fullnames, n, codeobjsuffixes = zip(*L)
591 return set(codeobjsuffixes)
592
593 def plot_all_tests(self, relative=False, profiling_minimum=1.0):
594 if relative and profiling_minimum < 1:
595 raise ValueError("Cannot use relative plots with profiling")
596 import pylab
597
598 for st in self.speed_tests:
599 fullname = st.fullname()
600 pylab.figure()
601 ns = self.get_ns(fullname)
602 codeobjsuffixes = self.get_codeobjsuffixes(fullname)
603 codeobjsuffixes.remove("All")
604 codeobjsuffixes.remove("Overheads")
605 codeobjsuffixes = ["All", "Overheads"] + sorted(codeobjsuffixes)
606 if relative or profiling_minimum == 1:
607 codeobjsuffixes = ["All"]
608 baseline = None
609 havelabel = set()
610 markerstyles_cycle = iter(
611 itertools.cycle(["o", "s", "d", "v", "p", "h", "^", "<", ">"])
612 )
613 dashes = {}
614 markerstyles = {}
615 for isuffix, suffix in enumerate(codeobjsuffixes):
616 cols = itertools.cycle(pylab.rcParams["axes.color_cycle"])
617 for (iconfig, config), col in zip(enumerate(self.configurations), cols):
618 configname = config.name
619 runtimes = []
620 skip = True
621 for n in ns:
622 runtime = self.full_results.get(
623 (configname, fullname, n, "All"), numpy.nan
624 )
625 thistime = self.full_results.get(
626 (configname, fullname, n, suffix), numpy.nan
627 )
628 if float(thistime / runtime) >= profiling_minimum:
629 skip = False
630 runtimes.append(thistime)
631 if skip:
632 continue
633 runtimes = numpy.array(runtimes)
634 if relative:
635 if baseline is None:
636 baseline = runtimes
637 runtimes = baseline / runtimes
638 if suffix == "All":
639 lw = 2
640 label = configname
641 else:
642 lw = 1
643 label = suffix
644 plottable = sum(-numpy.isnan(runtimes[1:] + runtimes[:-1]))
645 if plottable:
646 if label in havelabel:
647 label = None
648 else:
649 havelabel.add(label)
650 dash = None
651 msty = None
652 if suffix != "All":
653 if suffix in dashes:
654 dash = dashes[suffix]
655 msty = markerstyles[suffix]
656 else:
657 j = len(dashes)
658 dash = (8, 2)
659 for b in bin(j)[2:]:
660 if b == "0":
661 dash = dash + (2, 2)
662 else:
663 dash = dash + (4, 2)
664 dashes[suffix] = dash
665 markerstyles[suffix] = msty = next(markerstyles_cycle)
666 line = pylab.plot(
667 ns,
668 runtimes,
669 lw=lw,
670 color=col,
671 marker=msty,
672 mec="none",
673 ms=8,
674 label=label,
675 )[0]
676 if dash is not None:
677 line.set_dashes(dash)
678 pylab.title(fullname)
679 pylab.legend(loc="best", fontsize="x-small", handlelength=8.0)
680 pylab.xlabel(st.n_label)
681 if st.n_axis_log:
682 pylab.gca().set_xscale("log")
683 if st.time_axis_log:
684 pylab.gca().set_yscale("log")
685
686
687 # Code below auto generates restructured text tables, copied from:
688 # http://stackoverflow.com/questions/11347505/what-are-some-approaches-to-outputting-a-python-data-structure-to-restructuredte
689
690
691 def make_table(grid):
692 max_cols = [
693 max(out)
694 for out in map(list, zip(*[[len(item) for item in row] for row in grid]))
695 ]
696 rst = table_div(max_cols, 1)
697
698 for i, row in enumerate(grid):
699 header_flag = False
700 if i == 0 or i == len(grid) - 1:
701 header_flag = True
702 rst += normalize_row(row, max_cols)
703 rst += table_div(max_cols, header_flag)
704 return rst
705
706
707 def table_div(max_cols, header_flag=1):
708 out = ""
709 if header_flag == 1:
710 style = "="
711 else:
712 style = "-"
713
714 for max_col in max_cols:
715 out += f"{max_col * style} "
716
717 out += "\n"
718 return out
719
720
721 def normalize_row(row, max_cols):
722 r = ""
723 for i, max_col in enumerate(max_cols):
724 r += row[i] + (max_col - len(row[i]) + 1) * " "
725
726 return f"{r}\n"