-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathdevice.py
1644 lines (1506 loc) · 82.9 KB
/
device.py
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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Module implementing the bulk of the brian2genn interface by defining the "genn" device.
'''
import os
import shutil
import sys
import platform
from pkg_resources import parse_version
from subprocess import call, check_call, CalledProcessError
import inspect
from collections import defaultdict
import tempfile
import itertools
import numpy
import numbers
from brian2.codegen.translation import make_statements
from brian2.input.poissoninput import PoissonInput
from brian2.spatialneuron.spatialneuron import (SpatialNeuron,
SpatialStateUpdater)
from brian2.units import second
from brian2.codegen.generators.cpp_generator import (c_data_type,
CPPCodeGenerator)
from brian2.codegen.templates import MultiTemplate
from brian2.core.clocks import defaultclock
from brian2.core.variables import *
from brian2.core.network import Network
from brian2.devices.device import all_devices
from brian2.devices.cpp_standalone.device import CPPStandaloneDevice
from brian2.parsing.rendering import CPPNodeRenderer
from brian2.synapses.synapses import Synapses, SynapticPathway
from brian2.monitors.spikemonitor import SpikeMonitor
from brian2.monitors.ratemonitor import PopulationRateMonitor
from brian2.monitors.statemonitor import StateMonitor
from brian2.utils.filetools import copy_directory, ensure_directory
from brian2.utils.stringtools import word_substitute, get_identifiers
from brian2.groups.group import Group, CodeRunner
from brian2.groups.neurongroup import (NeuronGroup, StateUpdater, Resetter,
Thresholder, SubexpressionUpdater)
from brian2.groups.subgroup import Subgroup
from brian2.input.poissongroup import PoissonGroup
from brian2.input.spikegeneratorgroup import *
from brian2.synapses.synapses import StateUpdater as SynapsesStateUpdater
from brian2.utils.logger import get_logger, std_silent
from brian2.devices.cpp_standalone.codeobject import CPPStandaloneCodeObject
from brian2 import prefs
from .codeobject import GeNNCodeObject, GeNNUserCodeObject
from .genn_generator import get_var_ndim
__all__ = ['GeNNDevice']
logger = get_logger('brian2.devices.genn')
def stringify(code):
'''
Helper function to prepare multiline strings (potentially including
quotation marks) to be included in strings.
Parameters
----------
code : str
The code to convert.
'''
code = code.replace('\n', '\\n\\\n')
code = code.replace('"', '\\"')
return code
def freeze(code, ns):
'''
Support function for substituting constant values.
'''
# this is a bit of a hack, it should be passed to the template somehow
for k, v in ns.items():
if (isinstance(v, Variable) and
v.scalar and v.constant and v.read_only):
try:
v = v.get_value()
except NotImplementedError:
continue
if isinstance(v, basestring):
code = word_substitute(code, {k: v})
elif isinstance(v, numbers.Number):
# Use a renderer to correctly transform constants such as True or inf
renderer = CPPNodeRenderer()
string_value = renderer.render_expr(repr(v))
if v < 0:
string_value = '(%s)' % string_value
code = word_substitute(code, {k: string_value})
else:
pass # don't deal with this object
return code
def get_compile_args():
'''
Get the compile args based on the users preferences. Uses Brian's
preferences for the C++ compilation (either `codegen.cpp.extra_compile_args`
for both Windows and UNIX, or `codegen.cpp.extra_compile_args_gcc` for UNIX
and `codegen.cpp.extra_compile_args_msvc` for Windows), and the Brian2GeNN
preference `devices.genn.extra_compile_args_nvcc` for the CUDA compilation
with nvcc.
Returns
-------
(compile_args_gcc, compile_args_msvc, compile_args_nvcc) : (str, str, str)
Tuple with the respective compiler arguments (as strings).
'''
if prefs.codegen.cpp.extra_compile_args is not None:
args = ' '.join(prefs.codegen.cpp.extra_compile_args)
compile_args_gcc = args
compile_args_msvc = args
else:
compile_args_gcc = ' '.join(prefs.codegen.cpp.extra_compile_args_gcc)
compile_args_msvc = ' '.join(prefs.codegen.cpp.extra_compile_args_msvc)
compile_args_nvcc = ' '.join(prefs.devices.genn.extra_compile_args_nvcc)
return compile_args_gcc, compile_args_msvc, compile_args_nvcc
def decorate(code, variables, shared_variables, parameters, do_final=True):
'''
Support function for inserting GeNN-specific "decorations" for variables and
parameters, such as $(.).
'''
# this is a bit of a hack, it should be part of the language probably
for v in itertools.chain(variables, shared_variables, parameters):
code = word_substitute(code, {v: '$(' + v + ')'})
code = word_substitute(code, {'dt': 'DT'}).strip()
if do_final:
code = stringify(code)
code = word_substitute(code, {'addtoinSyn': '$(addtoinSyn)'})
code = word_substitute(code, {'_hidden_weightmatrix': '$(_hidden_weightmatrix)'})
return code
def extract_source_variables(variables, varname, smvariables):
'''Support function to extract the "atomic" variables used in a variable
that is of instance `Subexpression`.
'''
identifiers = get_identifiers(variables[varname].expr)
for vnm, var in variables.items():
if var in defaultclock.variables.values():
raise NotImplementedError('Recording an expression that depends on '
'the time t or the timestep dt is '
'currently not supported in Brian2GeNN')
if vnm in identifiers:
if isinstance(var, ArrayVariable):
smvariables.append(vnm)
elif isinstance(var, Subexpression):
smvariables = extract_source_variables(variables, vnm,
smvariables)
return smvariables
class DelayedCodeObject(object):
'''
Dummy class used for delaying the CodeObject creation of stateupdater,
thresholder, and resetter of a NeuronGroup (which will all be merged into a
single code object).
'''
def __init__(self, owner, name, abstract_code, variables, variable_indices,
override_conditional_write):
self.owner = owner
self.name = name
self.abstract_code = abstract_code
self.variables = variables
self.variable_indices = variable_indices
self.override_conditional_write = override_conditional_write
class neuronModel(object):
'''
Class that contains all relevant information of a neuron model.
'''
def __init__(self):
self.name = ''
self.clock = None
self.N = 0
self.variables = []
self.variabletypes = []
self.variablescope = dict()
self.shared_variables = []
self.shared_variabletypes = []
self.parameters = []
self.pvalue = []
self.code_lines = []
self.thresh_cond_lines = []
self.reset_code_lines = []
self.support_code_lines = []
self.run_regularly_object = None
self.run_regularly_step = None
self.run_regularly_read = None
self.run_regularly_write = None
class spikegeneratorModel(object):
'''
Class that contains all relevant information of a spike generator group.
'''
def __init__(self):
self.name = ''
self.N = 0
class synapseModel(object):
'''
Class that contains all relevant information about a synapse model.
'''
def __init__(self):
self.name = ''
self.srcname = ''
self.srcN = 0
self.trgname = ''
self.trgN = 0
self.N = 0
self.variables = []
self.variabletypes = []
self.shared_variables = []
self.shared_variabletypes = []
self.variablescope = dict()
self.external_variables = []
self.parameters = []
self.pvalue = []
self.postSyntoCurrent = []
# The following dictionaries contain keys "pre"/"post" for the pre-
# and post-synaptic pathway and "dynamics" for the synaptic dynamics
self.main_code_lines = defaultdict(str)
self.support_code_lines = defaultdict(str)
self.connectivity = ''
self.delay = 0
class spikeMonitorModel(object):
'''
Class the contains all relevant information about a spike monitor.
'''
def __init__(self):
self.name = ''
self.neuronGroup = ''
self.notSpikeGeneratorGroup = True
class rateMonitorModel(object):
'''
CLass that contains all relevant information about a rate monitor.
'''
def __init__(self):
self.name = ''
self.neuronGroup = ''
self.notSpikeGeneratorGroup = True
class stateMonitorModel(object):
'''
Class that contains all relvant information about a state monitor.
'''
def __init__(self):
self.name = ''
self.monitored = ''
self.isSynaptic = False
self.variables = []
self.srcN = 0
self.trgN = 0
self.when = ''
self.connectivity = ''
class CPPWriter(object):
'''
Class that provides the method for writing C++ files from a string of code.
'''
def __init__(self, project_dir):
self.project_dir = project_dir
self.source_files = []
self.header_files = []
def write(self, filename, contents):
logger.diagnostic('Writing file %s:\n%s' % (filename, contents))
if filename.lower().endswith('.cpp'):
self.source_files.append(filename)
elif filename.lower().endswith('.h'):
self.header_files.append(filename)
elif filename.endswith('.*'):
self.write(filename[:-1] + 'cpp', contents.cpp_file)
self.write(filename[:-1] + 'h', contents.h_file)
return
fullfilename = os.path.join(self.project_dir, filename)
if os.path.exists(fullfilename):
if open(fullfilename, 'r').read() == contents:
return
open(fullfilename, 'w').write(contents)
# ------------------------------------------------------------------------------
# Start of GeNNDevice
# ------------------------------------------------------------------------------
class GeNNDevice(CPPStandaloneDevice):
'''
The main "genn" device. This does most of the translation work from Brian 2
generated code to functional GeNN code, assisted by the "GeNN language".
'''
def __init__(self):
super(GeNNDevice, self).__init__()
# Remember whether we have already passed the "run" statement
self.run_statement_used = False
self.network_schedule = ['start', 'synapses', 'groups', 'thresholds',
'resets', 'end']
self.neuron_models = []
self.spikegenerator_models = []
self.synapse_models = []
self.ktimer= dict()
self.ktimer['neuron_tme']= True
self.ktimer['synapse_tme']= False
self.ktimer['learning_tme']= False
self.ktimer['synDyn_tme']= False
self.delays = {}
self.spike_monitor_models = []
self.rate_monitor_models = []
self.state_monitor_models = []
self.run_duration = None
self.net = None
self.simple_code_objects = {}
self.report_func = ''
#: List of all source and header files (to be included in runner)
self.source_files = []
self.header_files = []
self.connectivityDict = dict()
self.groupDict = dict()
# Overwrite the code slots defined in standard C++ standalone
self.code_lines = {'before_start': [],
'after_start': [],
'before_run': [],
'after_run': [],
'before_end': [],
'after_end': []}
def insert_code(self, slot, code):
'''
Insert custom C++ code directly into ``main.cpp``. The available slots
are:
``before_start`` / ``after_start``
Before/after allocating memory for the arrays and loading arrays from
disk.
``before_run`` / ``after_run``
Before/after calling GeNN's ``run`` function.
``before_end`` / ``after_end``
Before/after writing results to disk and deallocating memory.
Parameters
----------
slot : str
The name of the slot where the code will be placed (see above for
list of available slots).
code : str
The C++ code that should be inserted.
'''
# Only overwritten so that we can have custom documentation
super(GeNNDevice, self).insert_code(slot, code)
def activate(self, build_on_run=True, **kwargs):
new_prefs = {'codegen.generators.cpp.restrict_keyword': '__restrict',
'codegen.loop_invariant_optimisations': False,
'core.network.default_schedule': ['start', 'synapses',
'groups', 'thresholds',
'resets', 'end']}
changed = []
for new_pref, new_value in new_prefs.iteritems():
if prefs[new_pref] != new_value:
changed.append(new_pref)
prefs[new_pref] = new_value
if changed:
logger.info('The following preferences have been changed for '
'Brian2GeNN, reset them manually if you use a '
'different device later in the same script: '
'{}'.format(', '.join(changed)), once=True)
prefs._backup()
super(GeNNDevice, self).activate(build_on_run, **kwargs)
def code_object_class(self, codeobj_class=None, *args, **kwds):
if codeobj_class is GeNNCodeObject:
return codeobj_class
else:
return GeNNUserCodeObject
def code_object(self, owner, name, abstract_code, variables, template_name,
variable_indices, codeobj_class=None, template_kwds=None,
override_conditional_write=None, **kwds):
'''
Processes abstract code into code objects and stores them in different
arrays for `GeNNCodeObjects` and `GeNNUserCodeObjects`.
'''
if (template_name in ['stateupdate', 'threshold', 'reset'] and
isinstance(owner, NeuronGroup)):
# Delay the code generation process, we want to merge them into one
# code object later
codeobj = DelayedCodeObject(owner=owner,
name=name,
abstract_code=abstract_code,
variables=variables,
variable_indices=variable_indices,
override_conditional_write=override_conditional_write)
self.simple_code_objects[name] = codeobj
elif template_name in ['reset', 'synapses', 'stateupdate', 'threshold']:
codeobj_class = GeNNCodeObject
codeobj = super(GeNNDevice, self).code_object(owner, name,
abstract_code,
variables,
template_name,
variable_indices,
codeobj_class=codeobj_class,
template_kwds=template_kwds,
override_conditional_write=override_conditional_write,
)
self.simple_code_objects[codeobj.name] = codeobj
else:
codeobj_class = GeNNUserCodeObject
codeobj = super(GeNNDevice, self).code_object(owner, name,
abstract_code,
variables,
template_name,
variable_indices,
codeobj_class=codeobj_class,
template_kwds=template_kwds,
override_conditional_write=override_conditional_write,
)
self.code_objects[codeobj.name] = codeobj
return codeobj
# The following two methods are only overwritten to catch assignments to the
# delay variable -- GeNN does not support heterogeneous delays
def fill_with_array(self, var, arr):
if isinstance(var.owner, Synapses) and var.name == 'delay':
# Assigning is only allowed if the variable has been declared in the
# Synapse constructor and is therefore scalar
if not var.scalar:
raise NotImplementedError(
'GeNN does not support assigning to the '
'delay variable -- set the delay for all'
'synapses (heterogeneous delays are not '
'supported) as an argument to the '
'Synapses initializer.')
else:
# We store the delay so that we can later access it
self.delays[var.owner.name] = numpy.asarray(arr).item()
elif isinstance(var.owner, NeuronGroup) and var.name == 'lastspike':
# Workaround for versions of Brian 2 <= 2.1.3.1 which initialize
# a NeuronGroup's lastspike variable to -inf, no longer supported
# by the new implementation of the timestep function
if arr == -numpy.inf:
logger.warn('Initializing the lastspike variable with -10000s '
'instead of -inf to copy the behaviour of Brian 2 '
'for versions >= 2.2 -- upgrade Brian 2 to remove '
'this warning',
name_suffix='lastspike_inf', once=True)
arr = numpy.array(-1e4)
super(GeNNDevice, self).fill_with_array(var, arr)
def variableview_set_with_index_array(self, variableview, item,
value, check_units):
var = variableview.variable
if isinstance(var.owner, Synapses) and var.name == 'delay':
raise NotImplementedError('GeNN does not support assigning to the '
'delay variable -- set the delay for all '
'synapses (heterogeneous delays are not '
'supported) as an argument to the '
'Synapses initializer.')
super(GeNNDevice, self).variableview_set_with_index_array(variableview,
item,
value,
check_units)
def variableview_set_with_expression(self, variableview, item, code, run_namespace, check_units=True):
var = variableview.variable
if isinstance(var.owner, Synapses) and var.name == 'delay':
raise NotImplementedError('GeNN does not support assigning to the '
'delay variable -- set the delay for all '
'synapses (heterogeneous delays are not '
'supported) as an argument to the '
'Synapses initializer.')
variableview.set_with_expression.original_function(variableview,
item,
code,
run_namespace,
check_units)
def variableview_set_with_expression_conditional(self, variableview, cond,
code, run_namespace,
check_units=True):
var = variableview.variable
if isinstance(var.owner, Synapses) and var.name == 'delay':
raise NotImplementedError('GeNN does not support assigning to the '
'delay variable -- set the delay for all '
'synapses (heterogeneous delays are not '
'supported) as an argument to the '
'Synapses initializer.')
variableview.set_with_expression_conditional.original_function(variableview,
cond,
code,
run_namespace,
check_units)
# --------------------------------------------------------------------------
def make_main_lines(self):
'''
Generates the code lines that handle initialisation of Brian 2
cpp_standalone type arrays. These are then translated into the
appropriate GeNN data structures in separately generated code.
'''
main_lines = []
procedures = [('', main_lines)]
runfuncs = {}
for func, args in self.main_queue:
if func == 'run_code_object':
codeobj, = args
if self.run_statement_used:
raise NotImplementedError('Cannot execute code after the '
'run statement '
'(CodeObject: %s)' % codeobj.name)
# explicitly exclude spike queue related code objects here:
if not (codeobj.name.endswith('_initialise_queue') or
(codeobj.name.endswith('_push_spikes'))):
main_lines.append('_run_%s();' % codeobj.name)
elif func == 'run_network':
net, netcode = args
# do nothing
elif func == 'set_by_constant':
arrayname, value, is_dynamic = args
size_str = arrayname + '.size()' if is_dynamic else '_num_' + arrayname
code = '''
for(int i=0; i<{size_str}; i++)
{{
{arrayname}[i] = {value};
}}
'''.format(arrayname=arrayname, size_str=size_str,
value=CPPNodeRenderer().render_expr(repr(value)))
main_lines.extend(code.split('\n'))
elif func == 'set_by_array':
arrayname, staticarrayname, is_dynamic = args
size_str = arrayname + '.size()' if is_dynamic else '_num_' + arrayname
code = '''
for(int i=0; i<{size_str}; i++)
{{
{arrayname}[i] = {staticarrayname}[i];
}}
'''.format(arrayname=arrayname, size_str=size_str,
staticarrayname=staticarrayname)
main_lines.extend(code.split('\n'))
elif func == 'set_by_single_value':
arrayname, item, value = args
code = '{arrayname}[{item}] = {value};'.format(
arrayname=arrayname,
item=item,
value=value)
main_lines.extend([code])
elif func == 'set_array_by_array':
arrayname, staticarrayname_index, staticarrayname_value = args
code = '''
for(int i=0; i<_num_{staticarrayname_index}; i++)
{{
{arrayname}[{staticarrayname_index}[i]] = {staticarrayname_value}[i];
}}
'''.format(arrayname=arrayname,
staticarrayname_index=staticarrayname_index,
staticarrayname_value=staticarrayname_value)
main_lines.extend(code.split('\n'))
elif func == 'resize_array':
array_name, new_size = args
main_lines.append("{array_name}.resize({new_size});".format(
array_name=array_name,
new_size=new_size))
elif func == 'insert_code':
main_lines.append(args)
elif func == 'start_run_func':
name, include_in_parent = args
if include_in_parent:
main_lines.append('%s();' % name)
main_lines = []
procedures.append((name, main_lines))
elif func == 'end_run_func':
name, include_in_parent = args
name, main_lines = procedures.pop(-1)
runfuncs[name] = main_lines
name, main_lines = procedures[-1]
else:
raise NotImplementedError(
"Unknown main queue function type " + func)
# generate the finalisations
for codeobj in self.code_objects.itervalues():
if hasattr(codeobj.code, 'main_finalise'):
main_lines.append(codeobj.code.main_finalise)
return main_lines
def fix_random_generators(self, model, code):
'''
Translates cpp_standalone style random number generator calls into
GeNN- compatible calls by replacing the cpp_standalone
`_vectorisation_idx` argument with the GeNN `_seed` argument.
'''
# TODO: In principle, _vectorisation_idx is an argument to any
# function that does not take any arguments -- in practice, random
# number generators are the only argument-less functions that are
# commonly used. We cannot check for explicit names `_rand`, etc.,
# since multiple uses of binomial or PoissonInput will need to names
# that we cannot easily predict (poissoninput_binomial_2, etc.)
if '(_vectorisation_idx)' in code:
code = code.replace('(_vectorisation_idx)',
'(_seed)')
if not '_seed' in model.variables:
model.variables.append('_seed')
model.variabletypes.append('uint64_t')
model.variablescope['_seed'] = 'genn'
return code
# --------------------------------------------------------------------------
def build(self, directory='GeNNworkspace', compile=True, run=True,
use_GPU=True,
debug=False, with_output=True, direct_call=True):
'''
This function does the main post-translation work for the genn device.
It uses the code generated during/before run() and extracts information
about neuron groups, synapse groups, monitors, etc. that is then
formatted for use in GeNN-specific templates. The overarching strategy
of the brian2genn interface is to use cpp_standalone code generation
and templates for most of the "user-side code" (in the meaning defined
in GeNN) and have GeNN-specific templates for the model definition and
the main code for the executable that pulls everything together (in
main.cpp and engine.cpp templates). The handling of input/output
arrays for everything is lent from cpp_standalone and the
cpp_standalone arrays are then translated into GeNN-suitable data
structures using the static (not code-generated) b2glib library
functions. This means that the GeNN specific cod only has to be
concerned about executing the correct model and feeding back results
into the appropriate cpp_standalone data structures.
'''
print 'building genn executable ...'
if directory is None: # used during testing
directory = tempfile.mkdtemp()
# Start building the project
self.project_dir = directory
ensure_directory(directory)
for d in ['code_objects', 'results', 'static_arrays']:
ensure_directory(os.path.join(directory, d))
writer = CPPWriter(directory)
logger.debug(
"Writing GeNN project to directory " + os.path.normpath(directory))
# FIXME: This is only needed to keep Brian2GeNN compatible with Brian2 2.0.1 and earlier
if isinstance(self.arange_arrays, dict):
arange_arrays = sorted([(var, start)
for var, start in
self.arange_arrays.iteritems()],
key=lambda (var, start): var.name)
else:
arange_arrays = self.arange_arrays
# write the static arrays
logger.debug("static arrays: " + str(sorted(self.static_arrays.keys())))
static_array_specs = []
for name, arr in sorted(self.static_arrays.items()):
arr.tofile(os.path.join(directory, 'static_arrays', name))
static_array_specs.append(
(name, c_data_type(arr.dtype), arr.size, name))
synapses = []
synapses.extend(s for s in self.net.objects if isinstance(s, Synapses))
main_lines = self.make_main_lines()
# assemble the model descriptions:
objects = dict((obj.name, obj) for obj in self.net.objects)
neuron_groups = [obj for obj in self.net.objects if
isinstance(obj, NeuronGroup)]
poisson_groups = [obj for obj in self.net.objects if
isinstance(obj, PoissonGroup)]
spikegenerator_groups = [obj for obj in self.net.objects if
isinstance(obj, SpikeGeneratorGroup)]
synapse_groups = [obj for obj in self.net.objects if
isinstance(obj, Synapses)]
spike_monitors = [obj for obj in self.net.objects if
isinstance(obj, SpikeMonitor)]
rate_monitors = [obj for obj in self.net.objects if
isinstance(obj, PopulationRateMonitor)]
state_monitors = [obj for obj in self.net.objects if
isinstance(obj, StateMonitor)]
for obj in self.net.objects:
if isinstance(obj, (SpatialNeuron, SpatialStateUpdater)):
raise NotImplementedError(
'Brian2GeNN does not support multicompartmental neurons')
if not isinstance(obj, (
NeuronGroup, PoissonGroup, SpikeGeneratorGroup, Synapses,
SpikeMonitor, PopulationRateMonitor, StateMonitor,
StateUpdater, SynapsesStateUpdater, Resetter,
Thresholder, SynapticPathway, CodeRunner)):
raise NotImplementedError(
"Brian2GeNN does not support objects of type "
"'%s'" % obj.__class__.__name__)
# We only support run_regularly and "constant over dt"
# subexpressions for neurons
if (isinstance(obj, SubexpressionUpdater) and
not isinstance(obj.group, NeuronGroup)):
raise NotImplementedError(
'Subexpressions with the flag "constant over dt" are only '
'supported for NeuronGroup (not for objects of type '
'"%s").' % obj.group.__class__.__name__
)
if (obj.__class__ == CodeRunner and
not isinstance(obj.group, NeuronGroup)):
raise NotImplementedError(
'CodeRunner objects (most commonly created with the '
'"run_regularly" method) are only supported for '
'NeuronGroup (not for objects of type '
'"%s").' % obj.group.__class__.__name__
)
self.dtDef = 'model.setDT(' + repr(float(defaultclock.dt)) + ');'
# Process groups
self.process_neuron_groups(neuron_groups, objects)
self.process_poisson_groups(objects, poisson_groups)
self.process_spikegenerators(spikegenerator_groups)
self.process_synapses(synapse_groups)
# need to establish which kernel timers will be created if kernel riming is desired
if len(self.synapse_models) > 0:
self.ktimer['synapse_tme']= True
for synapse_model in self.synapse_models:
if len(synapse_model.main_code_lines['post']) > 0:
self.ktimer['learning_tme']= True
if len(synapse_model.main_code_lines['dynamics']) > 0:
self.ktimer['dynamics_tme']= True
# Process monitors
self.process_spike_monitors(spike_monitors)
self.process_rate_monitors(rate_monitors)
self.process_state_monitors(directory, state_monitors, writer)
# Write files from templates
# Create an empty network.h file, this allows us to use Brian2's
# objects.cpp template unchanged
writer.write('network.*', GeNNUserCodeObject.templater.network(None, None))
self.header_files.append('network.h')
self.generate_objects_source(arange_arrays, self.net,
static_array_specs,
synapses, writer)
self.copy_source_files(writer, directory)
# Rename randomkit.c so that it gets compiled by an explicit rule in
# GeNN's makefile template, otherwise optimization flags will not be
# used.
randomkit_dir = os.path.join(directory, 'brianlib', 'randomkit')
shutil.move(os.path.join(randomkit_dir, 'randomkit.c'),
os.path.join(randomkit_dir, 'randomkit.cc'))
self.generate_code_objects(writer)
self.generate_model_source(writer)
self.generate_main_source(writer, main_lines)
self.generate_engine_source(writer)
self.generate_makefile(directory, use_GPU)
# Compile and run
if compile:
try:
self.compile_source(debug, directory, use_GPU)
except CalledProcessError as ex:
raise RuntimeError(('Project compilation failed (Command {cmd} '
'failed with error code {returncode}).\n'
'See the output above (if any) for more '
'details.').format(cmd=ex.cmd,
returncode=ex.returncode)
)
if run:
try:
self.run(directory, use_GPU, with_output)
except CalledProcessError as ex:
if ex.returncode == 222:
raise NotImplementedError('GeNN does not support multiple '
'synapses per neuron pair (use '
'multiple Synapses objects).')
else:
raise RuntimeError(('Project run failed (Command {cmd} '
'failed with error code {returncode}).\n'
'See the output above (if any) for more '
'details.').format(cmd=ex.cmd,
returncode=ex.returncode)
)
def generate_code_objects(self, writer):
# Generate data for non-constant values
code_object_defs = defaultdict(list)
for codeobj in self.code_objects.itervalues():
lines = []
for k, v in codeobj.variables.iteritems():
if isinstance(v, ArrayVariable):
try:
if isinstance(v, DynamicArrayVariable):
if get_var_ndim(v) == 1:
dyn_array_name = self.dynamic_arrays[v]
array_name = self.arrays[v]
line = '{c_type}* const {array_name} = &{dyn_array_name}[0];'
line = line.format(c_type=c_data_type(v.dtype),
array_name=array_name,
dyn_array_name=dyn_array_name)
lines.append(line)
line = 'const int _num{k} = {dyn_array_name}.size();'
line = line.format(k=k,
dyn_array_name=dyn_array_name)
lines.append(line)
else:
lines.append('const int _num%s = %s;' % (k, v.size))
except TypeError:
pass
for line in lines:
# Sometimes an array is referred to by to different keys in our
# dictionary -- make sure to never add a line twice
if not line in code_object_defs[codeobj.name]:
code_object_defs[codeobj.name].append(line)
# Generate the code objects
for codeobj in self.code_objects.itervalues():
ns = codeobj.variables
# TODO: fix these freeze/CONSTANTS hacks somehow - they work but not elegant.
if not codeobj.template_name in ['stateupdate', 'threshold',
'reset', 'synapses']:
if isinstance(codeobj.code, MultiTemplate):
code = freeze(codeobj.code.cpp_file, ns)
code = code.replace('%CONSTANTS%', '\n'.join(
code_object_defs[codeobj.name]))
code = '#include "objects.h"\n' + code
writer.write('code_objects/' + codeobj.name + '.cpp', code)
self.source_files.append(
'code_objects/' + codeobj.name + '.cpp')
writer.write('code_objects/' + codeobj.name + '.h',
codeobj.code.h_file)
self.header_files.append(
'code_objects/' + codeobj.name + '.h')
def run(self, directory, use_GPU, with_output):
gpu_arg = "1" if use_GPU else "0"
if gpu_arg == "1":
where = 'on GPU'
else:
where = 'on CPU'
print 'executing genn binary %s ...' % where
pref_vars = prefs['devices.cpp_standalone.run_environment_variables']
for key, value in itertools.chain(pref_vars.iteritems(),
self.run_environment_variables.iteritems()):
if key in os.environ and os.environ[key] != value:
logger.info('Overwriting environment variable '
'"{key}"'.format(key=key),
name_suffix='overwritten_env_var', once=True)
os.environ[key] = value
with std_silent(with_output):
if os.sys.platform == 'win32':
cmd = directory + "\\main.exe test " + str(
self.run_duration) + " " + gpu_arg
check_call(cmd, cwd=directory)
else:
# print ["./main", "test", str(self.run_duration), gpu_arg]
check_call(["./main", "test", str(self.run_duration), gpu_arg],
cwd=directory)
self.has_been_run = True
last_run_info = open(
os.path.join(directory, 'results/last_run_info.txt'), 'r').read()
self._last_run_time, self._last_run_completed_fraction = map(float,
last_run_info.split())
# The following is a verbatim copy of the respective code in
# CPPStandaloneDevice.run. In the long run, we can hopefully implement
# this on the device-independent level, see #761 and discussion in
# #750.
# Make sure that integration did not create NaN or very large values
owners = [var.owner for var in self.arrays]
# We don't want to check the same owner twice but var.owner is a
# weakproxy which we can't put into a set. We therefore store the name
# of all objects we already checked. Furthermore, under some specific
# instances a variable might have been created whose owner no longer
# exists (e.g. a `_sub_idx` variable for a subgroup) -- we ignore the
# resulting reference error.
already_checked = set()
for owner in owners:
try:
if owner.name in already_checked:
continue
if isinstance(owner, Group):
owner._check_for_invalid_states()
already_checked.add(owner.name)
except ReferenceError:
pass
def compile_source(self, debug, directory, use_GPU):
if prefs.devices.genn.path is not None:
genn_path = prefs.devices.genn.path
logger.debug('Using GeNN path from preference: '
'"{}"'.format(genn_path))
elif 'GENN_PATH' in os.environ:
genn_path = os.environ['GENN_PATH']
logger.debug('Using GeNN path from environment variable: '
'"{}"'.format(genn_path))
else:
raise RuntimeError('Set the GENN_PATH environment variable or '
'the devices.genn.path preference.')
# Check for GeNN compatibility
genn_version = None
version_file = os.path.join(genn_path, 'version.txt')
if os.path.exists(version_file):
try:
with open(version_file, 'r') as f:
genn_version = parse_version(f.read().strip())
logger.debug('GeNN version: %s' % genn_version)
except (OSError, IOError) as ex:
logger.debug('Getting version from $GENN_PATH/version.txt '
'failed: %s' % str(ex))
if prefs.core.default_float_dtype == numpy.float32:
if genn_version is None or not genn_version >= parse_version('3.2'):
logger.warn('Support for single-precision floats requires GeNN '
'3.2 or later. Upgrade GeNN if the compilation '
'fails.', once=True)
env = os.environ.copy()
env['GENN_PATH'] = genn_path
if use_GPU:
if prefs.devices.genn.cuda_path is not None:
cuda_path = prefs.devices.genn.cuda_path
env['CUDA_PATH'] = cuda_path
logger.debug('Using CUDA path from preference: '
'"{}"'.format(cuda_path))
elif 'CUDA_PATH' in env:
cuda_path = env['CUDA_PATH']
logger.debug('Using CUDA path from environment variable: '
'"{}"'.format(cuda_path))
else:
raise RuntimeError('Set the CUDA_PATH environment variable or '
'the devices.genn.cuda_path preference.')
if prefs['codegen.cpp.extra_link_args']:
# declare the link flags as an environment variable so that GeNN's
# generateALL can pick it up
env['LINK_FLAGS'] = ' '.join(prefs['codegen.cpp.extra_link_args'])
with std_silent(debug):
if os.sys.platform == 'win32':
vcvars_loc = prefs['codegen.cpp.msvc_vars_location']
if vcvars_loc == '':
from distutils import msvc9compiler
for version in xrange(16, 8, -1):
fname = msvc9compiler.find_vcvarsall(version)
if fname:
vcvars_loc = fname
break
if vcvars_loc == '':
raise IOError("Cannot find vcvarsall.bat on standard "
"search path. Set the "
"codegen.cpp.msvc_vars_location preference "
"explicitly.")
arch_name = prefs['codegen.cpp.msvc_architecture']
if arch_name == '':
mach = platform.machine()
if mach == 'AMD64':
arch_name = 'x86_amd64'
else:
arch_name = 'x86'
vcvars_cmd = '"{vcvars_loc}" {arch_name}'.format(
vcvars_loc=vcvars_loc, arch_name=arch_name)
buildmodel_cmd = os.path.join(genn_path, 'lib', 'bin',
'genn-buildmodel.bat')
cmd = vcvars_cmd + ' && ' + buildmodel_cmd + " magicnetwork_model.cpp"
if not use_GPU:
cmd += ' -c'
cmd += ' && nmake /f WINmakefile clean && nmake /f WINmakefile'
check_call(cmd.format(genn_path=genn_path), cwd=directory, env=env)
else:
buildmodel_cmd = os.path.join(genn_path, 'lib', 'bin', 'genn-buildmodel.sh')
args = [buildmodel_cmd, 'magicnetwork_model.cpp']
if not use_GPU:
args += ['-c']
check_call(args, cwd=directory, env=env)