Debian Codegraph @

brian2/devices/cpp_standalone/device.py

raw
1 """
2 Module implementing the C++ "standalone" device.
3 """
4
5 import inspect
6 import itertools
7 import numbers
8 import os
9 import shutil
10 import subprocess
11 import sys
12 import tempfile
13 import time
14 import zlib
15 from collections import Counter, defaultdict
16 from collections.abc import Mapping
17 from hashlib import md5
18
19 import numpy as np
20 from distutils import ccompiler
21
22 from brian2.codegen.codeobject import check_compiler_kwds
23 from brian2.codegen.cpp_prefs import get_compiler_and_args, get_msvc_env
24 from brian2.codegen.generators.cpp_generator import c_data_type
25 from brian2.core.clocks import EventClock
26 from brian2.core.functions import Function
27 from brian2.core.namespace import get_local_namespace
28 from brian2.core.network import Network
29 from brian2.core.preferences import BrianPreference, prefs
30 from brian2.core.variables import (
31 ArrayVariable,
32 Constant,
33 DynamicArrayVariable,
34 Variable,
35 VariableView,
36 )
37 from brian2.devices.device import Device, all_devices, reset_device, set_device
38 from brian2.groups.group import Group
39 from brian2.input import TimedArray
40 from brian2.parsing.rendering import CPPNodeRenderer
41 from brian2.synapses.synapses import Synapses
42 from brian2.units import second
43 from brian2.units.fundamentalunits import Quantity, fail_for_dimension_mismatch
44 from brian2.utils.filelock import FileLock
45 from brian2.utils.filetools import copy_directory, ensure_directory, in_directory
46 from brian2.utils.logger import get_logger, std_silent
47 from brian2.utils.stringtools import word_substitute
48
49 from .codeobject import CPPStandaloneCodeObject, openmp_pragma
50
51 __all__ = []
52
53 logger = get_logger(__name__)
54
55
56 # Preferences
57 prefs.register_preferences(
58 "devices.cpp_standalone",
59 "C++ standalone preferences ",
60 openmp_threads=BrianPreference(
61 default=0,
62 docs="""
63 The number of threads to use if OpenMP is turned on. By default, this value is set to 0 and the C++ code
64 is generated without any reference to OpenMP. If greater than 0, then the corresponding number of threads
65 are used to launch the simulation.
66 """,
67 ),
68 openmp_spatialneuron_strategy=BrianPreference(
69 default=None,
70 validator=lambda val: val in [None, "branches", "systems"],
71 docs="""
72 DEPRECATED. Previously used to chose the strategy to parallelize the
73 solution of the three tridiagonal systems for multicompartmental
74 neurons. Now, its value is ignored.
75 """,
76 ),
77 make_cmd_unix=BrianPreference(
78 default="make",
79 docs="""
80 The make command used to compile the standalone project. Defaults to the
81 standard GNU make commane "make".""",
82 ),
83 run_cmd_unix=BrianPreference(
84 default="./main",
85 validator=lambda val: isinstance(val, str) or isinstance(val, list),
86 docs="""
87 The command used to run the compiled standalone project. Defaults to executing
88 the compiled binary with "./main". Must be a single binary as string or a list
89 of command arguments (e.g. ["./binary", "--key", "value"]).
90 """,
91 ),
92 extra_make_args_unix=BrianPreference(
93 default=[f"-j{os.cpu_count()}"],
94 docs="""
95 Additional flags to pass to the GNU make command on Linux/OS-X.
96 Defaults to "-j $(CPU_COUNT)" for parallel compilation.""",
97 ),
98 extra_make_args_windows=BrianPreference(
99 default=[],
100 docs="""
101 Additional flags to pass to the nmake command on Windows. By default, no
102 additional flags are passed.
103 """,
104 ),
105 run_environment_variables=BrianPreference(
106 default={"LD_BIND_NOW": "1"},
107 docs="""
108 Dictionary of environment variables and their values that will be set
109 during the execution of the standalone code.
110 """,
111 ),
112 )
113
114
115 class CPPWriter:
116 def __init__(self, project_dir):
117 self.project_dir = project_dir
118 self.source_files = set()
119 self.header_files = set()
120
121 def write(self, filename, contents):
122 logger.diagnostic(f"Writing file {filename}:\n{contents}")
123 if filename.lower().endswith(".cpp") or filename.lower().endswith(".c"):
124 self.source_files.add(filename)
125 elif filename.lower().endswith(".h"):
126 self.header_files.add(filename)
127 elif filename.endswith(".*"):
128 self.write(f"{filename[:-1]}cpp", contents.cpp_file)
129 self.write(f"{filename[:-1]}h", contents.h_file)
130 return
131 fullfilename = os.path.join(self.project_dir, filename)
132 if os.path.exists(fullfilename):
133 with open(fullfilename) as f:
134 if f.read() == contents:
135 return
136 with open(fullfilename, "w") as f:
137 f.write(contents)
138
139
140 def invert_dict(x):
141 return {v: k for k, v in x.items()}
142
143
144 class CPPStandaloneDevice(Device):
145 """
146 The `Device` used for C++ standalone simulations.
147 """
148
149 def __init__(self):
150 super().__init__()
151 #: Dictionary mapping `ArrayVariable` objects to their globally
152 #: unique name
153 self.arrays = {}
154 #: Dictionary mapping `ArrayVariable` objects to their value or to
155 #: ``None`` if the value (potentially) depends on executed code. This
156 #: mechanism allows to access state variables in standalone mode if
157 #: their value is known at run time
158 self.array_cache = {}
159 #: List of all dynamic arrays
160 #: Dictionary mapping `DynamicArrayVariable` objects with 1 dimension to
161 #: their globally unique name
162 self.dynamic_arrays = {}
163 #: Dictionary mapping `DynamicArrayVariable` objects with 2 dimensions
164 #: to their globally unique name
165 self.dynamic_arrays_2d = {}
166 #: List of all arrays to be filled with zeros (list of (var, varname) )
167 self.zero_arrays = []
168 #: List of all arrays to be filled with numbers (list of
169 #: (var, varname, start) tuples
170 self.arange_arrays = []
171 #: Set of all existing synapses
172 self.synapses = set()
173 #: Whether the simulation has been run
174 self.has_been_run = False
175
176 #: Whether apply_run_args has been called
177 self.run_args_applied = False
178
179 #: Whether a run should trigger a build
180 self.build_on_run = False
181
182 #: build options
183 self.build_options = None
184
185 #: The directory which contains the generated code and results
186 self.project_dir = None
187
188 #: The directory which contains the results (relative to `project_dir``)
189 self.results_dir = None
190
191 #: Whether to generate profiling information (stored in an instance
192 #: variable to be accessible during CodeObject generation)
193 self.enable_profiling = False
194
195 #: CodeObjects that use profiling (users can potentially enable
196 #: profiling only for a subset of runs)
197 self.profiled_codeobjects = []
198
199 #: Dict of all static saved arrays
200 self.static_arrays = {}
201
202 #: Names of static arrays used for run_args given as lists of values
203 self.run_args_arrays = []
204
205 #: Dict of all TimedArray objects
206 self.timed_arrays = {}
207
208 self.code_objects = {}
209 self.main_queue = []
210 self.runfuncs = {}
211 self.networks = set()
212 self.static_array_specs = []
213 self.report_func = ""
214
215 #: Code lines that have been manually added with `device.insert_code`
216 #: Dictionary mapping slot names to lists of lines.
217 #: Note that the main slot is handled separately as part of `main_queue`
218 self.code_lines = {
219 "before_start": [],
220 "after_start": [],
221 "before_network_run": [],
222 "after_network_run": [],
223 "before_end": [],
224 "after_end": [],
225 }
226
227 #: Dictionary storing compile and binary execution times
228 self.timers = {"run_binary": None, "compile": {"clean": None, "make": None}}
229
230 self.clocks = set()
231
232 self.extra_compile_args = []
233 self.define_macros = []
234 self.headers = []
235 self.include_dirs = []
236 self.library_dirs = []
237 self.runtime_library_dirs = []
238 self.run_environment_variables = {}
239 if sys.platform.startswith("darwin"):
240 if "DYLD_LIBRARY_PATH" in os.environ:
241 dyld_library_path = f"{os.environ['DYLD_LIBRARY_PATH']}:{os.path.join(sys.prefix, 'lib')}"
242 else:
243 dyld_library_path = os.path.join(sys.prefix, "lib")
244 self.run_environment_variables["DYLD_LIBRARY_PATH"] = dyld_library_path
245 self.libraries = []
246 if sys.platform == "win32":
247 self.libraries += ["advapi32"]
248 self.extra_link_args = []
249 self.writer = None
250
251 def reinit(self):
252 # Remember the build_on_run setting and its options -- important during
253 # testing
254 build_on_run = self.build_on_run
255 build_options = self.build_options
256 self.__init__()
257 super().reinit()
258 self.build_on_run = build_on_run
259 self.build_options = build_options
260
261 def spike_queue(self, source_start, source_end):
262 return None # handled differently
263
264 def freeze(self, code, ns):
265 # TODO: Remove this function at some point
266 logger.warn(
267 "The CPPStandaloneDevice.freeze function should no longer "
268 "be used, add constant definitions directly to the "
269 'code in the "CONSTANTS" section instead.',
270 name_suffix="deprecated_freeze_use",
271 once=True,
272 )
273 # this is a bit of a hack, it should be passed to the template somehow
274 for k, v in ns.items():
275 if isinstance(v, Variable) and v.scalar and v.constant and v.read_only:
276 try:
277 v = v.get_value()
278 except NotImplementedError:
279 continue
280 if isinstance(v, str):
281 code = word_substitute(code, {k: v})
282 elif isinstance(v, numbers.Number):
283 # Use a renderer to correctly transform constants such as True or inf
284 renderer = CPPNodeRenderer()
285 string_value = renderer.render_expr(repr(v))
286 if prefs.core.default_float_dtype == np.float32 and isinstance(
287 v, (float, np.float32, np.float64)
288 ):
289 string_value += "f"
290 if v < 0:
291 string_value = f"({string_value})"
292 code = word_substitute(code, {k: string_value})
293 else:
294 pass # don't deal with this object
295 return code
296
297 def insert_code(self, slot, code):
298 """
299 Insert code directly into main.cpp
300 """
301 if slot == "main":
302 self.main_queue.append(("insert_code", code))
303 elif slot in self.code_lines:
304 self.code_lines[slot].append(code)
305 else:
306 logger.warn(f"Ignoring device code, unknown slot: {slot}, code: {code}")
307
308 def apply_run_args(self):
309 if self.run_args_applied:
310 raise RuntimeError(
311 "The 'apply_run_args()' function can only be called once."
312 )
313 self.insert_code("main", "set_from_command_line(args);")
314 self.run_args_applied = True
315
316 def static_array(self, name, arr):
317 arr = np.atleast_1d(arr)
318 assert len(arr), f"length for {name}: {len(arr)}"
319 name = f"_static_array_{name}"
320 basename = name
321 i = 0
322 while name in self.static_arrays:
323 i += 1
324 name = f"{basename}_{str(i)}"
325 self.static_arrays[name] = arr.copy()
326 return name
327
328 def get_array_name(self, var, access_data=True):
329 """
330 Return a globally unique name for `var`.
331
332 Parameters
333 ----------
334 access_data : bool, optional
335 For `DynamicArrayVariable` objects, specifying `True` here means the
336 name for the underlying data is returned. If specifying `False`,
337 the name of object itself is returned (e.g. to allow resizing).
338 """
339 if isinstance(var, DynamicArrayVariable):
340 if access_data:
341 return self.arrays[var]
342 elif var.ndim == 1:
343 return self.dynamic_arrays[var]
344 else:
345 return self.dynamic_arrays_2d[var]
346 elif isinstance(var, ArrayVariable):
347 return self.arrays[var]
348 else:
349 raise TypeError(f"Do not have a name for variable of type {type(var)}.")
350
351 def get_array_filename(self, var, basedir=None):
352 """
353 Return a file name for a variable.
354
355 Parameters
356 ----------
357 var : `ArrayVariable`
358 The variable to get a filename for.
359 basedir : str
360 The base directory for the filename, defaults to ``'results'``.
361 DEPRECATED: Will raise an error if specified.
362 Returns
363 -------
364 filename : str
365 A filename of the form
366 ``varname+'_'+str(zlib.crc32(varname))``, where varname
367 is the name returned by `get_array_name`.
368
369 Notes
370 -----
371 The reason that the filename is not simply ``varname`` is
372 that this could lead to file names that are not unique in file systems
373 that are not case sensitive (e.g. on Windows).
374 """
375 if basedir is not None:
376 raise ValueError("Specifying 'basedir' is no longer supported.")
377 varname = self.get_array_name(var, access_data=False)
378 return f"{varname}_{str(zlib.crc32(varname.encode('utf-8')))}"
379
380 def add_array(self, var):
381 # Note that a dynamic array variable is added to both the arrays and
382 # the _dynamic_array dictionary
383 if isinstance(var, DynamicArrayVariable):
384 # The code below is slightly more complicated than just looking
385 # for a unique name as above for static_array, the name has
386 # potentially to be unique for more than one dictionary, with
387 # different prefixes. This is because dynamic arrays are added to
388 # a ``dynamic_arrays`` dictionary (with a `_dynamic` prefix) and to
389 # the general ``arrays`` dictionary. We want to make sure that we
390 # use the same name in the two dictionaries, not for example
391 # ``_dynamic_array_source_name_2`` and ``_array_source_name_1``
392 # (this would work fine, but it would make the code harder to read).
393 orig_dynamic_name = dynamic_name = (
394 f"_dynamic_array_{var.owner.name}_{var.name}"
395 )
396 orig_array_name = array_name = f"_array_{var.owner.name}_{var.name}"
397 suffix = 0
398
399 if var.ndim == 1:
400 dynamic_dict = self.dynamic_arrays
401 elif var.ndim == 2:
402 dynamic_dict = self.dynamic_arrays_2d
403 else:
404 raise AssertionError(
405 "Did not expect a dynamic array with {var.ndim} dimensions."
406 )
407 while (
408 dynamic_name in dynamic_dict.values()
409 or array_name in self.arrays.values()
410 ):
411 suffix += 1
412 dynamic_name = f"{orig_dynamic_name}_{int(suffix)}"
413 array_name = f"{orig_array_name}_{int(suffix)}"
414 dynamic_dict[var] = dynamic_name
415 self.arrays[var] = array_name
416 else:
417 orig_array_name = array_name = f"_array_{var.owner.name}_{var.name}"
418 suffix = 0
419 while array_name in self.arrays.values():
420 suffix += 1
421 array_name = f"{orig_array_name}_{int(suffix)}"
422 self.arrays[var] = array_name
423
424 def init_with_zeros(self, var, dtype):
425 if isinstance(var, DynamicArrayVariable):
426 varname = f"_dynamic{self.arrays[var]}"
427 else:
428 varname = self.arrays[var]
429 self.zero_arrays.append((var, varname))
430 self.array_cache[var] = np.zeros(var.size, dtype=dtype)
431
432 def init_with_arange(self, var, start, dtype):
433 if isinstance(var, DynamicArrayVariable):
434 varname = f"_dynamic{self.arrays[var]}"
435 else:
436 varname = self.arrays[var]
437 self.arange_arrays.append((var, varname, start))
438 self.array_cache[var] = np.arange(0, var.size, dtype=dtype) + start
439
440 def fill_with_array(self, var, arr):
441 arr = np.asarray(arr)
442 if arr.size == 0:
443 return # nothing to do
444 array_name = self.get_array_name(var, access_data=False)
445 if isinstance(var, DynamicArrayVariable):
446 # We can never be sure about the size of a dynamic array, so
447 # we can't do correct broadcasting. Therefore, we do not cache
448 # them at all for now.
449 self.array_cache[var] = None
450 else:
451 new_arr = np.empty(var.size, dtype=var.dtype)
452 new_arr[:] = arr
453 self.array_cache[var] = new_arr
454
455 if arr.size == 1:
456 if var.size == 1:
457 value = CPPNodeRenderer().render_expr(repr(arr.item(0)))
458 # For a single assignment, generate a code line instead of storing the array
459 self.main_queue.append(("set_by_single_value", (array_name, 0, value)))
460 else:
461 self.main_queue.append(
462 (
463 "set_by_constant",
464 (array_name, arr.item(), isinstance(var, DynamicArrayVariable)),
465 )
466 )
467 else:
468 # Using the std::vector instead of a pointer to the underlying
469 # data for dynamic arrays is fast enough here and it saves us some
470 # additional work to set up the pointer
471 static_array_name = self.static_array(array_name, arr)
472 self.main_queue.append(
473 (
474 "set_by_array",
475 (
476 array_name,
477 static_array_name,
478 isinstance(var, DynamicArrayVariable),
479 ),
480 )
481 )
482
483 def resize(self, var, new_size):
484 array_name = self.get_array_name(var, access_data=False)
485 self.main_queue.append(("resize_array", (array_name, new_size)))
486
487 def variableview_set_with_index_array(self, variableview, item, value, check_units):
488 if isinstance(item, slice) and item == slice(None):
489 item = "True"
490 value = Quantity(value)
491
492 if (
493 isinstance(item, int) or (isinstance(item, np.ndarray) and item.shape == ())
494 ) and value.size == 1:
495 array_name = self.get_array_name(variableview.variable, access_data=False)
496 value_str = CPPNodeRenderer().render_expr(repr(np.asarray(value).item(0)))
497 if self.array_cache.get(variableview.variable, None) is not None:
498 self.array_cache[variableview.variable][item] = value
499 # For a single assignment, generate a code line instead of storing the array
500 self.main_queue.append(
501 ("set_by_single_value", (array_name, item, value_str))
502 )
503 # Simple case where we don't have to do any indexing
504 elif item == "True" and variableview.index_var in ("_idx", "0"):
505 self.fill_with_array(variableview.variable, value)
506 else:
507 # We have to calculate indices. This will not work for synaptic
508 # variables
509 try:
510 indices = np.asarray(
511 variableview.indexing(item, index_var=variableview.index_var)
512 )
513 except NotImplementedError:
514 raise NotImplementedError(
515 f"Cannot set variable '{variableview.name}' "
516 "this way in standalone, try using "
517 "string expressions."
518 ) from None
519 # Using the std::vector instead of a pointer to the underlying
520 # data for dynamic arrays is fast enough here and it saves us some
521 # additional work to set up the pointer
522 arrayname = self.get_array_name(variableview.variable, access_data=False)
523 if indices.shape != () and (
524 value.shape == () or (value.size == 1 and indices.size > 1)
525 ):
526 value = np.repeat(value, indices.size)
527 elif value.shape != indices.shape and len(value) != len(indices):
528 raise ValueError(
529 "Provided values do not match the size "
530 "of the indices, "
531 f"{len(value)} != len(indices)."
532 )
533
534 staticarrayname_index = self.static_array(f"_index_{arrayname}", indices)
535 staticarrayname_value = self.static_array(f"_value_{arrayname}", value)
536 self.array_cache[variableview.variable] = None
537 self.main_queue.append(
538 (
539 "set_array_by_array",
540 (arrayname, staticarrayname_index, staticarrayname_value),
541 )
542 )
543
544 def get_value(self, var, access_data=True):
545 # Usually, we cannot retrieve the values of state variables in
546 # standalone scripts since their values might depend on the evaluation
547 # of expressions at runtime. For some variables we do know the value
548 # however (values that have been set with explicit values and not
549 # changed in code objects)
550 if self.array_cache.get(var, None) is not None:
551 return self.array_cache[var]
552 else:
553 # After the network has been run, we can retrieve the values from
554 # disk
555 if self.has_been_run:
556 dtype = var.dtype
557 fname = os.path.join(self.results_dir, self.get_array_filename(var))
558 with open(fname, "rb") as f:
559 data = np.fromfile(f, dtype=dtype)
560 # This is a bit of an heuristic, but our 2d dynamic arrays are
561 # only expanding in one dimension, we assume here that the
562 # other dimension has size 0 at the beginning
563 if isinstance(var.size, tuple) and len(var.size) == 2:
564 if var.size[0] * var.size[1] == len(data):
565 size = var.size
566 elif var.size[0] == 0:
567 size = (len(data) // var.size[1], var.size[1])
568 elif var.size[1] == 0:
569 size = (var.size[0], len(data) // var.size[0])
570 else:
571 raise IndexError(
572 "Do not now how to deal with 2d "
573 f"array of size {var.size!s}, the array on "
574 f"disk has length {len(data)}."
575 )
576
577 var.size = size
578 return data.reshape(var.size)
579 var.size = len(data)
580 return data
581 raise NotImplementedError(
582 "Cannot retrieve the values of state "
583 "variables in standalone code before the "
584 "simulation has been run."
585 )
586
587 def variableview_get_subexpression_with_index_array(
588 self, variableview, item, run_namespace=None
589 ):
590 if not self.has_been_run:
591 raise NotImplementedError(
592 "Cannot retrieve the values of state "
593 "variables in standalone code before the "
594 "simulation has been run."
595 )
596 # Temporarily switch to the runtime device to evaluate the subexpression
597 # (based on the values stored on disk)
598 set_device("runtime")
599 result = VariableView.get_subexpression_with_index_array(
600 variableview, item, run_namespace=run_namespace
601 )
602 reset_device()
603 return result
604
605 def variableview_get_with_expression(self, variableview, code, run_namespace=None):
606 raise NotImplementedError(
607 "Cannot retrieve the values of state "
608 "variables with string expressions in "
609 "standalone scripts."
610 )
611
612 def code_object_class(self, codeobj_class=None, fallback_pref=None):
613 """
614 Return `CodeObject` class (either `CPPStandaloneCodeObject` class or input)
615
616 Parameters
617 ----------
618 codeobj_class : a `CodeObject` class, optional
619 If this is keyword is set to None or no arguments are given, this method will return
620 the default (`CPPStandaloneCodeObject` class).
621 fallback_pref : str, optional
622 For the cpp_standalone device this option is ignored.
623
624 Returns
625 -------
626 codeobj_class : class
627 The `CodeObject` class that should be used
628 """
629 # Ignore the requested pref (used for optimization in runtime)
630 if codeobj_class is None:
631 return CPPStandaloneCodeObject
632 else:
633 return codeobj_class
634
635 def code_object(
636 self,
637 owner,
638 name,
639 abstract_code,
640 variables,
641 template_name,
642 variable_indices,
643 codeobj_class=None,
644 template_kwds=None,
645 override_conditional_write=None,
646 compiler_kwds=None,
647 ):
648 if compiler_kwds is None:
649 compiler_kwds = {}
650 check_compiler_kwds(
651 compiler_kwds,
652 [
653 "headers",
654 "sources",
655 "define_macros",
656 "libraries",
657 "include_dirs",
658 "library_dirs",
659 "runtime_library_dirs",
660 ],
661 "C++ standalone",
662 )
663 if template_kwds is None:
664 template_kwds = dict()
665 else:
666 template_kwds = dict(template_kwds)
667 # In standalone mode, the only place where we use additional header
668 # files is by inserting them into the template
669 codeobj_headers = compiler_kwds.get("headers", [])
670 template_kwds["user_headers"] = (
671 self.headers + prefs["codegen.cpp.headers"] + codeobj_headers
672 )
673 template_kwds["profiled"] = self.enable_profiling
674
675 do_not_invalidate = set()
676 if template_name == "synapses_create_array":
677 cache = self.array_cache
678 if (
679 cache[variables["N"]] is None
680 ): # synapses have been previously created with code
681 # Nothing we can do
682 logger.debug(
683 f"Synapses for '{owner.name}' have previously been created with "
684 "code, we therefore cannot cache the synapses created with arrays "
685 f"via '{name}'",
686 name_suffix="code_created_synapses_exist",
687 )
688 else: # first time we create synapses, or all previous connect calls were with arrays
689 cache[variables["N"]][0] += variables["sources"].size
690 do_not_invalidate.add(variables["N"])
691 for var, value in [
692 (
693 variables["_synaptic_pre"],
694 variables["sources"].get_value()
695 + variables["_source_offset"].get_value(),
696 ),
697 (
698 variables["_synaptic_post"],
699 variables["targets"].get_value()
700 + variables["_target_offset"].get_value(),
701 ),
702 ]:
703 cache[var] = np.append(
704 cache.get(var, np.empty(0, dtype=int)), value
705 )
706 do_not_invalidate.add(var)
707
708 codeobj = super().code_object(
709 owner,
710 name,
711 abstract_code,
712 variables,
713 template_name,
714 variable_indices,
715 codeobj_class=codeobj_class,
716 template_kwds=template_kwds,
717 override_conditional_write=override_conditional_write,
718 compiler_kwds=compiler_kwds,
719 )
720 self.code_objects[codeobj.name] = codeobj
721 if self.enable_profiling:
722 self.profiled_codeobjects.append(codeobj.name)
723
724 for var in codeobj.variables.values():
725 if isinstance(var, TimedArray):
726 self.timed_arrays[var] = var.name
727 # We mark all writeable (i.e. not read-only) variables used by the code
728 # as "dirty" to avoid that the cache contains incorrect values. This
729 # might remove a number of variables from the cache unnecessarily,
730 # since many variables are only read in the code.
731 # On the other hand, there are also *read-only* variables that can be
732 # changed by code (the "read-only" attribute only refers to the user
733 # being able to change values directly). For example, synapse creation
734 # write source and target indices, and monitors write the shared values.
735 # To correctly mark these values as changed, templates can include a
736 # "WRITES_TO_READ_ONLY_VARIABLES" comment, stating the name of the
737 # changed variables. For a monitor, this would for example state that
738 # the number of recorded values "N" changes. For the recorded variables,
739 # however, this information cannot be included in the template because
740 # it is up to the user to define which variables are recorded. For such
741 # cases, the "owner" object (e.g. a SpikeMonitor) can define a
742 # "written_readonly_vars" attribute, storing a set of `Variable` objects
743 # that will be changed by the owner's code objects.
744 template = getattr(codeobj.templater, template_name)
745 written_readonly_vars = {
746 codeobj.variables[varname] for varname in template.writes_read_only
747 } | getattr(owner, "written_readonly_vars", set())
748 for var in codeobj.variables.values():
749 if (
750 isinstance(var, ArrayVariable)
751 and var not in do_not_invalidate
752 and (not var.read_only or var in written_readonly_vars)
753 ):
754 self.array_cache[var] = None
755
756 return codeobj
757
758 def check_openmp_compatible(self, nb_threads):
759 if nb_threads > 0:
760 logger.warn(
761 "OpenMP code is not yet well tested, and may be inaccurate.",
762 "openmp",
763 once=True,
764 )
765 logger.diagnostic(f"Using OpenMP with {int(nb_threads)} threads ")
766 if prefs.devices.cpp_standalone.openmp_spatialneuron_strategy is not None:
767 logger.warn(
768 "The devices.cpp_standalone.openmp_spatialneuron_strategy "
769 "preference is no longer used and will be removed in "
770 "future versions of Brian.",
771 "openmp_spatialneuron_strategy",
772 once=True,
773 )
774
775 def generate_objects_source(
776 self,
777 writer,
778 arange_arrays,
779 synapses,
780 static_array_specs,
781 networks,
782 timed_arrays,
783 ):
784 arr_tmp = self.code_object_class().templater.objects(
785 None,
786 None,
787 array_specs=self.arrays,
788 dynamic_array_specs=self.dynamic_arrays,
789 dynamic_array_2d_specs=self.dynamic_arrays_2d,
790 zero_arrays=self.zero_arrays,
791 arange_arrays=arange_arrays,
792 synapses=synapses,
793 clocks=self.clocks,
794 static_array_specs=static_array_specs,
795 networks=networks,
796 get_array_filename=self.get_array_filename,
797 get_array_name=self.get_array_name,
798 profiled_codeobjects=self.profiled_codeobjects,
799 code_objects=list(self.code_objects.values()),
800 timed_arrays=timed_arrays,
801 )
802 writer.write("objects.*", arr_tmp)
803
804 def generate_main_source(self, writer):
805 main_lines = []
806 procedures = [("", main_lines)]
807 runfuncs = {}
808 for func, args in self.main_queue:
809 if func == "before_run_code_object":
810 (codeobj,) = args
811 main_lines.append(f"_before_run_{codeobj.name}();")
812 elif func == "run_code_object":
813 (codeobj,) = args
814 main_lines.append(f"_run_{codeobj.name}();")
815 elif func == "after_run_code_object":
816 (codeobj,) = args
817 main_lines.append(f"_after_run_{codeobj.name}();")
818 elif func == "run_network":
819 net, netcode = args
820 main_lines.extend(netcode)
821 elif func == "set_by_constant":
822 arrayname, value, is_dynamic = args
823 size_str = f"{arrayname}.size()" if is_dynamic else f"_num_{arrayname}"
824 code = f"""
825 {openmp_pragma("static")}
826 for(int i=0; i<{size_str}; i++)
827 {{
828 {arrayname}[i] = {CPPNodeRenderer().render_expr(repr(value))};
829 }}
830 """
831 main_lines.extend(code.split("\n"))
832 elif func == "set_by_array":
833 arrayname, staticarrayname, is_dynamic = args
834 size_str = f"{arrayname}.size()" if is_dynamic else f"_num_{arrayname}"
835 code = f"""
836 {openmp_pragma("static")}
837 for(int i=0; i<{size_str}; i++)
838 {{
839 {arrayname}[i] = {staticarrayname}[i];
840 }}
841 """
842 main_lines.extend(code.split("\n"))
843 elif func == "set_by_single_value":
844 arrayname, item, value = args
845 code = f"{arrayname}[{item}] = {value};"
846 main_lines.extend([code])
847 elif func == "set_array_by_array":
848 arrayname, staticarrayname_index, staticarrayname_value = args
849 code = f"""
850 {openmp_pragma("static")}
851 for(int i=0; i<_num_{staticarrayname_index}; i++)
852 {{
853 {arrayname}[{staticarrayname_index}[i]] = {staticarrayname_value}[i];
854 }}
855 """
856 main_lines.extend(code.split("\n"))
857 elif func == "resize_array":
858 array_name, new_size = args
859 main_lines.append(f"{array_name}.resize({new_size});")
860 elif func == "insert_code":
861 main_lines.append(args)
862 elif func == "start_run_func":
863 name, include_in_parent = args
864 if include_in_parent:
865 main_lines.append(f"{name}();")
866 main_lines = []
867 procedures.append((name, main_lines))
868 elif func == "end_run_func":
869 name, include_in_parent = args
870 name, main_lines = procedures.pop(-1)
871 runfuncs[name] = main_lines
872 name, main_lines = procedures[-1]
873 elif func == "seed":
874 seed = args
875 nb_threads = prefs.devices.cpp_standalone.openmp_threads
876 if nb_threads == 0: # no OpenMP
877 nb_threads = 1
878 main_lines.append(f"for (int _i=0; _i<{nb_threads}; _i++)")
879 if seed is None: # random
880 main_lines.append(" brian::_random_generators[_i].seed();")
881 else:
882 main_lines.append(
883 f" brian::_random_generators[_i].seed({seed!r}L + _i);"
884 )
885 else:
886 raise NotImplementedError(f"Unknown main queue function type {func}")
887
888 self.runfuncs = runfuncs
889
890 # generate the finalisations
891 for codeobj in self.code_objects.values():
892 if hasattr(codeobj.code, "main_finalise"):
893 main_lines.append(codeobj.code.main_finalise)
894
895 user_headers = self.headers + prefs["codegen.cpp.headers"]
896 main_tmp = self.code_object_class().templater.main(
897 None,
898 None,
899 main_lines=main_lines,
900 code_lines=self.code_lines,
901 code_objects=list(self.code_objects.values()),
902 report_func=self.report_func,
903 dt=float(self.defaultclock.dt),
904 user_headers=user_headers,
905 )
906 writer.write("main.cpp", main_tmp)
907
908 def generate_codeobj_source(self, writer):
909 # Generate data for non-constant values
910 renderer = CPPNodeRenderer()
911 code_object_defs = defaultdict(list)
912 for codeobj in self.code_objects.values():
913 lines = []
914 for k, v in codeobj.variables.items():
915 if isinstance(v, ArrayVariable):
916 try:
917 if isinstance(v, DynamicArrayVariable):
918 if v.ndim == 1:
919 dyn_array_name = self.dynamic_arrays[v]
920 array_name = self.arrays[v]
921 c_type = c_data_type(v.dtype)
922 line = (
923 f"{c_type}* const {array_name} ="
924 f" {dyn_array_name}.empty()? 0 :"
925 f" &{dyn_array_name}[0];"
926 )
927 lines.append(line)
928 line = (
929 f"const size_t _num{k} = {dyn_array_name}.size();"
930 )
931 lines.append(line)
932 else:
933 lines.append(f"const size_t _num{k} = {v.size};")
934 except TypeError:
935 pass
936 elif isinstance(v, Constant):
937 value = renderer.render_expr(repr(v.value))
938 c_type = c_data_type(v.dtype)
939 line = f"const {c_type} {k} = {value};"
940 lines.append(line)
941 for line in lines:
942 # Sometimes an array is referred to by to different keys in our
943 # dictionary -- make sure to never add a line twice
944 if line not in code_object_defs[codeobj.name]:
945 code_object_defs[codeobj.name].append(line)
946
947 # Generate the code objects
948 for codeobj in self.code_objects.values():
949 # Before/after run code
950 for block in codeobj.before_after_blocks:
951 cpp_code = getattr(codeobj.code, f"{block}_cpp_file")
952 cpp_code = cpp_code.replace(
953 "%CONSTANTS%", "\n".join(code_object_defs[codeobj.name])
954 )
955 h_code = getattr(codeobj.code, f"{block}_h_file")
956 writer.write(f"code_objects/{block}_{codeobj.name}.cpp", cpp_code)
957 writer.write(f"code_objects/{block}_{codeobj.name}.h", h_code)
958
959 # Main code
960 code = codeobj.code.cpp_file
961 code = code.replace(
962 "%CONSTANTS%", "\n".join(code_object_defs[codeobj.name])
963 )
964
965 writer.write(f"code_objects/{codeobj.name}.cpp", code)
966 writer.write(f"code_objects/{codeobj.name}.h", codeobj.code.h_file)
967
968 def generate_network_source(self, writer, compiler):
969 maximum_run_time = self._maximum_run_time
970 if maximum_run_time is not None:
971 maximum_run_time = float(maximum_run_time)
972 network_tmp = self.code_object_class().templater.network(
973 None, None, maximum_run_time=maximum_run_time
974 )
975 writer.write("network.*", network_tmp)
976
977 def generate_synapses_classes_source(self, writer):
978 synapses_classes_tmp = self.code_object_class().templater.synapses_classes(
979 None, None
980 )
981 writer.write("synapses_classes.*", synapses_classes_tmp)
982
983 def generate_run_source(self, writer):
984 run_tmp = self.code_object_class().templater.run(
985 None,
986 None,
987 run_funcs=self.runfuncs,
988 code_objects=list(self.code_objects.values()),
989 user_headers=self.headers,
990 array_specs=self.arrays,
991 clocks=self.clocks,
992 )
993 writer.write("run.*", run_tmp)
994
995 def generate_makefile(
996 self, writer, compiler, compiler_flags, linker_flags, nb_threads, debug
997 ):
998 if compiler == "msvc":
999 if nb_threads > 1:
1000 openmp_flag = "/openmp"
1001 else:
1002 openmp_flag = ""
1003 if debug:
1004 compiler_debug_flags = "/DEBUG /DDEBUG"
1005 linker_debug_flags = "/DEBUG"
1006 else:
1007 compiler_debug_flags = ""
1008 linker_debug_flags = ""
1009 # Generate the visual studio makefile
1010 source_bases = [
1011 fname.replace(".cpp", "").replace(".c", "").replace("/", "\\")
1012 for fname in sorted(writer.source_files)
1013 ]
1014 win_makefile_tmp = self.code_object_class().templater.win_makefile(
1015 None,
1016 None,
1017 source_files=sorted(writer.source_files),
1018 source_bases=source_bases,
1019 compiler_flags=compiler_flags,
1020 compiler_debug_flags=compiler_debug_flags,
1021 linker_flags=linker_flags,
1022 linker_debug_flags=linker_debug_flags,
1023 openmp_flag=openmp_flag,
1024 )
1025 writer.write("win_makefile", win_makefile_tmp)
1026 # write the list of sources
1027 source_list = " ".join(source_bases)
1028 source_list_fname = os.path.join(self.project_dir, "sourcefiles.txt")
1029 if os.path.exists(source_list_fname):
1030 with open(source_list_fname) as f:
1031 if f.read() == source_list:
1032 return
1033 with open(source_list_fname, "w") as f:
1034 f.write(source_list)
1035 else:
1036 # Generate the makefile
1037 if os.name == "nt":
1038 rm_cmd = "del *.o /s\n\tdel main.exe $(DEPS)"
1039 else:
1040 rm_cmd = "rm $(OBJS) $(PROGRAM) $(DEPS)"
1041 if debug:
1042 compiler_debug_flags = "-g -DDEBUG"
1043 linker_debug_flags = "-g"
1044 else:
1045 compiler_debug_flags = ""
1046 linker_debug_flags = ""
1047 makefile_tmp = self.code_object_class().templater.makefile(
1048 None,
1049 None,
1050 source_files=" ".join(sorted(writer.source_files)),
1051 header_files=" ".join(sorted(writer.header_files)),
1052 compiler_flags=compiler_flags,
1053 compiler_debug_flags=compiler_debug_flags,
1054 linker_debug_flags=linker_debug_flags,
1055 linker_flags=linker_flags,
1056 rm_cmd=rm_cmd,
1057 )
1058 writer.write("makefile", makefile_tmp)
1059
1060 def copy_source_files(self, writer, directory):
1061 # Copy the brianlibdirectory
1062 brianlib_dir = os.path.join(
1063 os.path.split(inspect.getsourcefile(CPPStandaloneCodeObject))[0], "brianlib"
1064 )
1065 brianlib_files = copy_directory(
1066 brianlib_dir, os.path.join(directory, "brianlib")
1067 )
1068 for file in brianlib_files:
1069 if file.lower().endswith(".cpp"):
1070 writer.source_files.add(f"brianlib/{file}")
1071 elif file.lower().endswith(".h"):
1072 writer.header_files.add(f"brianlib/{file}")
1073
1074 # Copy the CSpikeQueue implementation
1075 shutil.copy2(
1076 os.path.join(
1077 os.path.split(inspect.getsourcefile(Synapses))[0], "spikequeue.h"
1078 ),
1079 os.path.join(directory, "brianlib", "spikequeue.h"),
1080 )
1081 shutil.copy2(
1082 os.path.join(
1083 os.path.split(inspect.getsourcefile(Synapses))[0], "spikequeue.cpp"
1084 ),
1085 os.path.join(directory, "brianlib", "spikequeue.cpp"),
1086 )
1087 shutil.copy2(
1088 os.path.join(
1089 os.path.split(inspect.getsourcefile(Synapses))[0], "stdint_compat.h"
1090 ),
1091 os.path.join(directory, "brianlib", "stdint_compat.h"),
1092 )
1093
1094 def _insert_func_namespace(self, func, code_object, namespace):
1095 impl = func.implementations[self.code_object_class()]
1096 func_namespace = impl.get_namespace(code_object.owner)
1097 if func_namespace is not None:
1098 namespace.update(func_namespace)
1099 if impl.dependencies is not None:
1100 for dep in impl.dependencies.values():
1101 self._insert_func_namespace(dep, code_object, namespace)
1102
1103 def write_static_arrays(self, directory):
1104 # Write Function namespaces as static arrays
1105 for code_object in self.code_objects.values():
1106 for var in code_object.variables.values():
1107 if isinstance(var, Function):
1108 self._insert_func_namespace(var, code_object, self.static_arrays)
1109
1110 logger.diagnostic(f"static arrays: {str(sorted(self.static_arrays.keys()))}")
1111
1112 static_array_specs = []
1113 for name, arr in sorted(self.static_arrays.items()):
1114 arr.tofile(os.path.join(directory, "static_arrays", name))
1115 static_array_specs.append((name, c_data_type(arr.dtype), arr.size, name))
1116 self.static_array_specs = static_array_specs
1117
1118 def compile_source(self, directory, compiler, debug, clean):
1119 with in_directory(directory):
1120 if compiler == "msvc":
1121 msvc_env, vcvars_cmd = get_msvc_env()
1122 make_cmd = "nmake /f win_makefile"
1123 make_args = " ".join(
1124 prefs.devices.cpp_standalone.extra_make_args_windows
1125 )
1126 if os.path.exists("winmake.log"):
1127 os.remove("winmake.log")
1128 if vcvars_cmd:
1129 with open("winmake.log", "w") as f:
1130 f.write(f"{vcvars_cmd}\n")
1131 else:
1132 with open("winmake.log", "w") as f:
1133 f.write("MSVC environment: \n")
1134 for key, value in msvc_env.items():
1135 f.write(f"{key}={value}\n")
1136 with std_silent(debug):
1137 if vcvars_cmd:
1138 if clean:
1139 start_time = time.time()
1140 os.system(
1141 f"{vcvars_cmd} >>winmake.log 2>&1 && {make_cmd} clean >"
1142 " NUL 2>&1"
1143 )
1144 self.timers["compile"]["clean"] = time.time() - start_time
1145 start_time = time.time()
1146 x = os.system(
1147 f"{vcvars_cmd} >>winmake.log 2>&1 &&"
1148 f" {make_cmd} {make_args}>>winmake.log 2>&1"
1149 )
1150 self.timers["compile"]["make"] = time.time() - start_time
1151 else:
1152 os.environ.update(msvc_env)
1153 if clean:
1154 start_time = time.time()
1155 os.system(f"{make_cmd} clean > NUL 2>&1")
1156 self.timers["compile"]["clean"] = time.time() - start_time
1157 start_time = time.time()
1158 x = os.system(f"{make_cmd} {make_args}>>winmake.log 2>&1")
1159 self.timers["compile"]["make"] = time.time() - start_time
1160
1161 if x != 0:
1162 error_message = f"Project compilation failed (error code: {x}), consider having a look at 'winmake.log'."
1163 if not clean:
1164 error_message += (
1165 " Consider running with "
1166 '"clean=True" to force a complete '
1167 "rebuild."
1168 )
1169 raise RuntimeError(error_message)
1170 else:
1171 with std_silent(debug):
1172 if clean:
1173 start_time = time.time()
1174 os.system("make clean >/dev/null 2>&1")
1175 self.timers["compile"]["clean"] = time.time() - start_time
1176 make_cmd = prefs.devices.cpp_standalone.make_cmd_unix
1177 make_args = " ".join(
1178 prefs.devices.cpp_standalone.extra_make_args_unix
1179 )
1180 start_time = time.time()
1181 x = os.system(f"{make_cmd} {make_args}")
1182 self.timers["compile"]["make"] = time.time() - start_time
1183 if x != 0:
1184 error_message = (
1185 "Project compilation failed (error code: %u)." % x
1186 )
1187 if not clean:
1188 error_message += (
1189 " Consider running with "
1190 '"clean=True" to force a complete '
1191 "rebuild."
1192 )
1193 raise RuntimeError(error_message)
1194
1195 def seed(self, seed=None):
1196 """
1197 Set the seed for the random number generator.
1198
1199 Parameters
1200 ----------
1201 seed : int, optional
1202 The seed value for the random number generator, or ``None`` (the
1203 default) to set a random seed.
1204 """
1205 self.main_queue.append(("seed", seed))
1206
1207 def run(
1208 self, directory=None, results_directory=None, with_output=True, run_args=None
1209 ):
1210 if directory is None:
1211 directory = self.project_dir
1212 if results_directory is None:
1213 results_directory = self.results_dir
1214 else:
1215 if os.path.isabs(results_directory):
1216 raise TypeError(
1217 "The 'results_directory' argument needs to be a relative path but"
1218 f" was '{results_directory}'."
1219 )
1220 # Translate path to absolute path which ends with /
1221 self.results_dir = os.path.join(
1222 os.path.abspath(os.path.join(directory, results_directory)), ""
1223 )
1224 ensure_directory(self.results_dir)
1225
1226 self.run_args_arrays.clear() # forget about arrays from previous runs
1227 if run_args is None:
1228 run_args = []
1229 elif isinstance(run_args, Mapping):
1230 list_rep = []
1231 for key, value in run_args.items():
1232 if isinstance(key, VariableView):
1233 (
1234 name,
1235 string_value,
1236 value_name,
1237 value_ar,
1238 ) = self._prepare_variableview_run_arg(key, value)
1239 elif isinstance(key, TimedArray):
1240 (
1241 name,
1242 string_value,
1243 value_name,
1244 value_ar,
1245 ) = self._prepare_timed_array_run_arg(key, value)
1246 else:
1247 raise TypeError(
1248 "The keys for 'run_args' need to be 'VariableView' objects,"
1249 " i.e. attributes of groups such as 'neurongroup.v', or a"
1250 f" 'TimedArray'. Key has type '{type(key)}' instead."
1251 )
1252 if value_name:
1253 fname = os.path.join(self.project_dir, "static_arrays", value_name)
1254 # Make sure processes trying to write the same file don't clash
1255 with FileLock(fname + ".lock"):
1256 if not os.path.exists(fname):
1257 value_ar.tofile(fname)
1258 self.run_args_arrays.append(value_name)
1259 list_rep.append(f"{name}={string_value}")
1260
1261 run_args = list_rep
1262
1263 # Invalidate array cache for all variables set on the command line
1264 for arg in run_args:
1265 s = arg.split("=")
1266 if len(s) == 2:
1267 for var in self.array_cache:
1268 try:
1269 if (
1270 hasattr(var.owner, "name")
1271 and var.owner.name + "." + var.name == s[0]
1272 ):
1273 self.array_cache[var] = None
1274 except ReferenceError:
1275 pass # Happens when ephemeral subgroups have been used to set a variable
1276 run_args = ["--results_dir", self.results_dir] + run_args
1277 # Invalidate the cached end time of the clock and network, to deal with stopped simulations
1278 for clock in self.clocks:
1279 self.array_cache[clock.variables["t"]] = None
1280
1281 with in_directory(directory):
1282 # Set environment variables
1283
1284 for key, value in itertools.chain(
1285 prefs["devices.cpp_standalone.run_environment_variables"].items(),
1286 self.run_environment_variables.items(),
1287 ):
1288 if key in os.environ and os.environ[key] != value:
1289 logger.info(
1290 f'Overwriting environment variable "{key}"',
1291 name_suffix="overwritten_env_var",
1292 once=True,
1293 )
1294 os.environ[key] = value
1295 if not with_output:
1296 stdout = open(os.path.join(self.results_dir, "stdout.txt"), "w")
1297 else:
1298 stdout = None
1299 if os.name == "nt":
1300 start_time = time.time()
1301 Network._globally_running = True
1302 x = subprocess.call(["main"] + run_args, stdout=stdout)
1303 self.timers["run_binary"] = time.time() - start_time
1304 Network._globally_running = False
1305 else:
1306 run_cmd = prefs.devices.cpp_standalone.run_cmd_unix
1307 if isinstance(run_cmd, str):
1308 run_cmd = [run_cmd]
1309 start_time = time.time()
1310 Network._globally_running = True
1311 x = subprocess.call(run_cmd + run_args, stdout=stdout)
1312 self.timers["run_binary"] = time.time() - start_time
1313 Network._globally_running = False
1314 if stdout is not None:
1315 stdout.close()
1316 if x:
1317 stdout_fname = os.path.join(self.results_dir, "stdout.txt")
1318 if os.path.exists(stdout_fname):
1319 with open(stdout_fname) as f:
1320 print(f.read())
1321 raise RuntimeError(
1322 "Project run failed (project directory:"
1323 f" {os.path.abspath(directory)})"
1324 )
1325 self.has_been_run = True
1326 run_info_fname = os.path.join(self.results_dir, "last_run_info.txt")
1327 if os.path.isfile(run_info_fname):
1328 with open(run_info_fname) as f:
1329 last_run_info = f.read()
1330 run_time, completed_fraction = last_run_info.split()
1331 self._last_run_time = float(run_time)
1332 self._last_run_completed_fraction = float(completed_fraction)
1333
1334 # Make sure that integration did not create NaN or very large values
1335 owners = [var.owner for var in self.arrays]
1336 # We don't want to check the same owner twice but var.owner is a
1337 # weakproxy which we can't put into a set. We therefore store the name
1338 # of all objects we already checked. Furthermore, under some specific
1339 # instances a variable might have been created whose owner no longer
1340 # exists (e.g. a `_sub_idx` variable for a subgroup) -- we ignore the
1341 # resulting reference error.
1342 already_checked = set()
1343 for owner in owners:
1344 try:
1345 if not hasattr(owner, "name") or owner.name in already_checked:
1346 continue
1347 if isinstance(owner, Group):
1348 owner._check_for_invalid_states()
1349 already_checked.add(owner.name)
1350 except ReferenceError:
1351 pass
1352
1353 def _prepare_variableview_run_arg(self, key, value):
1354 fail_for_dimension_mismatch(key.dim, value) # TODO: Give name of variable
1355 value_ar = np.asarray(value, dtype=key.dtype)
1356 if value_ar.ndim == 0 or value_ar.size == 1:
1357 # single value, give value directly on command line
1358 string_value = repr(value_ar.item())
1359 value_name = None
1360 else:
1361 if value_ar.ndim != 1 or (
1362 not key.variable.dynamic and value_ar.size != key.shape[0]
1363 ):
1364 raise TypeError(
1365 "Incorrect size for variable"
1366 f" '{key.group_name}.{key.name}'. Shape {key.shape} ≠"
1367 f" {value_ar.shape}."
1368 )
1369 value_name = (
1370 f"init_{key.group_name}_{key.name}_{md5(value_ar.data).hexdigest()}.dat"
1371 )
1372 string_value = os.path.join("static_arrays", value_name)
1373 name = f"{key.group_name}.{key.name}"
1374 return name, string_value, value_name, value_ar
1375
1376 def _prepare_timed_array_run_arg(self, key, value):
1377 fail_for_dimension_mismatch(key.dim, value) # TODO: Give name of variable
1378 value_ar = np.asarray(value, dtype=key.values.dtype)
1379 if value_ar.ndim == 0 or value_ar.size == 1:
1380 # single value, give value directly on command line
1381 string_value = repr(value_ar.item())
1382 value_name = None
1383 elif value_ar.shape == key.values.shape:
1384 value_name = f"init_{key.name}_values_{md5(value_ar.data).hexdigest()}.dat"
1385 string_value = os.path.join("static_arrays", value_name)
1386 else:
1387 raise TypeError(
1388 "Incorrect size for variable"
1389 f" '{key.name}.values'. Shape {key.values.shape} ≠"
1390 f" {value_ar.shape}."
1391 )
1392 name = f"{key.name}.values"
1393 return name, string_value, value_name, value_ar
1394
1395 def build(
1396 self,
1397 directory="output",
1398 results_directory="results",
1399 compile=True,
1400 run=True,
1401 debug=False,
1402 clean=False,
1403 with_output=True,
1404 additional_source_files=None,
1405 run_args=None,
1406 direct_call=True,
1407 **kwds,
1408 ):
1409 """
1410 Build the project
1411
1412 TODO: more details
1413
1414 Parameters
1415 ----------
1416 directory : str, optional
1417 The output directory to write the project to, any existing files
1418 will be overwritten. If the given directory name is ``None``, then
1419 a temporary directory will be used (used in the test suite to avoid
1420 problems when running several tests in parallel). Defaults to
1421 ``'output'``.
1422 compile : bool, optional
1423 Whether or not to attempt to compile the project. Defaults to
1424 ``True``.
1425 run : bool, optional
1426 Whether or not to attempt to run the built project if it
1427 successfully builds. Defaults to ``True``.
1428 debug : bool, optional
1429 Whether to compile in debug mode. Defaults to ``False``.
1430 with_output : bool, optional
1431 Whether or not to show the ``stdout`` of the built program when run.
1432 Output will be shown in case of compilation or runtime error.
1433 Defaults to ``True``.
1434 clean : bool, optional
1435 Whether or not to clean the project before building. Defaults to
1436 ``False``.
1437 additional_source_files : list of str, optional
1438 A list of additional ``.cpp`` files to include in the build.
1439 direct_call : bool, optional
1440 Whether this function was called directly. Is used internally to
1441 distinguish an automatic build due to the ``build_on_run`` option
1442 from a manual ``device.build`` call.
1443 """
1444 if self.build_on_run and direct_call:
1445 raise RuntimeError(
1446 "You used set_device with build_on_run=True "
1447 "(the default option), which will automatically "
1448 "build the simulation at the first encountered "
1449 "run call - do not call device.build manually "
1450 "in this case. If you want to call it manually, "
1451 "e.g. because you have multiple run calls, use "
1452 "set_device with build_on_run=False."
1453 )
1454 if self.has_been_run:
1455 raise RuntimeError(
1456 "The network has already been built and run "
1457 "before. To build several simulations in "
1458 'the same script, call "device.reinit()" '
1459 'and "device.activate()". Note that you '
1460 "will have to set build options (e.g. the "
1461 "directory) and defaultclock.dt again."
1462 )
1463 renames = {
1464 "project_dir": "directory",
1465 "compile_project": "compile",
1466 "run_project": "run",
1467 }
1468 if len(kwds):
1469 msg = ""
1470 for kwd in kwds:
1471 if kwd in renames:
1472 msg += (
1473 f"Keyword argument '{kwd}' has been renamed to "
1474 f"'{renames[kwd]}'. "
1475 )
1476 else:
1477 msg += f"Unknown keyword argument '{kwd}'. "
1478 raise TypeError(msg)
1479
1480 if additional_source_files is None:
1481 additional_source_files = []
1482 if run_args is None:
1483 run_args = []
1484 if directory is None:
1485 directory = tempfile.mkdtemp(prefix="brian_standalone_")
1486 self.project_dir = directory
1487 ensure_directory(directory)
1488 if os.path.isabs(results_directory):
1489 raise TypeError(
1490 "The 'results_directory' argument needs to be a relative path but was "
1491 f"'{results_directory}'."
1492 )
1493 # Translate path to absolute path which ends with /
1494 self.results_dir = os.path.join(
1495 os.path.abspath(os.path.join(directory, results_directory)), ""
1496 )
1497
1498 # Determine compiler flags and directories
1499 compiler, default_extra_compile_args = get_compiler_and_args()
1500 extra_compile_args = self.extra_compile_args + default_extra_compile_args
1501 extra_link_args = self.extra_link_args + prefs["codegen.cpp.extra_link_args"]
1502
1503 codeobj_define_macros = [
1504 macro
1505 for codeobj in self.code_objects.values()
1506 for macro in codeobj.compiler_kwds.get("define_macros", [])
1507 ]
1508 define_macros = (
1509 self.define_macros
1510 + prefs["codegen.cpp.define_macros"]
1511 + codeobj_define_macros
1512 )
1513
1514 codeobj_include_dirs = [
1515 include_dir
1516 for codeobj in self.code_objects.values()
1517 for include_dir in codeobj.compiler_kwds.get("include_dirs", [])
1518 ]
1519 include_dirs = (
1520 self.include_dirs + prefs["codegen.cpp.include_dirs"] + codeobj_include_dirs
1521 )
1522
1523 codeobj_library_dirs = [
1524 library_dir
1525 for codeobj in self.code_objects.values()
1526 for library_dir in codeobj.compiler_kwds.get("library_dirs", [])
1527 ]
1528 library_dirs = (
1529 self.library_dirs + prefs["codegen.cpp.library_dirs"] + codeobj_library_dirs
1530 )
1531
1532 codeobj_runtime_dirs = [
1533 runtime_dir
1534 for codeobj in self.code_objects.values()
1535 for runtime_dir in codeobj.compiler_kwds.get("runtime_library_dirs", [])
1536 ]
1537 runtime_library_dirs = (
1538 self.runtime_library_dirs
1539 + prefs["codegen.cpp.runtime_library_dirs"]
1540 + codeobj_runtime_dirs
1541 )
1542
1543 codeobj_libraries = [
1544 library
1545 for codeobj in self.code_objects.values()
1546 for library in codeobj.compiler_kwds.get("libraries", [])
1547 ]
1548 libraries = self.libraries + prefs["codegen.cpp.libraries"] + codeobj_libraries
1549
1550 compiler_obj = ccompiler.new_compiler(compiler=compiler)
1551
1552 # Distutils does not use the shell, so it does not need to quote filenames/paths
1553 # Since we include the compiler flags in the makefile, we need to quote them
1554 include_dirs = [f'"{include_dir}"' for include_dir in include_dirs]
1555 library_dirs = [f'"{library_dir}"' for library_dir in library_dirs]
1556 runtime_library_dirs = [
1557 f'"{runtime_dir}"' for runtime_dir in runtime_library_dirs
1558 ]
1559
1560 compiler_flags = (
1561 ccompiler.gen_preprocess_options(define_macros, include_dirs)
1562 + extra_compile_args
1563 )
1564
1565 linker_flags = (
1566 ccompiler.gen_lib_options(
1567 compiler_obj,
1568 library_dirs=library_dirs,
1569 runtime_library_dirs=runtime_library_dirs,
1570 libraries=libraries,
1571 )
1572 + extra_link_args
1573 )
1574
1575 codeobj_source_files = [
1576 source_file
1577 for codeobj in self.code_objects.values()
1578 for source_file in codeobj.compiler_kwds.get("sources", [])
1579 ]
1580 additional_source_files += codeobj_source_files
1581
1582 for d in ["code_objects", "results", "static_arrays"]:
1583 ensure_directory(os.path.join(directory, d))
1584
1585 self.writer = CPPWriter(directory)
1586 # Compile the spike queue together with the other source files
1587 self.writer.source_files.add("brianlib/spikequeue.cpp")
1588 self.writer.header_files.add("brianlib/spikequeue.h")
1589 # Get the number of threads if specified in an openmp context
1590 nb_threads = prefs.devices.cpp_standalone.openmp_threads
1591 # If the number is negative, we need to throw an error
1592 if nb_threads < 0:
1593 raise ValueError("The number of OpenMP threads can not be negative !")
1594
1595 logger.diagnostic(
1596 "Writing C++ standalone project to directory "
1597 f"'{os.path.normpath(directory)}'."
1598 )
1599
1600 self.check_openmp_compatible(nb_threads)
1601
1602 self.write_static_arrays(directory)
1603
1604 # Check that all names are globally unique
1605 names = [obj.name for net in self.networks for obj in net.sorted_objects]
1606 non_unique_names = [name for name, count in Counter(names).items() if count > 1]
1607 if len(non_unique_names):
1608 formatted_names = ", ".join(f"'{name}'" for name in non_unique_names)
1609 raise ValueError(
1610 "All objects need to have unique names in "
1611 "standalone mode, the following name(s) were used "
1612 f"more than once: {formatted_names}"
1613 )
1614
1615 self.generate_objects_source(
1616 self.writer,
1617 self.arange_arrays,
1618 self.synapses,
1619 self.static_array_specs,
1620 self.networks,
1621 self.timed_arrays,
1622 )
1623 self.generate_main_source(self.writer)
1624 self.generate_codeobj_source(self.writer)
1625 self.generate_network_source(self.writer, compiler)
1626 self.generate_synapses_classes_source(self.writer)
1627 self.generate_run_source(self.writer)
1628 self.copy_source_files(self.writer, directory)
1629
1630 self.writer.source_files.update(additional_source_files)
1631
1632 self.generate_makefile(
1633 self.writer,
1634 compiler,
1635 compiler_flags=" ".join(compiler_flags),
1636 linker_flags=" ".join(linker_flags),
1637 nb_threads=nb_threads,
1638 debug=debug,
1639 )
1640
1641 if compile:
1642 self.compile_source(directory, compiler, debug, clean)
1643 if run:
1644 self.run(directory, results_directory, with_output, run_args)
1645 time_measurements = {
1646 "'make clean'": self.timers["compile"]["clean"],
1647 "'make'": self.timers["compile"]["make"],
1648 "running 'main'": self.timers["run_binary"],
1649 }
1650 logged_times = [
1651 f"{task}: {measurement:.2f}s"
1652 for task, measurement in time_measurements.items()
1653 if measurement is not None
1654 ]
1655 logger.debug(f"Time measurements: {', '.join(logged_times)}")
1656
1657 def delete(self, code=True, data=True, run_args=True, directory=True, force=False):
1658 if self.project_dir is None:
1659 return # Nothing to delete
1660
1661 if directory and not all([code, data, run_args]):
1662 raise ValueError(
1663 "When deleting the directory, code and data will"
1664 "be deleted as well. Set the corresponding "
1665 "parameters to True."
1666 )
1667
1668 fnames = []
1669
1670 # Delete data
1671 if data:
1672 results_dir = self.results_dir
1673 logger.debug(f"Deleting data files in '{results_dir}'")
1674 fnames.append(os.path.join(results_dir, "random_generator_state"))
1675 fnames.append(os.path.join(results_dir, "last_run_info.txt"))
1676 if self.profiled_codeobjects:
1677 fnames.append(os.path.join(results_dir, "profiling_info.txt"))
1678 for var in self.arrays:
1679 fnames.append(os.path.join(results_dir, self.get_array_filename(var)))
1680 for syn in self.synapses:
1681 for pathway in syn._pathways:
1682 fnames.append(os.path.join(results_dir, f"{pathway.name}_queue"))
1683
1684 # Delete code
1685 if code:
1686 logger.debug(f"Deleting code files in '{self.project_dir}'")
1687 if sys.platform == "win32":
1688 fnames.extend(
1689 [
1690 "sourcefiles.txt",
1691 "win_makefile",
1692 "main.exe",
1693 "main.ilk",
1694 "main.pdb",
1695 "winmake.log",
1696 ]
1697 )
1698 else:
1699 fnames.extend(["make.deps", "makefile", "main"])
1700
1701 fnames.extend(
1702 [
1703 os.path.join("brianlib", "stdint_compat.h"),
1704 ]
1705 )
1706 fnames.extend(self.writer.header_files)
1707
1708 for source_file in self.writer.source_files:
1709 fnames.append(source_file)
1710 base_name, _ = os.path.splitext(source_file)
1711 if sys.platform == "win32":
1712 fnames.append(f"{base_name}.obj")
1713 else:
1714 fnames.append(f"{base_name}.o")
1715
1716 for static_array_name in self.static_arrays:
1717 fnames.append(os.path.join("static_arrays", static_array_name))
1718
1719 if run_args:
1720 for fname in self.run_args_arrays:
1721 fnames.append(os.path.join("static_arrays", fname))
1722
1723 for fname in fnames:
1724 full_fname = os.path.join(self.project_dir, fname)
1725 try:
1726 os.remove(full_fname)
1727 except OSError as ex:
1728 logger.warn(f'File "{full_fname}" could not be deleted: {str(ex)}')
1729
1730 # Delete directories
1731
1732 if directory:
1733 directories = [
1734 "brianlib",
1735 "code_objects",
1736 "results",
1737 "static_arrays",
1738 "",
1739 ]
1740 full_directories = [
1741 os.path.join(self.project_dir, directory) for directory in directories
1742 ]
1743 for full_directory in full_directories:
1744 try:
1745 os.rmdir(full_directory)
1746 except OSError:
1747 if not os.path.exists(full_directory):
1748 continue
1749
1750 # The directory is not empty:
1751 if force:
1752 logger.debug(
1753 'Directory "{}" is not empty, but '
1754 "deleting it due to the use of the force "
1755 "option."
1756 )
1757 shutil.rmtree(full_directory)
1758 else:
1759 # We only give a warning if there is a file or a
1760 # directory we do not know about. We do not want to e.g.
1761 # complain about an unknown file in the results
1762 # directory and then again complain about the results
1763 # directory when deleting the main directory
1764 still_present = [
1765 name
1766 for name in os.listdir(full_directory)
1767 if os.path.isfile(name)
1768 or os.path.join(full_directory, name)
1769 not in full_directories
1770 ]
1771 if len(still_present):
1772 still_present = ", ".join(
1773 f'"{name}"' for name in still_present
1774 )
1775 logger.warn(
1776 f"Not deleting the '{full_directory}' directory, "
1777 "because it contains files/directories "
1778 f"not added by Brian: {still_present}",
1779 name_suffix="delete_skips_directory",
1780 )
1781
1782 def network_run(
1783 self,
1784 net,
1785 duration,
1786 report=None,
1787 report_period=10 * second,
1788 namespace=None,
1789 profile=None,
1790 level=0,
1791 **kwds,
1792 ):
1793 if duration < 0:
1794 raise ValueError(
1795 f"Function 'run' expected a non-negative duration but got '{duration}'"
1796 )
1797
1798 self.networks.add(net)
1799 if kwds:
1800 logger.warn(
1801 "Unsupported keyword argument(s) provided for run: %s"
1802 % ", ".join(kwds.keys())
1803 )
1804 # We store this as an instance variable for later access by the
1805 # `code_object` method
1806 self.enable_profiling = profile
1807
1808 # Allow setting `profile` in the `set_device` call (used e.g. in brian2cuda
1809 # SpeedTest configurations)
1810 if profile is None:
1811 self.enable_profiling = self.build_options.get("profile", False)
1812
1813 all_objects = net.sorted_objects
1814 net._clocks = {obj.clock for obj in all_objects}
1815 t_end = net.t + duration
1816 for clock in net._clocks:
1817 clock.set_interval(net.t, t_end)
1818
1819 # Get the local namespace
1820 if namespace is None:
1821 namespace = get_local_namespace(level=level + 2)
1822
1823 net.before_run(namespace)
1824 self.synapses |= {s for s in net.objects if isinstance(s, Synapses)}
1825 self.clocks.update(net._clocks)
1826 net.t_ = float(t_end)
1827
1828 # TODO: remove this horrible hack
1829 for clock in self.clocks:
1830 if clock.name == "clock":
1831 clock._name = "_clock"
1832
1833 # Extract all the CodeObjects
1834 # Note that since we ran the Network object, these CodeObjects will be sorted into the right
1835 # running order, assuming that there is only one clock
1836 code_objects = []
1837 for obj in all_objects:
1838 if obj.active:
1839 for codeobj in obj._code_objects:
1840 code_objects.append((obj.clock, codeobj))
1841
1842 # Code for a progress reporting function
1843 standard_code = """
1844 std::string _format_time(float time_in_s)
1845 {
1846 float divisors[] = {24*60*60, 60*60, 60, 1};
1847 char letters[] = {'d', 'h', 'm', 's'};
1848 float remaining = time_in_s;
1849 std::string text = "";
1850 int time_to_represent;
1851 for (int i =0; i < sizeof(divisors)/sizeof(float); i++)
1852 {
1853 time_to_represent = int(remaining / divisors[i]);
1854 remaining -= time_to_represent * divisors[i];
1855 if (time_to_represent > 0 || text.length())
1856 {
1857 if(text.length() > 0)
1858 {
1859 text += " ";
1860 }
1861 text += (std::to_string(time_to_represent)+letters[i]);
1862 }
1863 }
1864 //less than one second
1865 if(text.length() == 0)
1866 {
1867 text = "< 1s";
1868 }
1869 return text;
1870 }
1871 void report_progress(const double elapsed, const double completed, const double start, const double duration)
1872 {
1873 if (completed == 0.0)
1874 {
1875 %STREAMNAME% << "Starting simulation at t=" << start << " s for duration " << duration << " s";
1876 } else
1877 {
1878 %STREAMNAME% << completed*duration << " s (" << (int)(completed*100.) << "%) simulated in " << _format_time(elapsed);
1879 if (completed < 1.0)
1880 {
1881 const int remaining = (int)((1-completed)/completed*elapsed+0.5);
1882 %STREAMNAME% << ", estimated " << _format_time(remaining) << " remaining.";
1883 }
1884 }
1885
1886 %STREAMNAME% << std::endl << std::flush;
1887 }
1888 """
1889 if report is None:
1890 report_func = ""
1891 elif report == "text" or report == "stdout":
1892 report_func = standard_code.replace("%STREAMNAME%", "std::cout")
1893 elif report == "stderr":
1894 report_func = standard_code.replace("%STREAMNAME%", "std::cerr")
1895 elif isinstance(report, str):
1896 report_func = """
1897 void report_progress(const double elapsed, const double completed, const double start, const double duration)
1898 {
1899 %REPORT%
1900 }
1901 """.replace("%REPORT%", report)
1902 else:
1903 raise TypeError(
1904 "report argument has to be either 'text', "
1905 "'stdout', 'stderr', or the code for a report "
1906 "function"
1907 )
1908
1909 if report_func != "":
1910 if self.report_func != "" and report_func != self.report_func:
1911 raise NotImplementedError(
1912 "The C++ standalone device does not "
1913 "support multiple report functions, "
1914 "each run has to use the same (or "
1915 "none)."
1916 )
1917 self.report_func = report_func
1918
1919 if report is not None:
1920 report_call = "report_progress"
1921 else:
1922 report_call = "NULL"
1923
1924 # Generate the updaters
1925 run_lines = [f"{net.name}.clear();"]
1926 all_clocks = set()
1927 for clock, codeobj in code_objects:
1928 run_lines.append(f"{net.name}.add(&{clock.name}, _run_{codeobj.name});")
1929 all_clocks.add(clock)
1930
1931 # Under some rare circumstances (e.g. a NeuronGroup only defining a
1932 # subexpression that is used by other groups (via linking, or recorded
1933 # by a StateMonitor) *and* not calculating anything itself *and* using a
1934 # different clock than all other objects) a clock that is not used by
1935 # any code object should nevertheless advance during the run. We include
1936 # such clocks without a code function in the network.
1937 for clock in net._clocks:
1938 if clock not in all_clocks:
1939 run_lines.append(f"{net.name}.add(&{clock.name}, NULL);")
1940
1941 run_lines.extend(self.code_lines["before_network_run"])
1942 if not self.run_args_applied:
1943 run_lines.append("set_from_command_line(args);")
1944 self.run_args_applied = True
1945 run_lines.append(
1946 f"{net.name}.run({float(duration)!r}, {report_call},"
1947 f" {float(report_period)!r});"
1948 )
1949 run_lines.extend(self.code_lines["after_network_run"])
1950 self.main_queue.append(("run_network", (net, run_lines)))
1951
1952 net.after_run()
1953
1954 # Manually set the cache for the clocks, simulation scripts might
1955 # want to access the time (which has been set in code and is therefore
1956 # not accessible by the normal means until the code has been built and
1957 # run)
1958 for clock in net._clocks:
1959 self.array_cache[clock.variables["timestep"]] = np.array([clock._i_end])
1960 # FIXME: Not ideal to condition this on the type of clock
1961 if isinstance(clock, EventClock):
1962 self.array_cache[clock.variables["t"]] = np.array(
1963 [clock._times[clock._i_end]]
1964 )
1965 else:
1966 self.array_cache[clock.variables["t"]] = np.array(
1967 [clock._i_end * clock.dt_]
1968 )
1969
1970 if self.build_on_run:
1971 if self.has_been_run:
1972 raise RuntimeError(
1973 "The network has already been built and run "
1974 "before. Use set_device with "
1975 "build_on_run=False and an explicit "
1976 "device.build call to use multiple run "
1977 "statements with this device."
1978 )
1979 self.build(direct_call=False, **self.build_options)
1980
1981 def network_store(self, net, *args, **kwds):
1982 raise NotImplementedError(
1983 "The store/restore mechanism is not supported in the C++ standalone"
1984 )
1985
1986 def network_restore(self, net, *args, **kwds):
1987 raise NotImplementedError(
1988 "The store/restore mechanism is not supported in the C++ standalone"
1989 )
1990
1991 def network_get_profiling_info(self, net):
1992 fname = os.path.join(self.project_dir, "results", "profiling_info.txt")
1993 if not os.path.exists(fname):
1994 raise ValueError(
1995 "No profiling info collected (did you run with 'profile=True'?)"
1996 )
1997 net._profiling_info = []
1998 with open(fname) as f:
1999 for line in f:
2000 (key, val) = line.split()
2001 net._profiling_info.append((key, float(val) * second))
2002 return sorted(net._profiling_info, key=lambda item: item[1], reverse=True)
2003
2004 def run_function(self, name, include_in_parent=True):
2005 """
2006 Context manager to divert code into a function
2007
2008 Code that happens within the scope of this context manager will go into the named function.
2009
2010 Parameters
2011 ----------
2012 name : str
2013 The name of the function to divert code into.
2014 include_in_parent : bool
2015 Whether or not to include a call to the newly defined function in the parent context.
2016 """
2017 return RunFunctionContext(name, include_in_parent)
2018
2019
2020 class RunFunctionContext:
2021 def __init__(self, name, include_in_parent):
2022 self.name = name
2023 self.include_in_parent = include_in_parent
2024
2025 def __enter__(self):
2026 cpp_standalone_device.main_queue.append(
2027 ("start_run_func", (self.name, self.include_in_parent))
2028 )
2029
2030 def __exit__(self, type, value, traceback):
2031 cpp_standalone_device.main_queue.append(
2032 ("end_run_func", (self.name, self.include_in_parent))
2033 )
2034
2035
2036 cpp_standalone_device = CPPStandaloneDevice()
2037 all_devices["cpp_standalone"] = cpp_standalone_device