Debian Codegraph @

docs_sphinx/developer/codegen.rst

raw
1 Code generation
2 ===============
3
4 The generation of a code snippet is done by a `CodeGenerator` class.
5 The templates are stored in the `CodeObject.templater` attribute, which is
6 typically implemented as a subdirectory of templates. The compilation and
7 running of code is done by a `CodeObject`. See the sections below for each
8 of these.
9
10 Code path
11 ---------
12
13 The following gives an outline of the key steps that happen for the code
14 generation associated to a `NeuronGroup` `StateUpdater`. The items in grey
15 are Brian core functions and methods and do not need to be implemented to
16 create a new code generation target or device. The parts in yellow are
17 used when creating a new device. The parts in green relate to generating
18 code snippets from abstract code blocks. The parts in blue relate to creating
19 new templates which these snippets are inserted into. The parts in red
20 relate to creating new runtime behaviour (compiling and running generated
21 code).
22
23 .. image:: codegen_code_paths.png
24
25 In brief, what happens can be summarised as follows. `Network.run` will call
26 `BrianObject.before_run` on each of the objects in the network. Objects such
27 as `StateUpdater`, which is a subclass of `CodeRunner` use this spot to
28 generate and compile their code. The process for doing this is to first
29 create the abstract code block, done in the `StateUpdater.update_abstract_code`
30 method. Then, a `CodeObject` is created with this code block. In doing so,
31 Brian will call out to the currently active `Device` to get the `CodeObject`
32 and `CodeGenerator` classes associated to the device, and this hierarchy of
33 calls gives several hooks which can be changed to implement new targets.
34
35 Code generation
36 ---------------
37
38 To implement a new language, or variant of an existing language, derive a class
39 from `CodeGenerator`. Good examples to look at are the `NumpyCodeGenerator`,
40 `CPPCodeGenerator` and `CythonCodeGenerator` classes in the
41 ``brian2.codegen.generators`` package. Each `CodeGenerator` has a ``class_name``
42 attribute which is a string used by the user to refer to this code generator
43 (for example, when defining function implementations).
44
45 The derived `CodeGenerator` class should implement the methods marked as
46 ``NotImplemented`` in the base `CodeGenerator` class. `CodeGenerator` also has
47 several handy utility methods to make it easier to write these, see the
48 existing examples to get an idea of how these work.
49
50 Syntax translation
51 ------------------
52
53 One aspect of writing a new language is that sometimes you need to translate
54 from Python syntax into the syntax of another language. You are free to
55 do this however you like, but we recommend using a `NodeRenderer` class
56 which allows you to iterate over the abstract syntax tree of an expression.
57 See examples in ``brian2.parsing.rendering``.
58
59 Templates
60 ---------
61
62 In addition to snippet generation, you need to create templates for the
63 new language. See the ``templates`` directories in ``brian2.codegen.runtime.*``
64 for examples of these. They are written in the Jinja2 templating system. The
65 location of these templates is set as the `CodeObject.templater` attribute.
66 Examples such as `CPPCodeObject` show how this is done.
67
68 Template structure
69 ~~~~~~~~~~~~~~~~~~
70
71 Languages typically define a ``common_group`` template that is the base for all
72 other templates. This template sets up the basic code structure that will be reused by
73 all code objects, e.g. by defining a function header and body, and adding standard
74 imports/includes. This template defines several blocks, in particular a ``maincode``
75 clock containing the actual code that is specific to each code object. The specific
76 templates such as ``reset`` then derive from the ``common_group`` base template and
77 override the ``maincode`` block. The base template can also define additional blocks
78 that are sometimes but not always overwritten. For example, the ``common_group.cpp``
79 template of the C++ standalone code generator defines an ``extra_headers`` block that
80 can be overwritten by child templates to include additional header files needed for the
81 code in ``maincode``.
82
83 Template keywords
84 ~~~~~~~~~~~~~~~~~
85
86 Templates also specify additional information necessary for the code generation process
87 as Jinja comments (``{# ... #}``). The following keywords are recognized by Brian:
88
89 ``USES_VARIABLES``
90 Lists variable names that are used by the template, even if they are not referred to
91 in user code.
92 ``WRITES_TO_READ_ONLY_VARIABLES``
93 Lists read-only variables that are modified by the template. Normally, read-only
94 variables are not considered to change during code execution, but e.g. synapse
95 creation requires changes to synaptic indices that are considered read-only
96 otherwise.
97 ``ALLOWS_SCALAR_WRITE``
98 The presence of this keyword means that in this template, writing to scalar
99 variables is permitted. Writing to scalar variables is not permitted by default,
100 because it can be ambiguous in contexts that do not involve all neurons/synapses.
101 For example, should the statement ``scalar_variable += 1`` in a reset statement
102 update the variable once or once for every spiking neuron?
103 ``ITERATE_ALL``
104 Lists indices that are iterated over completely. For example, during the state
105 update or threshold step, the template iterates over all neurons with the standard
106 index ``_idx``. When executing the reset statements on the other hand, not all
107 neurons are concerned. This is only used for the numpy code generation target,
108 where it allows avoiding expensive unnecessary indexing.
109
110 Code objects
111 ------------
112
113 To allow the final code block to be compiled and run, derive a class from
114 `CodeObject`. This class should implement the placeholder methods defined in
115 the base class. The class should also have attributes ``templater`` (which
116 should be a `Templater` object pointing to the directory where the templates
117 are stored)
118 ``generator_class`` (which should be the `CodeGenerator` class), and
119 ``class_name`` (which should be a string the user can use to refer to this
120 code generation target.
121
122 Default functions
123 -----------------
124
125 You will typically want to implement the default functions such as the
126 trigonometric, exponential and ``rand`` functions. We usually put these
127 implementations either in the same module as the `CodeGenerator` class or
128 the `CodeObject` class depending on whether they are language-specific or
129 runtime target specific. See those modules for examples of implementing
130 these functions.
131
132 Code guide
133 ----------
134
135 * ``brian2.codegen``: everything related to code generation
136 * ``brian2.codegen.generators``: snippet generation,
137 including the `CodeGenerator` classes and default function implementations.
138 * ``brian2.codegen.runtime``: templates, compilation and running of code,
139 including `CodeObject` and default function implementations.
140 * ``brian2.core.functions``, ``brian2.core.variables``: these define the values
141 that variable names can have.
142 * ``brian2.parsing``: tools for parsing expressions, etc.
143 * ``brian2.parsing.rendering``: AST tools for rendering expressions in Python
144 into different languages.
145 * ``brian2.utils``: various tools for string manipulation, file management, etc.
146
147 Additional information
148 ----------------------
149
150 For some additional (older, but still accurate) notes on code generation:
151
152 .. toctree::
153 :maxdepth: 2
154
155 oldcodegen