Code generation based on custom templates
Engee allows you to generate code by usage of Templates.
Templates are text files with .cgt
extension (Codegen Template), which use special syntax to automatically add data and generate code. Code generation using templates is supported for C and Chisel languages.
There are two kinds of custom templates - for blocks and for the main
function:
-
Block templates allow you to generate code for individual model components (functions or modules) that implement specific logic. They provide usage of code at the level of individual operations, which is preferable in the development of complex models with a large number of blocks.
-
Templates for function
main
focus on the overall execution structure of the model, including initialisation, step-by-step processing and termination. This approach is preferred for sequencing the execution of operations in multitasking models.
The choice between these approaches depends on the level of detail and scale: block templates are used to fine-tune the logic, while the `main' template is used to control the entire model.
Code generation for blocks
Custom templates can be used to generate code for blocks of Engee models. After adding the template to the path, click on the "Generate Code" button . In the results folder you will find the generated file in the selected language.
If the template is in a folder (any directory other than /user ), you need to add it to path. To do this, select the folder with the template, right-click on it and add it to the path. Once added, the folder will be displayed with a blue icon ![]() |
The code generator analyses all templates added to the path. In case of finding several templates, the code generator will use the last added template. |
For generation to work, the template file for blocks must have .cgt extension.
|
Block template syntax
The template syntax is based on comments. They can be single-line, starting with //!
, or multi-line, enclosed in /*! */
. Any valid Julia code can be written inside comments. Comments are used so that the template code is executed, but not in the final generated file.
The uncommented parts of the template are directly written to the file. These areas must contain code in C or Chisel. Inside such code, you can insert a small code in Julia using the $()
syntax. Inside the brackets, you can specify any working Julia code that will be executed, and its result will replace this construct in the final file. If the expression is clear and unambiguous, you can use $
without brackets, but the bracketed option is always recommended.
The $() syntax uses special functions only for handling inputs, outputs, and states, but not for block parameters (except for the state_addr function).
|
The special functions supported for code generation within $()
are summarised below:
List of supported functions
Category |
Function |
Description |
Functions for inputs |
|
Returns the input port of the block |
|
Returns the input port data type |
|
|
Returns the dimension of the input port |
|
|
Returns the number of input port dimensions |
|
|
Returns the length ( |
|
|
Returns the complexity of the input port |
|
|
||
Returns the input port calculation step |
|
|
Returns the number of input ports of the block |
Functions for outputs |
|
Returns the output port of the block |
|
|
Returns the output port data type |
|
|
Returns the output port size |
|
|
Returns the number of output port dimensions |
|
|
Returns the length ( |
|
|
Returns the complexity of the output port |
|
|
Returns the output port calculation step |
||
|
Returns the number of output ports of the block |
Functions for states |
|
Returns the block state |
|
|
Returns state data type |
|
|
||
Returns the state dimensionality |
|
|
Returns the number of state dimensions |
|
|
Returns the length ( |
|
|
Returns the complexity of the state |
|
Returns the number of states of the block |
Functions to handle paths to a block |
|
Returns block name |
Functions for Chisel templates |
|
Returns a string with the Chisel type of the signal. For example, if |
Functions for working with the scheduler |
|
Returns the block calculation step (you can use |
|
Returns the number of sampling rates in the model |
|
|
Returns the base sampling rate of the model |
|
|
Returns an array of ratios of base and other sampling rates, e.g. |
|
|
Returns |
|
|
Returns |
Code generation in templates is performed by usage of special metacode macros, which determine in which parts of the final code the necessary fragments will be added (switch the output of the code generator to the corresponding buffer). These macros are used to structure the code and control its placement. The list of supported macros includes:
_List of metacode macros.
Category | Macros | Description |
---|---|---|
Template buffers |
|
It is used to declare local variables of the |
|
Adds code to the end of the generated file. Typically used to terminate or add comments. |
|
|
Contains code that is executed when the model is initialised. The buffer is emitted in the |
|
|
It is used to generate a description of the block’s input ports. The buffer is included in the appropriate section of the model code. |
|
|
Contains code to describe the block’s output ports. It is generated in the section related to output processing. |
|
|
Adds code to the beginning of the file, before the |
|
|
It is used to describe the states of a block, including their sizes, data types and initialisation. It is generated in the state section of the model. |
|
|
The main buffer into which code is written by default, unless another macro is specified. This code is executed at each simulation step. |
|
|
Contains code executed when the model is terminated. The buffer is emitted in the |
|
|
It is used to declare global variables and data types. The code will be inserted in model.h after the |
Templates use a global param
data structure to handle block parameters. This is a named Julia tuple that contains a description of all block parameters, including signal-like parameters (e.g., the value of the Gain parameter in the Gain block) and all other block characteristics.
To examine the contents of the param
structure, you can add a comment with the $param
expression in the template. During code generation, this expression will be replaced with the full description of parameters and characteristics of the block. After that you can refer to individual fields of the param
structure.
Example:
/*!
* BlockType = :SomeBlockINeedToExplore
* TargetLang = :C
*/
/* Let's see the block description:
$param
*/
After code generation, the $param
comment will be replaced with a description of the block parameters, allowing you to explore its structure and properties.
Template example
Let’s look at an example template for the following model:
//! BlockType = :Product
//! TargetLang = :C
//! @Step
//! if contains(param.Inputs,"/")
/* Division is performed if "/" is specified in the block parameters */
/* To avoid division by zero error, added input value check */
$(output_datatype_name(1)) $(output(1)) = $(input(2)) == 0 ? $(input(1)) : $(input(1)) / $(input(2));
//! else
/* Performs multiplication if division is not set in parameters */
$(output_datatype_name(1)) $(output(1)) = $(input(1)) * $(input(2));
//! end
The above example shows an updated template for generating the code for the Divide block in C. In this code:
-
`BlockType = :Product
: Specifies the type of block for which the code is generated; -
`TargetLang = :C
: Specifies the target language for generation, in this case C; -
The template code uses the
@Step
section, which defines the calculations performed at each step of the calculation; -
The
if contains(param.Inputs,"/")
condition checks whether theInputs
parameter contains the string"/"
. If it does, the division operation is performed:-
$(input(2)) == 0
- checks for division by zero. If the denominator is zero, the result is taken to be$(input(1))
; -
Otherwise the division
$(input(1)) / $(input(2))
is performed.
-
-
If division is not used, multiplication is performed
$(input(1)) * $(input(2))
.
Working principle:
-
The
@Step
section code is executed at each calculation step, determining the behaviour of the block depending on the parameters configuration. -
The usage of
$(input(n))
and$(output(n))
allows the input and output ports of the block to be dynamically accessed. -
The output port data type variables are defined via
$(output_datatype_name(1))
, making the code universal across data types.
For C Function and Engee Function blocks, the template syntax is different. Instead of the standard specification of the block type via BlockType , the format used is //!BlockType = :EngeeFunction!EngeeFunction, where ! is followed by the block name from the model, converted for the target language. If the specified BlockType is incorrect, the system will generate a generation error.
|
Usage of the newmodel_1 model template with the Divide block will generate a newmodel_1.c file with the following contents:
#include "newmodel_1.h"
/* External inputs */
Ext_newmodel_1_U newmodel_1_U;
/* External outputs */
Ext_newmodel_1_Y newmodel_1_Y;
/* Model initialise function */
void newmodel_1_init() {
/* (no initialise code required) */
}
/* Model terminate function */
void newmodel_1_term() {
/* (no terminate code required) */
}
/* Model step function */
void newmodel_1_step() {
/* Product: /Product incorporates:
* Inport: /In2
* Inport: /In1
*/
const double Product = newmodel_1_U.In2 * newmodel_1_U.In1;
/* Product: /Divide incorporates:
* Inport: /In1
* Inport: /In1
*/
const double Divide = newmodel_1_U.In1 / newmodel_1_U.In1;
/* Outport: /Out1:
* Product: /Divide
*/
newmodel_1_Y.Out1 = Divide;
/* Outport: /Out2 incorporates:
* Product: /Product
*/
newmodel_1_Y.Out2 = Product;
}
The generated code implements the main functions for running the model: initialisation (newmodel_1_init
), execution of the calculation step (newmodel_1_step
) and termination (newmodel_1_term
).
The newmodel_1_step
function performs the key operations of the model. In this example, two calculations are implemented: multiplication (Product) and division (Divide). The results of these operations are written to the corresponding model output parameters Out1 and Out2. To calculate the values, the data coming through the inputs In1 and In2 defined in the structure Ext_newmodel_1_U
are used.
The initialisation (newmodel_1_init
) and termination (newmodel_1_term
) functions specify /* (no initialize code required) /
and /
(no terminate code required) */
. This means that for this model, no additional custom code had to be added at the code generation stage to perform initialisation or termination operations. These functions are left empty, but are still included in the code to support the syntax of the pattern.
In the generated code, the For example, in the above template, there is only The Thus, space is always reserved for each section in the generated code, but their usage depends entirely on the content of the template. |
Generation of the main function
The main
function represents the entry point for program execution and serves as a wrapper to manage the model lifecycle. In Julia, the main
function is often used to orchestrate the start of a program, where key steps are defined: initialising the model, executing simulation steps and terminating.
The main
function is created using a Julia template, where the structure of the generated code is formed using C-style comments (/* … *//
as described in the syntax section above), and the engee.generate_code
function on the command line or script editor. The generate_code
function signature is as follows:
@with_exception_handling function generate_code(
model_path::String,
output_path::String;
subsystem_id::Maybe{String} = nothing,
subsystem_name::Maybe{String} = nothing,
target::Maybe{String} = nothing,
template_path::Maybe{String} = nothing
)
To generate the code for the main
function, the engee.generate_code
function requires the template path to be specified using the named parameters template_path
.
Example function call:
engee.generate_code(
"/user/codegen_model.engee", # the path to the model from which the code is generated
"/user/codegen_dir"; # the path where the code will be generated from
template_path = "/user/main_template.jl" # path to the main function template
)
Template example
Let’s look at an example template for generating the main
function:
Template for generating
function main_template() :: String
#=%
#include "$model_name.h"
void do_step(void){
%=#
if !is_singlerate_model && !is_singletask_model
zeroes = "0"
for ji = 2:rates_num zeroes *= ", 0" end
#=%
static bool OverrunFlags[$rates_num] = {$zeroes};
static bool eventFlags[$rates_num] = {$zeroes};
static int taskCounter[$rates_num] = {$zeroes};
if (OverrunFlags[0]) return;
%=#
for ji = 2:rates_num
i = ji - 1
rate_ratio = Int(rates[ji] / get_baserate())
#=%
if (taskCounter[$i] == 0) {
if (eventFlags[$i]) {
OverrunFlags[0] = false;
OverrunFlags[$i] = true;
/* Sampling too fast */
return;
}
eventFlags[$i] = true;
}
taskCounter[$i]++;
if (taskCounter[$i] == $rate_ratio) {
taskCounter[$i] = 0;
}
/* Step the model for base rate */
$(model_substep(0))
/* Indicate task for base rate complete */
OverrunFlags[0] = false;
%=#
end
for ji = 2:rates_num
i = ji - 1
#=%
/* If task {0} is running, do not run any lower priority task */
if (OverrunFlags[$i]) return;
/* Step the model for subrate */
if (eventFlags[$i]) {
OverrunFlags[$i] = true;
/* Step the model for subrate $i */
$(model_substep(i))
/* Indicate task complete for subrate */
OverrunFlags[$i] = false;
eventFlags[$i] = false;
}
%=#
end
else
#=%
static bool OverrunFlag = false;
/* Check for overrun */
if (OverrunFlag) {
return;
}
OverrunFlag = true;
/* Step the model */
$model_step
/* Indicate task complete */
OverrunFlag = false;
%=#
end
print_sig(s) = "$(s.ty) $(s.full_qual_name)$(dims(s))"
#=%
}
int main(int argc, char *argv[])
{
(void) argc;
(void) argv;
/* Initialise model */
$model_init
while (1) {
/* Perform application tasks here */
// Signals available:
// INS
// $(print_sig.(ins))
// OUTS
// $(print_sig.(outs))
}
/* Terminate model */
$model_term
return 0;
}
%=#
end
Here:
-
At the beginning of the template, the model header file is connected via
#include "$model_name.h"
to access the model functions. -
The main modelling step is executed by calling
$(model_substep(0))
and resetting the status flags. For sub-frequency tasks, execution is monitored, steps are processed with$(model_substep(i))
and completion flags are updated. -
For single-task models, overload control is implemented via the OverrunFlag and model execution is invoked via
$model_step
. -
In the
main
function,$model_init
is called to prepare the model for execution. -
In an infinite loop, model tasks and signals available for interaction are processed.
-
Before termination,
$model_term
is called to correctly terminate the model and release resources.