Debian Codegraph @

brian2/codegen/generators/GSL_generator.py

raw
1 """
2 GSLCodeGenerators for code that uses the ODE solver provided by the GNU Scientific Library (GSL)
3 """
4
5 import os
6 import re
7
8 import numpy as np
9
10 from brian2.codegen.generators import c_data_type
11 from brian2.codegen.permutation_analysis import (
12 OrderDependenceError,
13 check_for_order_independence,
14 )
15 from brian2.codegen.translation import make_statements
16 from brian2.core.functions import Function
17 from brian2.core.preferences import BrianPreference, PreferenceError, prefs
18 from brian2.core.variables import ArrayVariable, AuxiliaryVariable, Constant
19 from brian2.parsing.statements import parse_statement
20 from brian2.units.fundamentalunits import fail_for_dimension_mismatch
21 from brian2.utils.logger import get_logger
22 from brian2.utils.stringtools import get_identifiers, word_substitute
23
24 __all__ = ["GSLCodeGenerator", "GSLCPPCodeGenerator", "GSLCythonCodeGenerator"]
25
26
27 logger = get_logger(__name__)
28
29
30 def valid_gsl_dir(val):
31 """
32 Validate given string to be path containing required GSL files.
33 """
34 if val is None:
35 return True
36 if not isinstance(val, str):
37 raise PreferenceError(
38 f"Illegal value for GSL directory: {str(val)}, has to be str"
39 )
40 if not os.path.isdir(val):
41 raise PreferenceError(
42 f"Illegal value for GSL directory: {val}, has to be existing directory"
43 )
44 if any(
45 not os.path.isfile(os.path.join(val, "gsl", filename))
46 for filename in ["gsl_odeiv2.h", "gsl_errno.h", "gsl_matrix.h"]
47 ):
48 raise PreferenceError(
49 f"Illegal value for GSL directory: '{val}', "
50 "has to contain gsl_odeiv2.h, gsl_errno.h "
51 "and gsl_matrix.h"
52 )
53 return True
54
55
56 prefs.register_preferences(
57 "GSL",
58 "Directory containing GSL code",
59 directory=BrianPreference(
60 validator=valid_gsl_dir,
61 docs=(
62 "Set path to directory containing GSL header files (gsl_odeiv2.h etc.)"
63 "\nIf this directory is already in Python's include (e.g. because of "
64 "conda installation), this path can be set to None."
65 ),
66 default=None,
67 ),
68 )
69
70
71 class GSLCodeGenerator:
72 """
73 GSL code generator.
74
75 Notes
76 -----
77 Approach is to first let the already existing code generator for a target
78 language do the bulk of the translating from abstract_code to actual code.
79 This generated code is slightly adapted to render it GSL compatible.
80 The most critical part here is that the vector_code that is normally
81 contained in a loop in the ```main()``` is moved to the function ```_GSL_func```
82 that is sent to the GSL integrator. The variables used in the vector_code are
83 added to a struct named ```dataholder``` and their values are set from the
84 Brian namespace just before the scalar code block.
85 """
86
87 def __init__(
88 self,
89 variables,
90 variable_indices,
91 owner,
92 iterate_all,
93 codeobj_class,
94 name,
95 template_name,
96 override_conditional_write=None,
97 allows_scalar_write=False,
98 ):
99 self.generator = codeobj_class.original_generator_class(
100 variables,
101 variable_indices,
102 owner,
103 iterate_all,
104 codeobj_class,
105 name,
106 template_name,
107 override_conditional_write,
108 allows_scalar_write,
109 )
110 self.method_options = dict(owner.state_updater.method_options)
111 self.integrator = owner.state_updater.integrator
112 # default timestep to start with is the timestep of the NeuronGroup itself
113 self.method_options["dt_start"] = owner.dt.variable.get_value()[0]
114 self.variable_flags = owner.state_updater._gsl_variable_flags
115
116 def __getattr__(self, item):
117 return getattr(self.generator, item)
118
119 # A series of functions that should be overridden by child class:
120 def c_data_type(self, dtype):
121 """
122 Get string version of object dtype that is attached to Brian variables. c
123 pp_generator already has this function, but the Cython generator does not,
124 but we need it for GSL code generation.
125 """
126 return NotImplementedError
127
128 def initialize_array(self, varname, values):
129 """
130 Initialize a static array with given floating point values. E.g. in C++,
131 when called with arguments ``array`` and ``[1.0, 3.0, 2.0]``, this
132 method should return ``double array[] = {1.0, 3.0, 2.0}``.
133
134 Parameters
135 ----------
136 varname : str
137 The name of the array variable that should be initialized
138 values : list of float
139 The values that should be assigned to the array
140
141 Returns
142 -------
143 code : str
144 One or more lines of array initialization code.
145 """
146 raise NotImplementedError
147
148 def var_init_lhs(self, var, type):
149 """
150 Get string version of the left hand side of an initializing expression
151
152 Parameters
153 ----------
154 var : str
155 type : str
156
157 Returns
158 -------
159 code : str
160 For cpp returns type + var, while for cython just var
161 """
162 raise NotImplementedError
163
164 def unpack_namespace_single(self, var_obj, in_vector, in_scalar):
165 """
166 Writes the code necessary to pull single variable out of the Brian
167 namespace into the generated code.
168
169 The code created is significantly different between cpp and cython,
170 so I decided to not make this function general
171 over all target languages (i.e. in contrast to most other functions
172 that only have syntactical differences)
173 """
174 raise NotImplementedError
175
176 # GSL functions that are the same for all target languages:
177 def find_function_names(self):
178 """
179 Return a list of used function names in the self.variables dictionary
180
181 Functions need to be ignored in the GSL translation process, because the
182 brian generator already sufficiently
183 dealt with them. However, the brian generator also removes them from the
184 variables dict, so there is no
185 way to check whether an identifier is a function after the brian
186 translation process. This function is called
187 before this translation process and the list of function names is stored
188 to be used in the GSL translation.
189
190 Returns
191 -------
192 function_names : list
193 list of strings that are function names used in the code
194 """
195 variables = self.variables
196 return [
197 var for var, var_obj in variables.items() if isinstance(var_obj, Function)
198 ]
199
200 def is_cpp_standalone(self):
201 """
202 Check whether we're running with cpp_standalone.
203
204 Test if `get_device()` is instance `CPPStandaloneDevice`.
205
206 Returns
207 -------
208 is_cpp_standalone : bool
209 whether currently using cpp_standalone device
210
211 See Also
212 --------
213 is_constant_and_cpp_standalone : uses the returned value
214 """
215 # imports here to avoid circular imports
216 from brian2.devices.cpp_standalone.device import CPPStandaloneDevice
217 from brian2.devices.device import get_device
218
219 device = get_device()
220 return isinstance(device, CPPStandaloneDevice)
221
222 def is_constant_and_cpp_standalone(self, var_obj):
223 """Check whether self.cpp_standalone and variable is Constant.
224
225 This check is needed because in the case of using the cpp_standalone device we do not
226 want to apply our GSL variable conversion (var --> _GSL_dataholder.var), because the cpp_standalone
227 code generation process involves replacing constants with their actual value ('freezing').
228 This results in code that looks like (if for example var = 1.2): _GSL_dataholder.1.2 = 1.2 and _GSL_dataholder->1.2.
229 To prevent repetitive calls to get_device() etc. the outcome of is_cpp_standalone is saved.
230
231 Parameters
232 ----------
233 var_obj : `Variable`
234 instance of brian Variable class describing the variable
235
236 Returns
237 -------
238 is_cpp_standalone : bool
239 whether the used device is cpp_standalone and the given variable is an instance of Constant
240 """
241 if not hasattr(self, "cpp_standalone"):
242 self.cpp_standalone = self.is_cpp_standalone()
243 return isinstance(var_obj, Constant) and self.cpp_standalone
244
245 def find_differential_variables(self, code):
246 """
247 Find the variables that were tagged _gsl_{var}_f{ind} and return var, ind pairs.
248
249 `GSLStateUpdater` tagged differential variables and here we extract the information given in these tags.
250
251 Parameters
252 ----------
253 code : list of strings
254 A list of strings containing gsl tagged variables
255
256 Returns
257 -------
258 diff_vars : dict
259 A dictionary with variable names as keys and differential equation index as value
260 """
261 diff_vars = {}
262 for expr_set in code:
263 for expr in expr_set.split("\n"):
264 expr = expr.strip(" ")
265 try:
266 lhs, op, rhs, comment = parse_statement(expr)
267 except ValueError:
268 pass
269 m = re.search("_gsl_(.+?)_f([0-9]*)$", lhs)
270 if m:
271 diff_vars[m.group(1)] = m.group(2)
272 return diff_vars
273
274 def diff_var_to_replace(self, diff_vars):
275 """
276 Add differential variable-related strings that need to be replaced to go
277 from normal brian to GSL code
278
279 From the code generated by Brian's 'normal' generators (cpp_generator or
280 cython_generator a few bits of text need to be replaced to get GSL
281 compatible code. The bits of text related to differential equation
282 variables are put in the replacer dictionary in this function.
283
284 Parameters
285 ----------
286 diff_vars : dict
287 dictionary with variables as keys and differential equation index as value
288
289 Returns
290 -------
291 to_replace : dict
292 dictionary with strings that need to be replaced as keys and the
293 strings that will replace them as values
294 """
295 variables = self.variables
296 to_replace = {}
297 for var, diff_num in list(diff_vars.items()):
298 to_replace.update(self.var_replace_diff_var_lhs(var, diff_num))
299 var_obj = variables[var]
300 array_name = self.generator.get_array_name(var_obj, access_data=True)
301 idx_name = "_idx" # TODO: could be dynamic?
302 replace_what = f"{var} = {array_name}[{idx_name}]"
303 replace_with = f"{var} = _GSL_y[{diff_num}]"
304 to_replace[replace_what] = replace_with
305 return to_replace
306
307 def get_dimension_code(self, diff_num):
308 """
309 Generate code for function that sets the dimension of the ODE system.
310
311 GSL needs to know how many differential variables there are in the
312 ODE system. Since the current approach is to have the code in the vector
313 loop the same for all simulations, this dimension is set by an external
314 function. The code for this set_dimension functon is written here.
315 It is assumed the code will be the same for each target language with the
316 exception of some syntactical differences
317
318 Parameters
319 ----------
320 diff_num : int
321 Number of differential variables that describe the ODE system
322
323 Returns
324 -------
325 set_dimension_code : str
326 The code describing the target language function in a single string
327 """
328 code = ["\n{start_declare}int set_dimension(size_t * dimension){open_function}"]
329 code += ["\tdimension[0] = %d{end_statement}" % diff_num]
330 code += ["\treturn GSL_SUCCESS{end_statement}{end_function}"]
331 return ("\n").join(code).format(**self.syntax)
332
333 def yvector_code(self, diff_vars):
334 """
335 Generate code for function dealing with GSLs y vector.
336
337 The values of differential variables have to be transferred from
338 Brian's namespace to a vector that is given to GSL. The transferring
339 from Brian --> y and back from y --> Brian after integration happens in
340 separate functions. The code for these is written here.
341
342 Parameters
343 ----------
344 diff_vars : dictionary
345 Dictionary containing variable names as keys (str) and differential
346 variable index as value
347
348 Returns
349 -------
350 yvector_code : str
351 The code for the two functions (``_fill_y_vector`` and
352 ``_empty_y_vector``) as single string.
353 """
354 fill_y = [
355 "\n{start_declare}int _fill_y_vector(_dataholder *"
356 "_GSL_dataholder, double * _GSL_y, int _idx){open_function}"
357 ]
358 empty_y = [
359 "\n{start_declare}int _empty_y_vector(_dataholder * "
360 "_GSL_dataholder, double * _GSL_y, int _idx){"
361 "open_function}"
362 ]
363 for var, diff_num in list(diff_vars.items()):
364 diff_num = int(diff_num)
365 array_name = self.generator.get_array_name(
366 self.variables[var], access_data=True
367 )
368 fill_y += [
369 "\t_GSL_y[%d] = _GSL_dataholder{access_pointer}%s[_idx]{end_statement}"
370 % (diff_num, array_name)
371 ]
372 empty_y += [
373 "\t_GSL_dataholder{access_pointer}%s[_idx] = _GSL_y[%d]{end_statement}"
374 % (array_name, diff_num)
375 ]
376 fill_y += ["\treturn GSL_SUCCESS{end_statement}{end_function}"]
377 empty_y += ["\treturn GSL_SUCCESS{end_statement}{end_function}"]
378 return ("\n").join(fill_y + empty_y).format(**self.syntax)
379
380 def make_function_code(self, lines):
381 """
382 Add lines of GSL translated vector code to 'non-changing' _GSL_func code.
383
384 Adds nonchanging aspects of GSL _GSL_func code to lines of code
385 written somewhere else (`translate_vector_code`). Here these lines
386 are put between the non-changing parts of the code and the
387 target-language specific syntax is added.
388
389 Parameters
390 ----------
391 lines : str
392 Code containing GSL version of equations
393
394 Returns
395 -------
396 function_code : str
397 code describing ``_GSL_func`` that is sent to GSL integrator.
398 """
399 code = [
400 "\n{start_declare}int _GSL_func(double t, const double "
401 "_GSL_y[], double f[], void * params){open_function}"
402 "\n\t{start_declare}_dataholder * _GSL_dataholder = {open_cast}"
403 "_dataholder *{close_cast} params{end_statement}"
404 "\n\t{start_declare}int _idx = _GSL_dataholder{access_pointer}_idx"
405 "{end_statement}"
406 ]
407 code += [lines]
408 code += ["\treturn GSL_SUCCESS{end_statement}{end_function}"]
409 return ("\n").join(code).format(**self.syntax)
410
411 def write_dataholder_single(self, var_obj):
412 """
413 Return string declaring a single variable in the ``_dataholder`` struct.
414
415 Parameters
416 ----------
417 var_obj : `Variable`
418
419 Returns
420 -------
421 code : str
422 string describing this variable object as required for the ``_dataholder`` struct
423 (e.g. ``double* _array_neurongroup_v``)
424 """
425 dtype = self.c_data_type(var_obj.dtype)
426 if isinstance(var_obj, ArrayVariable):
427 pointer_name = self.get_array_name(var_obj, access_data=True)
428 try:
429 restrict = self.generator.restrict
430 except AttributeError:
431 restrict = ""
432 if var_obj.scalar or var_obj.size == 1:
433 restrict = ""
434 return f"{dtype}* {restrict} {pointer_name}{{end_statement}}"
435 else:
436 return f"{dtype} {var_obj.name}{{end_statement}}"
437
438 def write_dataholder(self, variables_in_vector):
439 """
440 Return string with full code for _dataholder struct.
441
442 Parameters
443 ----------
444 variables_in_vector : dict
445 dictionary containing variable name as key and `Variable` as value
446
447 Returns
448 -------
449 code : str
450 code for _dataholder struct
451 """
452 code = ["\n{start_declare}struct _dataholder{open_struct}"]
453 code += ["\tint _idx{end_statement}"]
454 for var, var_obj in list(variables_in_vector.items()):
455 if (
456 var == "t"
457 or "_gsl" in var
458 or self.is_constant_and_cpp_standalone(var_obj)
459 ):
460 continue
461 code += [f" {self.write_dataholder_single(var_obj)}"]
462 code += ["{end_struct}"]
463 return ("\n").join(code).format(**self.syntax)
464
465 def scale_array_code(self, diff_vars, method_options):
466 """
467 Return code for definition of ``_GSL_scale_array`` in generated code.
468
469 Parameters
470 ----------
471 diff_vars : dict
472 dictionary with variable name (str) as key and differential variable
473 index (int) as value
474 method_options : dict
475 dictionary containing integrator settings
476
477 Returns
478 -------
479 code : str
480 full code describing a function returning a array containing doubles
481 with the absolute errors for each differential variable (according
482 to their assigned index in the GSL StateUpdater)
483 """
484 # get scale values per variable from method_options
485 abs_per_var = method_options["absolute_error_per_variable"]
486 abs_default = method_options["absolute_error"]
487
488 if not isinstance(abs_default, float):
489 raise TypeError(
490 "The absolute_error key in method_options should be "
491 f"a float. Was type {type(abs_default)}"
492 )
493
494 if abs_per_var is None:
495 diff_scale = {var: float(abs_default) for var in list(diff_vars.keys())}
496 elif isinstance(abs_per_var, dict):
497 diff_scale = {}
498 for var, error in list(abs_per_var.items()):
499 # first do some checks on input
500 if var not in diff_vars:
501 if var not in self.variables:
502 raise KeyError(
503 "absolute_error specified for variable that "
504 f"does not exist: {var}"
505 )
506 else:
507 raise KeyError(
508 "absolute_error specified for variable that is "
509 f"not being integrated: {var}"
510 )
511 fail_for_dimension_mismatch(
512 error,
513 self.variables[var],
514 "Unit of absolute_error_per_variable "
515 f"for variable {var} does not match "
516 "unit of variable itself",
517 )
518 # if all these are passed we can add the value for error in base units
519 diff_scale[var] = float(error)
520 # set the variables that are not mentioned to default value
521 for var in list(diff_vars.keys()):
522 if var not in abs_per_var:
523 diff_scale[var] = float(abs_default)
524 else:
525 raise TypeError(
526 "The absolute_error_per_variable key in method_options "
527 "should either be None or a dictionary "
528 "containing the error for each individual state variable. "
529 f"Was type {type(abs_per_var)}"
530 )
531 # write code
532 return self.initialize_array(
533 "_GSL_scale_array", [diff_scale[var] for var in sorted(diff_vars)]
534 )
535
536 def find_undefined_variables(self, statements):
537 r"""
538 Find identifiers that are not in ``self.variables`` dictionary.
539
540 Brian does not save the ``_lio_`` variables it uses anywhere. This is
541 problematic for our GSL implementation because we save the lio variables
542 in the ``_dataholder`` struct (for which we need the datatype of the
543 variables). This function adds the left hand side variables that are
544 used in the vector code to the variable dictionary as
545 `AuxiliaryVariable`\ s (all we need later is the datatype).
546
547 Parameters
548 ----------
549 statements : list
550 list of statement objects (need to have the dtype attribute)
551
552 Notes
553 -----
554 I keep ``self.variables`` and ``other_variables`` separate so I can
555 distinguish what variables are in the Brian namespace and which ones are
556 defined in the code itself.
557 """
558 variables = self.variables
559 other_variables = {}
560 for statement in statements:
561 var = statement.var
562 if var not in variables:
563 other_variables[var] = AuxiliaryVariable(var, dtype=statement.dtype)
564 return other_variables
565
566 def find_used_variables(self, statements, other_variables):
567 """
568 Find all the variables used on the right hand side of the given
569 expressions.
570
571 Parameters
572 ----------
573 statements : list
574 list of statement objects
575
576 Returns
577 -------
578 used_variables : dict
579 dictionary of variables that are used as variable name (str),
580 `Variable` pairs.
581 """
582 variables = self.variables
583 used_variables = {}
584 for statement in statements:
585 rhs = statement.expr
586 for var in get_identifiers(rhs):
587 if var in self.function_names:
588 continue
589 try:
590 var_obj = variables[var]
591 except KeyError:
592 var_obj = other_variables[var]
593 used_variables[var] = var_obj # save as object because this has
594 # all needed info (dtype, name, isarray)
595
596 # I don't know a nicer way to do this, the above way misses write
597 # variables (e.g. not_refractory)..
598 read, write, _ = self.array_read_write(statements)
599 for var in read | write:
600 if var not in used_variables:
601 used_variables[var] = variables[var] # will always be array and
602 # thus exist in variables
603
604 return used_variables
605
606 def to_replace_vector_vars(self, variables_in_vector, ignore=frozenset()):
607 """
608 Create dictionary containing key, value pairs with to be replaced text
609 to translate from conventional Brian to GSL.
610
611 Parameters
612 ----------
613 variables_in_vector : dict
614 dictionary with variable name (str), `Variable` pairs of variables
615 occurring in vector code
616 ignore : set, optional
617 set of strings with variable names that should be ignored
618
619 Returns
620 -------
621 to_replace : dict
622 dictionary with strings that need to be replaced i.e. _lio_1 will be
623 _GSL_dataholder._lio_1 (in cython) or _GSL_dataholder->_lio_1 (cpp)
624
625 Notes
626 -----
627 t will always be added because GSL defines its own t.
628 i.e. for cpp: {'const t = _ptr_array_defaultclock_t[0];' : ''}
629 """
630 access_pointer = self.syntax["access_pointer"]
631 to_replace = {}
632 t_in_code = None
633 for var, var_obj in list(variables_in_vector.items()):
634 if var_obj.name == "t":
635 t_in_code = var_obj
636 continue
637 if "_gsl" in var or var in ignore:
638 continue
639 if self.is_constant_and_cpp_standalone(var_obj):
640 # does not have to be processed by GSL generator
641 self.variables_to_be_processed.remove(var_obj.name)
642 continue
643 if isinstance(var_obj, ArrayVariable):
644 pointer_name = self.get_array_name(var_obj, access_data=True)
645 to_replace[pointer_name] = (
646 f"_GSL_dataholder{access_pointer}{pointer_name}"
647 )
648 else:
649 to_replace[var] = f"_GSL_dataholder{access_pointer}{var}"
650
651 # also make sure t declaration is replaced if in code
652 if t_in_code is not None:
653 t_declare = self.var_init_lhs("t", "const double ")
654 array_name = self.get_array_name(t_in_code, access_data=True)
655 end_statement = self.syntax["end_statement"]
656 replace_what = f"{t_declare} = {array_name}[0]{end_statement}"
657 to_replace[replace_what] = ""
658 self.variables_to_be_processed.remove("t")
659
660 return to_replace
661
662 def unpack_namespace(
663 self, variables_in_vector, variables_in_scalar, ignore=frozenset()
664 ):
665 """
666 Write code that unpacks Brian namespace to cython/cpp namespace.
667
668 For vector code this means putting variables in _dataholder (i.e.
669 _GSL_dataholder->var or _GSL_dataholder.var = ...)
670 Note that code is written so a variable could occur both in scalar and
671 vector code
672
673 Parameters
674 ----------
675 variables_in_vector : dict
676 dictionary with variable name (str), `Variable` pairs of variables
677 occurring in vector code
678 variables_in_scalar : dict
679 dictionary with variable name (str), `Variable` pairs of variables
680 occurring in scalar code
681 ignore : set, optional
682 set of string names of variables that should be ignored
683
684 Returns
685 -------
686 unpack_namespace_code : str
687 code fragment unpacking the Brian namespace (setting variables in
688 the _dataholder struct in case of vector)
689 """
690 code = []
691 for var, var_obj in list(self.variables.items()):
692 if var in ignore:
693 continue
694 if self.is_constant_and_cpp_standalone(var_obj):
695 continue
696 in_vector = var in variables_in_vector
697 in_scalar = var in variables_in_scalar
698 if in_vector:
699 self.variables_to_be_processed.remove(var)
700 code += [self.unpack_namespace_single(var_obj, in_vector, in_scalar)]
701 return ("\n").join(code)
702
703 def translate_vector_code(self, code_lines, to_replace):
704 """
705 Translate vector code to GSL compatible code by substituting fragments
706 of code.
707
708 Parameters
709 ----------
710 code_lines : list
711 list of strings describing the vector_code
712 to_replace: dict
713 dictionary with to be replaced strings (see to_replace_vector_vars
714 and to_replace_diff_vars)
715
716 Returns
717 -------
718 vector_code : str
719 New code that is now to be added to the function that is sent to the
720 GSL integrator
721 """
722 code = []
723 for expr_set in code_lines:
724 for line in expr_set.split(
725 "\n"
726 ): # every line seperate to make tabbing correct
727 code += [f" {line}"]
728 code = ("\n").join(code)
729 code = word_substitute(code, to_replace)
730
731 # special substitute because of limitations of regex word boundaries with
732 # variable[_idx]
733 for from_sub, to_sub in list(to_replace.items()):
734 m = re.search(r"\[(\w+)\];?$", from_sub)
735 if m:
736 code = re.sub(re.sub(r"\[", r"\[", from_sub), to_sub, code)
737
738 if "_gsl" in code:
739 raise AssertionError(
740 "Translation failed, _gsl still in code (should only "
741 "be tag, and should be replaced).\n"
742 f"Code:\n{code}"
743 )
744
745 return code
746
747 def translate_scalar_code(
748 self, code_lines, variables_in_scalar, variables_in_vector
749 ):
750 """
751 Translate scalar code: if calculated variables are used in the vector_code
752 their value is added to the variable in the _dataholder.
753
754 Parameters
755 ----------
756 code_lines : list
757 list of strings containing scalar code
758 variables_in_vector : dict
759 dictionary with variable name (str), `Variable` pairs of variables
760 occurring in vector code
761 variables_in_scalar : dict
762 dictionary with variable name (str), `Variable` pairs of variables
763 occurring in scalar code
764
765 Returns
766 -------
767 scalar_code : str
768 code fragment that should be injected in the main before the loop
769 """
770 code = []
771 for line in code_lines:
772 m = re.search(r"(\w+ = .*)", line)
773 try:
774 new_line = m.group(1)
775 var, op, expr, comment = parse_statement(new_line)
776 except (ValueError, AttributeError):
777 code += [line]
778 continue
779 if var in list(variables_in_scalar.keys()):
780 code += [line]
781 elif var in list(variables_in_vector.keys()):
782 if var == "t":
783 continue
784 try:
785 self.variables_to_be_processed.remove(var)
786 except KeyError:
787 raise AssertionError(
788 "Trying to process variable named %s by "
789 "putting its value in the _GSL_dataholder "
790 "based on scalar code, but the variable "
791 "has been processed already." % var
792 ) from None
793 code += [f"_GSL_dataholder.{var} {op} {expr} {comment}"]
794 return "\n".join(code)
795
796 def add_gsl_variables_as_non_scalar(self, diff_vars):
797 """
798 Add _gsl variables as non-scalar.
799
800 In `GSLStateUpdater` the differential equation variables are substituted
801 with GSL tags that describe the information needed to translate the
802 conventional Brian code to GSL compatible code. This function tells
803 Brian that the variables that contain these tags should always be vector
804 variables. If we don't do this, Brian renders the tag-variables as
805 scalar if no vector variables are used in the right hand side of the
806 expression.
807
808 Parameters
809 ----------
810 diff_vars : dict
811 dictionary with variables as keys and differential equation index as
812 value
813 """
814 for var, ind in list(diff_vars.items()):
815 name = f"_gsl_{var}_f{ind}"
816 self.variables[name] = AuxiliaryVariable(var, scalar=False)
817
818 def add_meta_variables(self, options):
819 if options["use_last_timestep"]:
820 try:
821 N = self.variables["N"].item()
822 self.owner.variables.add_array(
823 "_last_timestep",
824 size=N,
825 values=np.ones(N) * options["dt_start"],
826 dtype=np.float64,
827 )
828 except KeyError:
829 # has already been run
830 pass
831 self.variables["_last_timestep"] = self.owner.variables.get(
832 "_last_timestep"
833 )
834 pointer_last_timestep = (
835 f"{self.get_array_name(self.variables['_last_timestep'])}[_idx]"
836 )
837 else:
838 pointer_last_timestep = None
839
840 if options["save_failed_steps"]:
841 N = self.variables["N"].item()
842 try:
843 self.owner.variables.add_array("_failed_steps", size=N, dtype=np.int32)
844 except KeyError:
845 # has already been run
846 pass
847 self.variables["_failed_steps"] = self.owner.variables.get("_failed_steps")
848 pointer_failed_steps = (
849 f"{self.get_array_name(self.variables['_failed_steps'])}[_idx]"
850 )
851 else:
852 pointer_failed_steps = None
853
854 if options["save_step_count"]:
855 N = int(self.variables["N"].get_value())
856 try:
857 self.owner.variables.add_array("_step_count", size=N, dtype=np.int32)
858 except KeyError:
859 # has already been run
860 pass
861 self.variables["_step_count"] = self.owner.variables.get("_step_count")
862 pointer_step_count = (
863 f"{self.get_array_name(self.variables['_step_count'])}[_idx]"
864 )
865 else:
866 pointer_step_count = None
867
868 return {
869 "pointer_last_timestep": pointer_last_timestep,
870 "pointer_failed_steps": pointer_failed_steps,
871 "pointer_step_count": pointer_step_count,
872 }
873
874 def translate(
875 self, code, dtype
876 ): # TODO: it's not so nice we have to copy the contents of this function..
877 """
878 Translates an abstract code block into the target language.
879 """
880 # first check if user code is not using variables that are also used by GSL
881 reserved_variables = [
882 "_dataholder",
883 "_fill_y_vector",
884 "_empty_y_vector",
885 "_GSL_dataholder",
886 "_GSL_y",
887 "_GSL_func",
888 ]
889 if any([var in self.variables for var in reserved_variables]):
890 # import here to avoid circular import
891 raise ValueError(
892 f"The variables {str(reserved_variables)} are reserved for the GSL"
893 " internal code."
894 )
895
896 # if the following statements are not added, Brian translates the
897 # differential expressions in the abstract code for GSL to scalar statements
898 # in the case no non-scalar variables are used in the expression
899 diff_vars = self.find_differential_variables(list(code.values()))
900 self.add_gsl_variables_as_non_scalar(diff_vars)
901
902 # add arrays we want to use in generated code before self.generator.translate() so
903 # brian does namespace unpacking for us
904 pointer_names = self.add_meta_variables(self.method_options)
905
906 scalar_statements = {}
907 vector_statements = {}
908 for ac_name, ac_code in code.items():
909 statements = make_statements(
910 ac_code, self.variables, dtype, optimise=True, blockname=ac_name
911 )
912 scalar_statements[ac_name], vector_statements[ac_name] = statements
913 for vs in vector_statements.values():
914 # Check that the statements are meaningful independent on the order of
915 # execution (e.g. for synapses)
916 try:
917 if self.has_repeated_indices(
918 vs
919 ): # only do order dependence if there are repeated indices
920 check_for_order_independence(
921 vs, self.generator.variables, self.generator.variable_indices
922 )
923 except OrderDependenceError:
924 # If the abstract code is only one line, display it in full
925 if len(vs) <= 1:
926 error_msg = f"Abstract code: '{vs[0]}'\n"
927 else:
928 error_msg = (
929 f"{len(vs)} lines of abstract code, first line is: '{vs[0]}'\n"
930 )
931 logger.warn(
932 "Came across an abstract code block that may not be "
933 "well-defined: the outcome may depend on the "
934 "order of execution. You can ignore this warning if "
935 "you are sure that the order of operations does not "
936 "matter. " + error_msg
937 )
938
939 # save function names because self.generator.translate_statement_sequence
940 # deletes these from self.variables but we need to know which identifiers
941 # we can safely ignore (i.e. we can ignore the functions because they are
942 # handled by the original generator)
943 self.function_names = self.find_function_names()
944
945 scalar_code, vector_code, kwds = self.generator.translate_statement_sequence(
946 scalar_statements, vector_statements
947 )
948
949 ############ translate code for GSL
950
951 # first check if any indexing other than '_idx' is used (currently not supported)
952 for code_list in list(scalar_code.values()) + list(vector_code.values()):
953 for code in code_list:
954 m = re.search(r"\[(\w+)\]", code)
955 if m is not None:
956 if m.group(1) != "0" and m.group(1) != "_idx":
957 from brian2.stateupdaters.base import (
958 UnsupportedEquationsException,
959 )
960
961 raise UnsupportedEquationsException(
962 "Equations result in state "
963 "updater code with indexing "
964 "other than '_idx', which "
965 "is currently not supported "
966 "in combination with the "
967 "GSL stateupdater."
968 )
969
970 # differential variable specific operations
971 to_replace = self.diff_var_to_replace(diff_vars)
972 GSL_support_code = self.get_dimension_code(len(diff_vars))
973 GSL_support_code += self.yvector_code(diff_vars)
974
975 # analyze all needed variables; if not in self.variables: put in separate dic.
976 # also keep track of variables needed for scalar statements and vector statements
977 other_variables = self.find_undefined_variables(
978 scalar_statements[None] + vector_statements[None]
979 )
980 variables_in_scalar = self.find_used_variables(
981 scalar_statements[None], other_variables
982 )
983 variables_in_vector = self.find_used_variables(
984 vector_statements[None], other_variables
985 )
986 # so that _dataholder holds diff_vars as well, even if they don't occur
987 # in the actual statements
988 for var in list(diff_vars.keys()):
989 if var not in variables_in_vector:
990 variables_in_vector[var] = self.variables[var]
991 # let's keep track of the variables that eventually need to be added to
992 # the _GSL_dataholder somehow
993 self.variables_to_be_processed = list(variables_in_vector.keys())
994
995 # add code for _dataholder struct
996 GSL_support_code = self.write_dataholder(variables_in_vector) + GSL_support_code
997 # add e.g. _lio_1 --> _GSL_dataholder._lio_1 to replacer
998 to_replace.update(
999 self.to_replace_vector_vars(
1000 variables_in_vector, ignore=list(diff_vars.keys())
1001 )
1002 )
1003 # write statements that unpack (python) namespace to _dataholder struct
1004 # or local namespace
1005 GSL_main_code = self.unpack_namespace(
1006 variables_in_vector, variables_in_scalar, ["t"]
1007 )
1008
1009 # rewrite actual calculations described by vector_code and put them in _GSL_func
1010 func_code = self.translate_one_statement_sequence(
1011 vector_statements[None], scalar=False
1012 )
1013 GSL_support_code += self.make_function_code(
1014 self.translate_vector_code(func_code, to_replace)
1015 )
1016 scalar_func_code = self.translate_one_statement_sequence(
1017 scalar_statements[None], scalar=True
1018 )
1019 # rewrite scalar code, keep variables that are needed in scalar code normal
1020 # and add variables to _dataholder for vector_code
1021 GSL_main_code += f"\n{self.translate_scalar_code(scalar_func_code, variables_in_scalar, variables_in_vector)}"
1022 if len(self.variables_to_be_processed) > 0:
1023 raise AssertionError(
1024 "Not all variables that will be used in the vector "
1025 "code have been added to the _GSL_dataholder. This "
1026 "might mean that the _GSL_func is using "
1027 "uninitialized variables.\n"
1028 "The unprocessed variables "
1029 f"are: {self.variables_to_be_processed}"
1030 )
1031
1032 scalar_code["GSL"] = GSL_main_code
1033 kwds["define_GSL_scale_array"] = self.scale_array_code(
1034 diff_vars, self.method_options
1035 )
1036 kwds["n_diff_vars"] = len(diff_vars)
1037 kwds["GSL_settings"] = dict(self.method_options)
1038 kwds["GSL_settings"]["integrator"] = self.integrator
1039 kwds["support_code_lines"] += GSL_support_code.split("\n")
1040 kwds["t_array"] = f"{self.get_array_name(self.variables['t'])}[0]"
1041 kwds["dt_array"] = f"{self.get_array_name(self.variables['dt'])}[0]"
1042 kwds["define_dt"] = "dt" not in variables_in_scalar
1043 kwds["cpp_standalone"] = self.is_cpp_standalone()
1044 for key, value in list(pointer_names.items()):
1045 kwds[key] = value
1046 return scalar_code, vector_code, kwds
1047
1048
1049 class GSLCythonCodeGenerator(GSLCodeGenerator):
1050 syntax = {
1051 "end_statement": "",
1052 "access_pointer": ".",
1053 "start_declare": "cdef extern ",
1054 "open_function": ":",
1055 "open_struct": ":",
1056 "end_function": "",
1057 "end_struct": "",
1058 "open_cast": "<",
1059 "close_cast": ">",
1060 "diff_var_declaration": "",
1061 }
1062
1063 def c_data_type(self, dtype):
1064 return c_data_type(dtype)
1065
1066 def initialize_array(self, varname, values):
1067 value_list = ", ".join(repr(v) for v in values)
1068 code = "cdef double {varname}[{n_values}]\n"
1069 code += "{varname}[:] = [{value_list}]"
1070 return code.format(varname=varname, value_list=value_list, n_values=len(values))
1071
1072 def var_replace_diff_var_lhs(self, var, ind):
1073 return {f"_gsl_{var}_f{ind}": f"f[{ind}]"}
1074
1075 def var_init_lhs(self, var, type):
1076 return var
1077
1078 def unpack_namespace_single(self, var_obj, in_vector, in_scalar):
1079 code = []
1080 if isinstance(var_obj, ArrayVariable):
1081 array_name = self.generator.get_array_name(var_obj)
1082 dtype = self.c_data_type(var_obj.dtype)
1083 if in_vector:
1084 code += [
1085 f"_GSL_dataholder.{array_name} = <{dtype} *> _buf_{array_name}.data"
1086 ]
1087 if in_scalar:
1088 code += [f"{array_name} = <{dtype} *> _buf_{array_name}.data"]
1089 else:
1090 if in_vector:
1091 code += [
1092 f'_GSL_dataholder.{var_obj.name} = _namespace["{var_obj.name}"]'
1093 ]
1094 if in_scalar:
1095 code += [f'{var_obj.name} = _namespace["{var_obj.name}"]']
1096 return "\n".join(code)
1097
1098 @staticmethod
1099 def get_array_name(var, access_data=True):
1100 # We have to do the import here to avoid circular import dependencies.
1101 from brian2.codegen.generators.cython_generator import CythonCodeGenerator
1102
1103 return CythonCodeGenerator.get_array_name(var, access_data)
1104
1105
1106 class GSLCPPCodeGenerator(GSLCodeGenerator):
1107 def __getattr__(self, item):
1108 return getattr(self.generator, item)
1109
1110 syntax = {
1111 "end_statement": ";",
1112 "access_pointer": "->",
1113 "start_declare": "",
1114 "open_function": "\n{",
1115 "open_struct": "\n{",
1116 "end_function": "\n}",
1117 "end_struct": "\n};",
1118 "open_cast": "(",
1119 "close_cast": ")",
1120 "diff_var_declaration": "const scalar ",
1121 }
1122
1123 def c_data_type(self, dtype):
1124 return self.generator.c_data_type(dtype)
1125
1126 def initialize_array(self, varname, values):
1127 value_list = ", ".join(repr(v) for v in values)
1128 return f"double const {varname}[] = {{{value_list}}};"
1129
1130 def var_replace_diff_var_lhs(self, var, ind):
1131 scalar_dtype = self.c_data_type(prefs.core.default_float_dtype)
1132 f = f"f[{ind}]"
1133 try:
1134 if "unless refractory" in self.variable_flags[var]:
1135 return {
1136 f"_gsl_{var}_f{ind}": f,
1137 f"{scalar_dtype} _gsl_{var}_f{ind};": "",
1138 f"{scalar_dtype} {f};": "",
1139 } # in case the replacement of
1140 # _gsl_var_find to f[ind] happens
1141 # first
1142 except KeyError:
1143 pass
1144 return {f"const {scalar_dtype} _gsl_{var}_f{ind}": f}
1145
1146 def var_init_lhs(self, var, type):
1147 return type + var
1148
1149 def unpack_namespace_single(self, var_obj, in_vector, in_scalar):
1150 if isinstance(var_obj, ArrayVariable):
1151 pointer_name = self.get_array_name(var_obj, access_data=True)
1152 array_name = self.get_array_name(var_obj)
1153 if in_vector:
1154 return f"_GSL_dataholder.{pointer_name} = {array_name};"
1155 else:
1156 return ""
1157 else:
1158 if in_vector:
1159 return f"_GSL_dataholder.{var_obj.name} = {var_obj.name};"
1160 else:
1161 return ""
1162
1163 def make_function_code(self, lines):
1164 # To pass constants that might be used in the function, we need to
1165 # add a %CONSTANTS% placeholder that will be replaced by the standalone
1166 # device
1167 return """
1168 // CONSTANTS
1169 %CONSTANTS%
1170 """ + super().make_function_code(lines)