Preamble

.1. Abstract

The eFMI (FMI for embedded systems) standard specified in this document aims to extend the scope of FMI (https://fmi-standard.org) from simulation towards software development. The eFMI standard is intended as exchange format for workflows and tool chains from physical models to embedded software. It is defined as a layered approach built upon the FMI for Co-Simulation standard (any version). An eFMI component, that is an eFMU (Functional Mock-Up Unit for embedded systems), can be packed in different formats. Especially, an eFMU can be packed as FMU and can then be simulated with any FMI compliant tool (https://fmi-standard.org/tools) to perform Software-in-the-loop (SiL) testing. Code generation for an embedded device requires however dedicated tool support for eFMI.

This effort is motivated by the fact that especially the development of advanced control functions and diagnosis functions can benefit from physical models. As of today the realization of such model-based functions incorporating physical models, in the following refered to as physics-based functions, is very involved. The expertise from the physical modeling domains, control design and numerics for real time applications are required as well as implementation knowledge in terms of rules & regulations for embedded software have to be taken into account in order to supply an industry grade function on an embedded device.

The eFMI standard describes a container format that will allow to exchange models in a variety of different types of model representations:

InputOutputBlock
  • The Algorithm Code representation describes the mathematical model in a target environment and implementation independent fashion as input/output, sampled data block with one fixed or variable sample time using the standardized intermediate language GALEC (Guarded Algorithmic Language for Embedded Control) developed for this purpose. GALEC is based on a small subset of Modelica functions together with changes and extensions as needed for embbeded real-time systems. GALEC code can be scrambled to provide a certain degree of Intellectual Property protection. Physical modeling tools should be able to generate this representation with reasonable effort.

  • The Production Code representations allow to ship C or C++ code within the same container, either as nearly target environment independent generic code and/or as highly optimized target environment specific code. Contrary to FMI, there is no standardized API (getX, setX, doStep, …​), but a description of the actual code interface to allow the code to be integrated into existing software architectures with minimal calling overhead. When an eFMI is packed as FMU, an FMU wrapper is added to a selected code representation. Software development tools should be able to provide the transformation from an Algorithm Code to one or more Production Code representations with reasonable effort.

  • The Binary Code representations provide target environment specific executable codes. These code representations naturally provide the best Intellectual Property protection.

  • The Behavioral Model representation provides references results for different scenarios to allow automatic tests of the Production and Binary Code representations. In the future this representation might be extended to include the original model from which the eFMI representations are derived, or computable scenarios might be added in form of FMUs.

By means of one global content XML description of all parts of an eFMU and by one XML manifest file for every eFMI representation shipped in an eFMU, a highly flexible and extensible mechanism is provided that allow to integrate eFMUs into arbitrary software architectures being deployed to any kinds of execution environment, including for example AUTOSAR or adaptive AUTOSAR.

.2. Overview

This document specifies the eFMI (FMI for embedded systems standard) with references to the FMI (Functional Mock-Up Interface) standard (https://fmi-standard.org/)

In section Section .3 the development of the eFMI standard and its intended usage is motivated.

The technical key concepts with reference to the current FMI standard are explained in section Chapter 1 for the better understanding of the later sections.

Thereafter the eFMI standard is specified starting with the description of the overall container structure of an eFMU (Functional Mock-Up Unit for embedded systems) in section Chapter 2.

The following sections Chapter 5, Chapter 4, Chapter 6, Chapter 7 are dedicated to the different types of model representations supported by eFMI. Each description consists of an introductory section followed by the specifications of the corresponding meta data and language:

  • The Behavioral Model representation provides reference results to allow automatic verification of the Production and Binary Code representations.

  • The Algorithm Code representation describes the mathematical model of discrete-time, sampled data, input/output blocks in a target environment and implementation independent fashion with the standardized intermediate language GALEC (Guarded Algorithmic Language for Embedded Control - a small subset of the Modelica language (https://www.modelica.org/modelicalanguage) with extensions as needed for embbeded systems).

  • The Production Code representation defines one or more mappings of an Algorithm Code representation to C or C++ Code (for example 32-bit and/or 64-bit representation of floating point numbers, portable [ISO/IEC 9899:2024] code and/or code specialized to a particular target environment like AUTOSAR and/or specific processors).

  • The Binary Code representation provides one or more target environment specific executable codes for one production code representation.

In the following image an overview of the eFMI representations is given, together with examples for potential tool chains:

efmi representations

This standard document is accompanied by the following open source codes and files to allow tools to more easily support the eFMI standard:

  • XML schema files for all xml manifest files defined in this document.

  • An eFMI compliance checker in form of a Python library, to check compliance of eFMUs (Functional Mock-Up Units for embedded systems) with this specification.

  • The eFMI_TestCases Modelica package providing > 20 dedicated Modelica models and variants of them to test eFMI tool chains.

  • The eFMI Modelica package providing all eFMI built-in functions as Modelica functions with a Modelica implementation, in order that Modelica models can use these functions.

  • ReferenceResults for the models of the eFMI_TestCases library in form of > 50 csv files.

  • eFMUs for the eFMI_TestCases library generated with various tools.

.3. Introduction

The goal of the eFMI standard (FMI for embedded Systems) is to enhance Production Code of embedded control systems by physics-based models in an automated way. This shall improve the performance of the underlying systems, reduce the maintenance costs and increase the productivity of software development for embedded systems.

Embedded software is commonly used on ECUs (Electronic Control Units) to control or monitor a system. In these cases it is beneficial to incorporate knowledge of the system behavior into the function. Physical models aim to describe the behaviour of the system for a given range of operation. These models are well described by differential- and algebraic equations or can be approximated by projection on a neural network.

Physical models can be utilized to achieve a significantly better performance of the system in applications such as:

  • observers/virtual sensors (e.g. extended and unscented Kalman filters, moving horizon estimation),

  • model-based diagnosis (e.g. signal based fault detectors, linear/nonlinear residual generators),

  • feedback and feedforward controllers (e.g. linear controllers with gain scheduling, nonlinear inverse models, nonlinear dynamic inversion, feedback linearization, linear/nonlinear model-predictive control),

  • neural networks to approximate physical models and/or the above applications.

These types of functions are typically hand-coded software implemented and tested in an elaborate and time-consuming fashion. The eFMI standard aims to provide model exchange capabilities that allow to transfer physical models created in dedicated modeling and simulation tools to embedded code generating tools for ECU software. This enables an end to end workflow from physical modeling to the deployment of the software function on an embedded device.

The eFMI standard is an open standard based on the FMI standard (Functional Mock-Up Interface, https://fmi-standard.org/). eFMI components are able to interoperate with software components according to the automotive embedded system standards AUTOSAR (https://www.autosar.org/standards/classic-platform/) and Adaptive AUTOSAR (https://www.autosar.org/standards/adaptive-platform/). Generated code shall refer to typical safety measures and coding guidelines, e.g. in the Automotive industry the ISO 26262 and [MISRA C:2025].

Different types of model representation shall allow to separate the concerns of deriving a proper computation algorithm and its compliant implementation for an embedded device. The container architecture and rich meta information, extending the FMI model description, support the integration in existing development processes and tool chains.

1. General concepts

This section describes the general concepts of the eFMI standard

The goal of the standard is to extend the existing FMI standard to the embedded domain. The FMI standard is focused on simulation of models and model parts, on few standardized target environments (Windows, Linux) with well known tool chains. With this context in mind, the FMI standard does not consider any constraints with respect to resource consumption or run time characteristics of the model.

In contrast there is a considerable diversity of embedded target environments, each with their own constraints with respect to runtime performance, memory limits or available compiler support. Given these additional constraints the goal of the FMI standard "Compile once, run everywhere" is neither feasible nor desirable.

A further aspect is the use of models not only for the sake of simulation but in a broad application range, from advanced control strategies like model predictive control to model based diagnosis. The eFMI standard must consider these aspects and is therefore designed as an extension to the FMI standard as described in the following.

1.1. Comparing FMI with eFMI

A major enhancement of the eFMI standard in comparison to the FMI standard is the introduction of different abstraction levels. The FMI standard is based on an executable C Code with an interface of fixed and well defined functions (like getX, setX and doStep). This approach is well suited for the purpose of simulation on a standardized target environment (either Windows or Linux).

However, such an approach is not very suitable for (deeply) embedded code due to the following reasons:

  • Support of a diverse number of target environments.

  • Support of a diverse number of compilers.

  • Integration of the code into existing code structures (in the following we will call this the "Software context") with minimum overhead in data passing and function calling.

For this reason one fixed C Code (or one fixed executable) representing the implementation is not sufficient. Instead the eFMI supports the concept of several C Code implementations (or also binary implementations), each with a description of the interface of the C Code. These descriptions are defined in so-called manifest files and are bundled with the corresponding code files into a Production code container. More details on these manifest files can be found in the section on Production Code manifests (Section 6.1). Here you will also find examples demonstrating the influence of the software context onto the generated code and manifest descriptions.

An FMU represents exactly one model (implemented by the C Code or executable). The same shall be true also for an eFMU despite of the fact that it may contain any number of C Code implementations, and additionally, it shall be easily possible to add further implementations (e.g. for different target environments) into the eFMU at any time.

This requirement is enabled by adding a higher level abstraction to the eFMU, namely the "Algorithm Code".

The Algorithm Code contains an abstracted description of the function(s) to be computed, and serves as the input to generate the C Code implementations. The functions are described in an imperative programming language, and the meta data is also given in a manifest file. The Algorithm Code is a solution to a causalization of this system by specifying

  • Causalization: the input/output behaviour of the system.

  • Discretization: discretization of differential equations (use of solver, time discretization).

The Algorithm Code is organized in code containers in the eFMU, similar to the Production Code container. For more details on the organization of these containers to form a valid eFMU, please see the section on container architecture (Chapter 2).

The following table summarizes the differences between FMI and eFMI.

Topic

FMI

eFMI

Goal

(co-) simulation

efficient ECU implementation

Target environment

standardized (Windows (.dll), Linux)

diverse: different ECUs, different compilers

Reuse

"as is" in "all" simulation environments

highly limited (therefore several implementations possible)

Interface

fixed based on standardized API (getX, setX, doStep, …​)

Only fixed on ideal algorithmic level (GALEC program of Algorithm Code container) but not C production code (derived Production and Binary Code containers); actual interface of production code described in Production Code manifest.

Implementation

one implementation (source code) compiled for different standard target environments

any number of implementations compiled for arbitrary many specific target environments

Abstraction level

C Code level

Abstract model representation algorithm (Algorithm Code) in addition to (derived) C Code implementation (Production Code)

1.2. FMI compliance

An important fact is that despite the broadened scope of the eFMI, an eFMU can be packed into an FMU. This is achieved by taking a distinguished Production Code level implementation and wrapping this to an FMI compliant interface with corresponding model description file. Surely this Production Code level implementation must be target environment independent and suitable for simulation target environments like Windows or Linux.

1.3. Functions in eFMI

In the following different kinds of functions considered in the eFMI standard are described. It is mentioned for which model representation a certain function kind is available. Differences between the kind of functions and consequences and requirements for e.g. transformation tools are also covered.

1.3.1. Block-interface functions

(Available in Algorithm Code and Production Code model representation)

The Algorithm and Production Code model representation is mathematically defined as a sampled input/output block with a fixed sample period for the whole block. All variables of the block have a defined type and all statements of the block are sorted and explicitly solved for a particular variable. Six block-interface functions for initialization of all block variables, (re)calibration and sampling are defined.

The block-interface functions are defined in the Algorithm Code representation. A Production Code generator translate the whole block to C code. It is also possible to just provide production code without underlying GALEC code; in this case, the Algorithm Code container still has to describe the block-interface in its manifest (although it is without actual code).

On Production Code level the block is highly integrated in the environment provided by the embedded control unit (ECU). For example, if the ECU provides input signals at certain addresses in memory or the parameters are part of an overall global C-struct. Consequently the actual implementation/interface of the block-interface is at liberty of the Production Code generating tool.

1.3.2. Built-in functions

(Available in Algorithm Code and Production Code model representation)

Built-in functions are functions with well defined syntax and semantics in the eFMI standard. This includes elementary functions such as sin, cos, log, exp, but also functions to solve linear equation systems in various ways, for example

1
  x := solveLinearEquations(A, b);

to solve the linear equation system A*x = b with regular A matrix for x.

Built-in functions can be used in Algorithm Code or Production Code. All built-in functions that are supported by the eFMI standard are defined in Section 3.11. The names of the built-in functions are reserved and must not be declared by the user.

A tool that transforms Algorithm Code into Production Code doesn’t need additional information for those functions, because their syntax and semantics are clearly defined thus the tool knows how to handle it.

1.3.3. Local functions

(Available at Algorithm Code and Production Code level)

In Algorithm Code, local functions can be defined together with the physics-based model that underlies the eFMU. A local function is formally defined with the GALEC language, see section Chapter 3. A Production Code generator generates a C-function from this definition. Alternatively, a local function can be provided as C Code, together with a GALEC wrapper that defines how the call of the GALEC function is mapped to C (the syntax and semantics is identical to the Modelica external function interface). The declaration of the logical function interface must be provided in the corresponding manifest file.

Example of a local function implemented with the GALEC language:

1
2
3
4
5
6
7
function add
  input  Real u1;
  input  Real u2;
  output Real y;
algorithm
  y := u1 + u2;
end add

Example of a local function wrapper with the GALEC language around a C-function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
/* GALEC function wrapper */
function dot  /* scalar product */
  input  Real v1[:];
  input  Real v2[size(v1,1)];
  output Real y;
  external "C" y = dot(size(v1,1), v1, v2)
end dot

/* C Code signature */
float_t dot(const int32_t n, float_t const v1[], float_t const v2[]);

2. eFMU container architecture

An eFMU can be packed in different formats. The basic structure of the eFMU specific part is always:

<eFMU root directory>  // depends on the package format
    // Directories for eFMU model representations (tool specific)
    schemas            // directory with the used eFMI schemas
    __content.xml      // defines the eFMU folder structure

The only required names are the file name __content.xml and the directory name schemas at the root of the eFMU folder. All other directory and file names are defined by the eFMU generation tool. The used directory and file names are stored in the __content.xml file and can therefore be deduced by reading this file.

The following eFMU package formats are defined:

  1. The <eFMU root directory> is a standard directory in the file system.
    [This is useful to hold an eFMU in a text-based version control system, such as github, gitlab or svn.]

  2. The <eFMU root directory> of (1) is zipped with the efmu-content, especially __content.xml, at the root of the zip-file. The zip-file has the extension .efmu.
    [This packaging is useful to ship or distribute an eFMU.]

  3. The <eFMU root directory> of (1) is path extra/org.efmi-standard inside a standard FMU (Functional Mock-Up Unit) of any FMU type and any FMU version. The path is defined according to the FMI 3.0 specification. With attribute activeFMU inside the __content.xml file it is defined which of the Algorithm, Production or Binary code representations is used as basis of the FMU.
    [This package format is useful to ship or distribute an eFMU for Software-in-the-Loop simulation with any suitable FMU tool.]

Note, Algorithm Code, Production Code and Binary Code representations can optionally store associated FMUs. For example Algorithm Code can store a Model-in-the-Loop FMU and Production Code can store one or more Software-in-the-Loop FMUs for different target environments. In order to execute these FMUs directly, an eFMI tool is needed. Otherwise, one of the stored FMUs can be selected for package format (3) in order that any FMI-tool can simulate this specific FMU.

Example:

An eFMU could be stored as zip-file with extension .fmu having the following internal structure:

modelDescription.xml      // required FMI file
// optional FMI directories and files
extra                     // extra directoy of FMI 2.0 and 3.0
    org.efmi-standard     // eFMU root directory
        // tool specific directories, e.g. AlgorithmCode
        schemas           // directory with the used eFMI schemas
        __content.xml     // defines the eFMU folder structure

An eFMU may contain any number of additional subdirectories below the <eFMU root directory>, each subdirectory being a container of some model representation type. An eFMU must contain exactly one Algorithm Code Model container; of any other model representation type arbitrary many containers can be given, including the special cases of none. Each container can be structured arbitrarily into further subdirectories and files, but must have a dedicated manifest file at its root.

2.1. Content description (efmiContainerManifest.xsd)

The __content.xml file is the registry for all model representations in the eFMU container. It has the following schema definition:

ContainerManifest
Name Description

xsdVersion

The version of the XSD Schema of the __content.xml in Semantic Versioning 2.0.0 format (https://semver.org).

activeFMU

Value of name attribute of model representation whose FMU is currently unpacked in the root directory of the FMU. If no FMU is unpacked currently, the value of this attribute must not be set.

efmiManifestAttributesBase

A group of attributes that is identical for all manifest files. For details see [ManifestAttributesBase].

Each model representation that is a part in the eFMU container must have a corresponding entry in the __content.xml file with the following information:

ModelRepresentation
Name Description

name

Unique name of the container, also defining its root directory name.

kind

The type of the model representation. The allowed values are AlgorithmCode, ProductionCode, BinaryCode, BehavioralModel.

manifest

Name of the container’s manifest file. The manifest is located in the container’s root directory, cf. "name" attribute.

checksum

SHA-1 hash according to [FIPS PUB 180-4] of the binary content — i.e., content as is without any modifications like operating environment specific line-ending or encoding localizations — of the manifest file of the model representation. The given checksum must be correct; if it is not the SHA-1 hash of the manifest file of the model representation, the eFMU is invalid. A checksum of the whole content of the model representation container is not required, because the files belonging to the container and their respective checksums are listed in its manifest.

manifestRefId

The unique GUID of the manifest file (= corresponding attribute of ManifestReference). References a manifest using the Manifest elements id attribute. This information has been added for technical purposes only to speedup resolving references between manifest files via the manifestRefId outlined below. Otherwise, following an inter-manifest reference (via a manifestRefId used in the source manifest) would demand to read other manifest files until a manifest with the desired id is found).

The following is an example of such a content file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.1" encoding="utf-8"?>
<Content xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="schemas/efmiContainerManifest.xsd"
         xsdVersion ="0.9.0"
         efmiVersion="1.0.0"
         id         ="{92b7edbe-e77d-419a-8457-bf8d452a98f6}"
         name       ="MyModel"
         generationDateAndTime="2021-02-27T15:43:25Z"
>
	<ModelRepresentation kind         ="ProductionCode"
                         name         ="TLGeneratedCode_v1"
                         manifest     ="mark.xml"
                         checksum     ="e29810938a2a535dc8f6f9b8f51c5febe834ee01"
                         manifestRefId="63f8c810-f008-47f0-a4b6-7a243f83e46b" />
	<ModelRepresentation kind         ="AlgorithmCode"
                         name         ="algoCode_v1"
                         manifest     ="luke.xml"
                         checksum     ="e29810938a2a535dc8f6f9b8f51c5febe834ee05"
                         manifestRefId="63f8c810-f008-47f0-a4b6-7a243f85e46b" />
	<ModelRepresentation kind         ="BinaryCode"
                         name         ="binCode_v1"
                         manifest     ="matthew.xml"
                         checksum     ="e29810938a2a535dc8f6f9b8f51c5febe834ee08>"
                         manifestRefId="63f8c810-f008-47f0-a4b6-7a243f85e47b" />
</content>

This __content.xml file describes therefore the following directory structure:

<eFMU root directory>
    TLGeneratedCode_v1
        mark.xml
    algoCode_v1
        luke.xml
    binCode_v1
        matthew.xml
    schemas               // directory with the used eFMI schemas
    __content.xml         // the xml-file of the example above

This example just demonstrates that the folder names of the model representations and the manifest file names are defined by the generating tool. Typically, more descriptive names would be used, such as:

<eFMU root directory>
    BehavioralModel
        manifest.xml
    AlgorithmCode
        manifest.xml
    ProductionCode_Generic_C_Float32
        manifest.xml
    ProductionCode_Generic_C_Float64
        manifest.xml
    ProductionCode_Autosar_Float32
        manifest.xml
    schemas
    __content.xml

2.2. Structure of Model Representations

Each model representation can have its own flexible structure. Its content and the structuring of information is described in the manifest file (for details on specific manifest files for the different kind of model representations refer to the corresponding sections). Which file in a model representation is its manifest file can be found as the reference entry in the __content.xml file. The manifest file must be located in the model representation’s root folder.

eFMI allows for having model representations consisting of a manifest file only, hence information should not be doubled. For example, a tool generating directly a Production Code Model Representation must also generate an Algorithm Code Model Representation, because information relevant for Algorithm Code is stored only in the corresponding manifest file and not in the Production Code manifest.

2.3. Model Representation Manifests

The model representation manifests share the same guiding principles:

  1. Entity names start with a capital letter

  2. Attribute names start with a lower-case letter and use camelCase where needed.

  3. Entities that serve as a group get the name of the grouped entities and an 's' as postfix.

  4. Each entity that should be referred to has an attribute called id.

  5. The type of an id attribute is an arbitrary string.

  6. All id attribute values in a manifest file are unique.

  7. References to other elements within or across manifest are established through attributes ending with "RefId". The value is the id of the referenced element.

  8. For file references a string attribute is used and the value is interpreted as the relative path starting at the corresponding model representations root folder.

  9. The context of a reference is specified in the definition of the manifest element and could be either within the same manifest (local context) or within the a referenced manifest (foreign context).

All manifests also share the principles outlined in the following sections:

2.3.1. Attributes of manifest files (efmiManifestAttributes.xsd)

The top-level element of a manifest file has the two attributes xsdVersion and kind that have a fixed value specific for the varying kinds of manifest. For example, for Algorithm Code manifests the two attributes must be:

ManifestAttributesFixedValues

The attributes have the following meaning:

AName Description

xsdVersion

The version of the XSD Schema of the manifest in Semantic Versioning 2.0.0 format (https://semver.org).

kind

The type of the manifest. The allowed values are: AlgorithmCode, ProductionCode, BinaryCode and BehavioralModel.

Additionally, the top-level element of a manifest file has the following attributes (that are not specific to the manifest kind):

ManifestAttributesBase

The attributes have the following meaning:

Name Description

efmiVersion

The version of the eFMI Standard in Semantic Versioning 2.0.0 format (https://semver.org).

id

The UUID for this manifest file.

name

The name of the block (controller, diagnosis system etc.) as used in the modeling environment from which the manifest file was created, such as "Modelica.Mechanics.Rotational.Examples.CoupledClutches".

description

Optional string with a brief description of the block.

version

Optional version number of the block as used in the modeling environment from which the manifest file was created. [Example: "1.0"].

generationDateAndTime

Date and time of last modification of the manifest or any contents within its container. Must be an xs:dateTime in Coordinated Universal Time (UTC), i.e, without time offset, only using arabic numerals, with hours, minutes and seconds but no smaller fractions, satisfying the pattern YYYY-MM-DDTHH:MM:SSZ whereas Y is the year, M the month, D the day, H the hour, M the minutes and S the seconds. This format is satisfying ISO 8601-1:2019. [Example: generationDateAndTime="2009-12-08T14:33:22Z" ]

generationTool

Optional name of the tool that created the manifest file. If the files have been created manually use generationTool="manual".

copyright

Optional information on the intellectual property copyright for the manifest and code files.
[Example: copyright = "© My Company 2020"].

license

Optional information on the intellectual property licensing for the manifest and code files.
[Example: license = "BSD license <license text or link to license>" or "Proprietary" or "Public Domain"].

Note, optional attributes defined in the __content.xml file, hold also for the manifest files in folders below this file, if not redefined in a manifest file. For example, if attribute license is defined in the __content.xml, but in no other manifest file of this eFMU, then the defined license holds for all directories and files below the <eFMU root directory>. If, say, a Production Code manifest defines a license attribute, then this license holds for all directories and folders in this Production Code model representation, independently what is defined in the __content.xml file.

2.3.2. Listing of relevant other manifest files (efmiManifestReferences.xsd)

The information about the eFMU is layered into several model representations (e.g. Algorithm Code, Production Code). In order to allow cross referencing between these model representations, the manifest files to be referenced need to be registered in a manifest file of a certain model representation. For this the ManifestReference tag is used with the following attributes

ManifestReference
Name Description

id

Unique id of the manifest reference entry. This id is used to establish cross manifest references.

manifestRefId

The unique GUID of the manifest. [Note, the name of the associated model representation in the __content.xml file is not used, in order to decouple the manifest files from the container manifest.]

checksum

The expected SHA-1 hash according to [FIPS PUB 180-4] of the binary content — i.e., content as is without any modifications like operating environment specific line-ending or encoding localizations — of the referenced manifest file. If the actual SHA-1 hash of the referenced manifest, as listed in the __content.xml, and the expected one are not equivalent, this container is stale (i.e., the referenced container changed since the last update of this container).

origin

Boolean flag to indicate if that referenced model representation is the one that was used to derive the current model representation.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<ManifestReferences>
  <ManifestReference id           ="ID_1"
                     manifestRefId="{63f8c810-f008-47f0-a4b6-7a243f85e46b}"
                     checksum     ="e29810938a2a535dc8f6f9b8f51c5febe834ee05"
                     origin       = true />
  <ManifestReference id           ="ID_2"
                     manifestRefId="{63f8c810-f008-47f0-a4b1-7a243f85222b}"
                     checksum     ="b4b84af148e587b95300d7a734302d1b911a6e58"
                     origin       =false />
</ManifestReferences>

2.3.3. Listing of files belonging to the model representation (efmiFiles.xsd)

Each manifest contains a list of the files that are part of its model representation. These files are listed in a manifest as follows in the Files elements tag.

FileList

A File element has the following attributes:

Name Description

id

id of the file reference entry. This is id is used to refer to the file reference within the manifests.

name

Name of the file

path

Directory part of path to the file (relative to root of model representation). Value has to start with ./ and end with /.

needsChecksum

Boolean flag indicating if the file is considered in the checksum calculation (the default value is "true").

checksum

Optional SHA-1 hash according to [FIPS PUB 180-4] of the binary content — i.e., content as is without any modifications like operating environment specific line-ending or encoding localizations — of the file. Must be given, if, and only if, needsChecksum="true". A given checksum must be correct; if it is not the SHA-1 hash of the file, the eFMU is invalid.

role

The role of the file in the model representation. This attribute is an enumeration with the following valid values:

- "Code": File containing code (Algorithm Code, Production Code or Binary Code).

- "Manifest": The manifest file itself.

- "FMU": One and only zip-file that is an FMU-container. Any version and any representation of an FMU can be used (for example FMI for ModelExchange, or FMI for CoSimulation, or FMU with a DLL, or an FMU with C-Code). This representation is useful to directly utilize the FMU in any FMI-compliant tool.

- "FMUFolder": The content of an FMU (so the files after unzipping an FMU). Any version and any representation of an FMU can be used. This representation is useful when an eFMU is stored in a version control system, such as github, gitlab or svn.

- "ReferenceData": File containing reference data (for example a csv file that stores reference values of variables).

- "other": All other files (for example an AUTOSAR description file *.arxml). Note, a description of the file can be stored in attribute description.

NOTE: The enumeration values have been selected such that each value may be used on an arbitrary level of abstraction, that is kind of model representation. In the future, more enumeration values might be added.

description

An optional description of the file (especially if role = \"other\").

ForeignFile

See below.

Example of a list of files:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<Files>
    <File id="ID_1" name         ="model.c"
                    path         ="./code/"
                    needsChecksum="true"
                    checksum     ="b4b84af148e587b95300d7a734302d1b912a6e58"
                    role         ="Code"/>
    <File id="ID_2" name         ="model.h"
                    path         ="./code/"
                    needsChecksum="true"
                    checksum     ="b4b84af148e587b95300d7a734402d1b911a6e58"
                    role         ="Code"/>
    <File id="ID_3" name         ="misra.doc"
                    path         ="./code/"
                    needsChecksum="true"
                    checksum     ="b4b84af148e587b95300d7a734302d1b914a6e58"
                    role         ="other"/>
    <File id="ID_4" name         ="model.arxml"
                    path         ="./code/"
                    needsChecksum="true"
                    checksum     ="b4b84af148e587b95300d7a734302d1b911a7e58"
                    role         ="other"/>
    <File id="ID_5" name         ="model.doc"
                    path         ="./description/"
                    needsChecksum="false"
                    role         ="other"/>
</Files>

2.3.4. Referencing

Referencing inside a model representation

Reference attributes pointing to entities in the same manifest must fulfill the naming convention that the attribute name consists of the original entity name and adding "RefId" as postfix. The value of the reference attribute must thereby be a valid id in the given context of the reference attribute, meaning that the id must exist in the context and be of the right type. For example a value of reference attribute variableRefId is an id number in the same manifest referencing a variable. In the Production Code Model Representation manifest file shown below, the DataReference with ID_100 references the variable T with ID_33 using the attribute variableRefId.

Referencing files

Files play a certain role in the eFMU model representation and are listed in a Files element of each manifest. Referencing files inside a model representation is done by using a FileReference element that comes along with Files and File element itself and not using a fileRefId attribute only. The reason to use a certain FileReference element is that the element comes along with a kind attribute of type string to allow for specifying the kind of a file in more detail.

FileReference
Name Description

fileRefId

Reference to the id in the file overview

kind

Attribute for a more detailed specification of the kind of file used. The list of allowed values is not predescribed but should follow the guideline ????

1
2
3
<CodeFile id="ID_13" fileType="ProductionCode">
    <FileReference fileRefId="ID_1" kind="SourceCode"/>
</CodeFile>

Note, that a FileReference attribute has no id attribute and therefore can’t be referenced. This prevents transitive file referencing.

Referencing into other model representation - ForeignReference (efmiManifestReferences.xsd)

The eFMU describes one model on different levels of abstraction. Thereby the level of abstraction decreases in the following order

  1. Behavioral Model

  2. Algorithm Code

  3. Production Code

  4. Binary Code

ForeignReference

In order to establish cross referencing between these model representations, the "derived" model representation must include a ManifestReference to that model representation as described above. The consistency to the referenced one is ensured as follows:

The manifestRefId is used to retrieve the (current) model representation checksum of the entry in the __content.xml file. This (current) checksum can be compared with the (stored) checksum that is part of the ManifestReference to ensure consistency; if the checksums are not equivalent, the referencing container is stale (i.e., the referenced container changed since the last update of this container).

In order to cross reference into a referenced container’s manifest, a ForeignReference element is present that has the following required two attributes:

Name Description

manifestReferenceRefId

The (manifest local) id of a ManifestReference.

foreignRefId

The id inside the referenced manifest file.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<ManifestReferences>
    <ManifestReference id           ="ID_1"
                       manifestRefId="{63f8c810-f008-47f0-a4b6-7a243f85e46b}"
                       checksum     ="e29810938a2a535dc8f6f9b8f51c5febe835ee05"
                       origin       ="true"/>
    ...
</ManifestReference>
 ...
        <Variable name        ="T"
                  id          ="ID_33"
                  typeDefRefId="ID_25"
                  pointer     ="false"
                  value       ="0.1"
                  const       ="false"
                  volatile    ="true"
                  static      ="false" />
        <Variable name        ="_Clocks_interval"
                  id          ="ID_34"
                  typeDefRefId="ID_25"
                  pointer     ="false"
                  value       ="0.005"
                  const       ="false"
                  volatile    ="true"
                  static      ="false" />
        <Variable name        ="gearRatio"
                  id          ="ID_35"
                  typeDefRefId="ID_25"
                  pointer     ="false"
                  value       ="105"
                  const       ="false"
                  volatile    ="true"
                  static      ="false" />
    ...
        <DataReferences>
            <DataReference id="ID_100" variableRefId="ID_33" >
                <ForeignVariableReference manifestReferenceRefId="ID_1" foreignRefId="ALG_ID_101"/>
            </DataReference>
            <DataReference id="ID_101" variableRefId="ID_34" >
                <ForeignVariableReference manifestReferenceRefId="ID_1" foreignRefId="ALG_ID_100"/>
            </DataReference>
            <DataReference id="ID_102" variableRefId="ID_35" >
                <ForeignVariableReference manifestReferenceRefId="ID_1" foreignRefId="ALG_ID_103"/>
            </DataReference>
	...

In the example above (a cut-out of a Production Code Model Representation manifest file), the manifestReferenceRefId attribute (with value "ID_1") identifies the ManifestReference as the one that references the Algorithm Code Model Representation with the Manifest id "63f8c810-f008-47f0-a4b6-7a243f85e46b" in the eFMU container and the foreignVariableRefId attribute the element in that container with the given id (e.g. "ALG_ID_102").

It has to be checked, that the referenced ids actually are valid and are used for the objects of the right type.

Important restriction: The names of a variable can differ in the manifests of the Behavioral Model, the Algorithm Code, and the Production Code. But for input and output variables of the eFMI block, that are defined in the Algorithm Code manifest, the structure (e.g. scalar or vector or matrix) has to be preserved over the different model representations. It means, an output vector y in the Algorithm Code manifest corresponds to a vector with the same length in all other model representations.

Referencing Files in Foreign Model Representations (efmiFiles.xsd)

In cases where a file in another model representation is used without change in the current model representation, one should use ForeignFile elements in the Files list.

ForeignFile
Name Description

id

The (manifest local) id.

ForeignReference

Identifying the foreign manifest and the file inside the manifest.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<ManifestReferences>
    <ManifestReference
        id="ID_0"
        manifestRefId="{63f8c810-f008-47f0-a4b6-7a243f85e46b}" checksum="e29810938a2a535dc8f6f9b8f51c5febe835ee05"
        origin="true"/>
    ...
</ManifestReference>
 ...
<Files>
    <File id="ID_1" name="model.c" path="./code"
          needsChecksum="true" checksum="e29810938a2a535dc8f6f9b8f51c5febe835ee05" role="Code"/>
    <File id="ID_2" name="model.h" path="./code"
          needsChecksum="true" checksum="e29810938a2a535dc8f6f9b8f51c6febe835ee05" role="Code"/>
    <File id="ID_3" name="misra.doc" path="./code"
          needsChecksum="true" checksum="e29810938a2a535dc8f6f9b8f51c5febe835ee06" role="other"/>
    <File id="ID_4" name="model.arxml" path="./code"
          needsChecksum="true" checksum="e29810938a2a535dc8f6f9b8f51c5febe835ee06" role="other"/>
    <File id="ID_5" name="model.doc" path="./description"
          needsChecksum="false" role="other"/>
    <ForeignFile id="ID_6">
        <ForeignFileReference manifestReferenceRefId="ID_0"
                              foreignRefId          ="ID_26" />
    </ForeignFile>
</Files>
Annotations

Optional, non-standardized, vendor-specific information — that a vendor might want to store and other vendors can ignore — are defined via <Annotation> elements in an optional <Annotations> list. The XSD is defined in efmiAnnotation.xsd and aligned to the corresponding elements of the FMI 3.0 standard:

Annotations

The only difference to FMI 3.0 is, that eFMI adds the additional reserved value "org.efmi-standard" for the type attribute of <Annotation> elements (besides the values already reserved in FMI 3.0).

2.3.5. Checksum calculation

The calculation of checksums is based on SHA-1 according to [FIPS PUB 180-4]. Checksums are computed based on binary content — i.e., content as is without any modifications like operating environment specific line-ending or encoding localizations.

The checksum is the mean to ensure integrity across different containers in an eFMU. These different container relate to each other and may be changed independent of each other. In order to ensure / check the integrity, with each change of a container, its checksum is updated in the reference entry in the __content.xml file.

For containers, that reference information from other containers or depend on them, also the checksum of these referenced containers is locally stored in that manifest. The comparison of these checksums is now an appropriate mean to check the consistency within the eFMU.

The calculation of checksums is done on the files that are listed in the manifest of the container (for which the needsChecksum attribute has the value "true") and the checksum is stored in the checksum attribute of the corresponding "File" list entry of the "Files" elememt of each manifest file.

The overall checksum of a model representation is the checksum of the manifest file, where all checksums of files of the model representation has been stored. Since the paths of the files are part of the manifest file itself it is ensured that a change of names, structure or content of the concerned files will result in a different checksum and allows for detecting changes, e.g. a model representation has been changed in the container, but has been taken as input for transformation tools before.

On the other hand, changes to files with attribute needsChecksum="false" (e.g. description files) will not affect the checksum as well as adding of files not listed in the manifest (listing in the manifest would also alter the checksum).

2.3.6. FMU File References

An eFMU container must be downward-compatible to an FMU container. Hence, it may have an FMU which is stored in the root directory of the container (above the "eFMU" directory). Such FMU needs to be associated with a certain model representation located in the eFMU container. In general, each model representation may have an optional FMU, especially a Production Code model representation.

The currently activated FMU needs to be specified in the __content.xml file by using the optional attribute activeFmu. If it is set, its value must correspond to the name of the associated model representation. If no FMU is unpacked currently, the value of this attribute must not be set.

The optional FMU of a model representation is specified within the manifest file of the model representation, where one and only one file in the list of files has the role attribute set to FMU. Its value must be a relative path inside the model representation to the FMU file.

When the FMU of a model representation M is activated, the following steps are performed:

  1. All files in the container’s root except the "eFMU" directory are removed.

  2. The FMU file referenced by M is unzipped to the container’s root.

  3. The value of the attribute activeFmu is set to the name of the model representation M.


3. Guarded Language for Embedded Control (GALEC)

3.1. Specification conventions

In addition to the common notational conventions about normative vs. non-normative text and referencing either (cf. [TODO-REFERENCE-COMMON-SPECIFICATION-CONVENTIONS]), the GALEC language specification uses further conventions that enable to write comprehensible, by humans readable normative text that is at the same time formally well-defined.

§1: Syntactic rule conventions

The textual syntax of GALEC programs is defined using extended Backus–Naur form (EBNF) according to [ISO/IEC 14977:1996]; respective syntax-rules are given in code listings of the form (cf. comment syntax-rule in §1 of Section 3.2):

1
2
3
4
5
6
7
comment =
    "/*",
    {
          { character } - ( { character }, ( "/*" | "*/" ), { character } )
        | comment
    },
    "*/" ;

In addition to [ISO/IEC 14977:1996], only a single syntax-rule exists for every non-terminal N that has N as meta-identifier. Prose text references to a non-terminal are therefore also references to a certain syntax-rule.

To avoid confusion of the overburdened term syntax — the question if syntax is only about the context-free grammar of a language or a definition of the whole language including further context-sensitive restrictions — and the thin line and nuances of syntax vs. semantic, we call [ISO/IEC 14977:1996] syntax-rules the syntactic rules of GALEC and only speak of syntax-rules if the context requires explicit reference to [ISO/IEC 14977:1996].

§2: Semantic rule conventions

Syntactic rules are further amended by semantic rules given in prose, which typically constrain the applicability of the syntactic rules they refer to. To reference a syntactic rule in prose text, the non-terminal defining it is used, highlighted in italic (e.g., comment). For readability reasons, every non-terminal can be used in plural or singular form and its first letter can be capitalized when used at the beginning of a sentence (e.g., comment, comments, Comment, and Comments all refer to the very same syntactic rule).

A non-terminal reference in prose text has a well-defined meaning besides just referencing a certain syntactic rule; it refers to a textual code fragment derived according to the referenced syntactic rule throughout the whole program derivation whereas all semantic rules are satisfied (the rules of the fragment itself as well as of other program parts). Formally, let N be a non-terminal reference within a semantic rule; let R be the syntactic rule defining N; N is a consecutive code fragment f of a whole program p, where f is derived according to R throughout the derivation of p and p satisfies all rules of the GALEC language specification.

We call such specification-abiding non-terminal references within semantic rules a syntactic term; they represent a valid code fragment of a GALEC program.

R-1 (language specifications are about valid programs only): The definition of semantic term might sound awkward. After all, semantic rules typically refer to syntactic rules for the reason to add further restrictions; to define that non-terminal references within such already imply their very own rules (besides others) seems to be self-referential. But it is no issue; the specification is still complete, correct, and sound. The semantic rule "N must satisfy condition c", where the reference to N implies that also all its conditions call = c ∧ crest must hold simply expands to "N must satisfy condition c and c ∧ crest" which is equivalent to "N must satisfy condition c and crest". The specification of GALEC is significantly eased however, because there is no need for semantic rules to handle the case that a referenced code fragment violates some other syntactic or semantic rule than the ones defined and of relevance at this part of the specification; hence, elsewhere defined syntactic relations (cf. §3) and semantic concepts of the fragment can just be used for the semantic rule at hand.

E-1 (power and implications of semantic terms): Semantic terms are a powerful concept with subtle implicit consequences. If, for example, the specification refers to loop-iterator-definitions, it is clear that this must be names declared by a for-loop regardless in which context the syntactic term loop-iterator-definition is used. This implication is given because loop-iterator-definition just derives to name and is only used by bounded-iteration which in turn is only used by for-loop.

This concept is, for example, heavily relied upon for the definition of a dimensionality analysis that guarantees upper bounded memory consumption and safe indexing of multidimensionals (cf. Section 3.8); it introduces a dedicated chain syntax-rule (constant-scalar-integer-expression), which is used as semantic term throughout the specification to enforce additional dimensionality-related semantic rules on all places such are of relevance.

§3: Syntactic relations used in semantic rules

Semantic rules often have to enforce or prohibit certain syntactic relations between program parts, i.e., that the derivation of some semantic term must be in a well-defined relation to the derivation of another throughout the whole program derivation (e.g., variable-definitions and references, cf. Section 3.7). To ease the specification of common cases, and enforce a consistent terminology, this section provides formal definitions for typical syntactic relations between syntactic terms. The defined relations are extensively used by semantic rules; readers of the GALEC specification should make themselves familiar with them.

Throughout the following definitions, italic highlighted Ni with i∈ℕ+ are syntactic terms according to §2.

Containment, nesting and closest: N1 is contained in N2, if, and only if, N1 is derived throughout the derivation of N2; in this case N2 is called a container of N1 and we say N2 contains N1 and N1 is part of N2. If, and only if, N2 contains N1 and both satisfy a common property X (any syntactic or semantic rule), N1 is called a nested X. Let N1 be contained in N2 and X and Y be properties satisfied by N1 and N2 respectively; N2 is the closest Y container of N1, if, and only if, there exists no N3 contained in N2 that also satisfies Y and contains N1; and N1 is the closest contained X of N2, if, and only if, there exists no N3 contained in N2 that satisfy X but is not contained in N1.

Exclusive containment: If, and only if, N2 contains N1, and throughout all possible derivations of the non-terminal N2 refers to the non-terminal N1 refers to can be derived at most once (i.e., considering all possible GALEC programs), we speak of the N1 of N2. In that case, let Y and X be the non-terminals N2 and N1 refer to respectively; obviously, N2 is the closest Y container of N1 and N1 the closest contained X of N2.

Preceding, following, siblings and equivalence: N1 is preceding N2, if, and only if, neither is contained in the other and the left-most derivation of the closest container of N1 and N2 derives N1 before N2; in this case N2 follows N1. Instead of preceding also the term before is used; and instead of follows also the term after. If, and only if, either, N1 follows N2 or N2 follows N1, both are siblings. N1 and N2 are different, if, and only if, they are siblings or the one contains the other.

Lexical equivalence: N1 is lexically-equivalent to a sequence of characters α, written N1 =lexical α, if, and only if, N1 derives to α. N1 is lexically-equivalent to N2, written N1 =lexical N2, if, and only if, N1 and N2 derive to the same sequence of characters.

Children and parent: Let d be a single-definition of the form β1, …​, βn or a definitions-list of the form β1 | …​ | βn according to [ISO/IEC 14977:1996]; βi with 1 ≤ i ≤ n is called the i'th factor of d. A δz is called the γ2-…​-γz'th factor of δ1, if, and only if, ∀i,j∈ℕ+; i = j - 1; 2 ≤ j ≤ z: δj is the γj'th factor of δi. Let R be the syntactic rule of N2. We call N1 the i1-…​-ik'th child of N2, if, and only if, N1 has been derived for the i1-…​-ik'th factor of R when deriving N2; in this case N2 is called the parent of N1. If, and only if, the i1-…​-ik'th factor of R has been derived when deriving N2, we say N2 has a i1-…​-ik'th child; otherwise it is without i1-…​-ik'th child. If N1 is the i1-…​-ik'th child of N2 and ∃r∈ℕ+; 1 ≤ r < k: r is a repeated-sequence, we also speak of the i1-…​-ik'th children of N2 (instead of child).

Nonexistence: N∃ is without a syntactic term according to some syntactic rule N∄, if, and only if, N∄ is not derived throughout the derivation of N∃; in this case, we say N∃ does not contain a N∄, it is N∄-free. Note, that semantic rules can define properties X of N∄ to further qualify which kind of term must not exist, i.e., N∄ is treated as semantic term for all purposes although it has not been derived or fails to satisfy X.

E-1: Consider the syntactic rule for constant-dimensions:

1
2
3
4
5
constant-dimensions =
    "[",
    ( derived-dimension | constant-scalar-integer-expression ),
    { ",", ( derived-dimension | constant-scalar-integer-expression ) },
    "]" ;

Its 1’st factor is "[", its 2’nd factor is ( derived-dimension | constant-scalar-integer-expression ), and its 2-1’st factor is derived-dimension. According to the presented syntactic rule, every constant-dimensions must have a 4’th child lexically-equivalent to ]. We can even distinguish between the 3-2-1’st children and 3-2-2’nd children; a constant-dimensions can be without 3-2-1’st children although it has a 3’rd child with 3-2’nd children (which are then all 3-2-2’nd children). And even without 3’rd child, a constant-dimensions can still contain a derived-dimension if it has a 2-1’st child (and therefore no 2-2’nd). If it is without 2-1’st child and 3-2-1’st children, it is without derived-dimensions — its is derived-dimensions-free — because constant-scalar-integer-expressions cannot derive such.

E-2: The following function-definition fragment defines various syntactic relations (denoted by using capitals only).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
[[ ⋯ ]]
algorithm
    /*
        For-loop CONTAINING another for-loop.
        Thus, neither for-loop is BEFORE or AFTER the other.
        Both for-loops are function-call-FREE:
    */
    for i in 1 : size(A, 1) loop
        /*
            If-statement PART OF a for-loop and CONTAINING a
            DIFFERENT for-loop. The if-statement is WITHOUT a
            function-call since it does NOT CONTAIN such:
        */
        if
            /*
                The 2'nd CHILD of the if-statement is an expression:
            */
            v[ i ] <> 0
        then
            /*
                NESTED for-loop, i.e., a for-loop CONTAINED in
                another for-loop. The NESTED for-loop FOLLOWS its
                CONTAINING if-statement's 2'nd CHILD:
            */
            for j in 1 : size(A, 2) loop
                /*
                    Assignment α PRECEDING another assignment β, with
                    which its 1'st CHILD is LEXICALLY-EQUIVALENT.
                    The assignment is also BEFORE another assignment γ
                    that is DIFFERENT to β; all three assignments are
                    SIBLINGS:
                */
                v[ i ] := A[ i, j ]; /* α */
            end for;
        else
            /*
                Assignment β AFTER a PRECEDING assignment α with
                LEXICALLY-EQUIVALENT 1'st CHILD:
            */
            v[ i ] := 1; /* β */
        end if;
    end for;
    /*
        Assignment γ not PART OF a for-loop, but for sure within
        a function-definition CONTAINER that trivially is its
        CLOSEST function-definition CONTAINER since GALEC does
        not support NESTED function-definitions:
    */
    A[size(A, 1), size(A, 2)] := -1; /* γ */
    [[ ⋯ ]]

3.2. Lexemes

GALEC programs are composed of characters (cf. §1) forming a sequence of white space, punctuation, literal, keyword, and name lexemes (cf. §1-4) that are subject to the longest match rule (cf. §5).

§1: Characters & white space

GALEC supports the Universal Coded Character Set (UCS, Unicode) according to [ISO/IEC 10646:2020] for program representation, with only line feed, tabulator, and space (and sequences thereof) as white space characters and non [INCITS 4-1986[R2022]] (US-ASCII) characters only within comments (the actual program is US-ASCII only). The respective [ISO/IEC 14977:1996] syntax-rules are:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
character = ? Any valid ISO/IEC 10646:2020 code point. ? ;

white-space = { space | new-line-character | comment } - ( ) ;

space =
      " " (* SPACE (ISO/IEC 10646:2020 code point 32). *)
    | ? CHARACTER TABULATION (ISO/IEC 10646:2020 code point 9). ? ;

new-line-character =
    ? LINE FEED (ISO/IEC 10646:2020 code point 10). ? ;

comment =
    "/*",
    {
          { character } - ( { character }, ( "/*" | "*/" ), { character } )
        | comment
    },
    "*/" ;

White space is universal; except for §1-4, { white-space } is implicitly preceding and following each syntactic-factor of a syntax-rule (cf. [ISO/IEC 14977:1996]).

E-1: The expanded rule of constant-dimensions, showing its implicit white-spaces, is:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
constant-dimensions =
	{ white-space },
	"[",
	{ white-space },
	(
		  { white-space }, derived-dimension, { white-space }
		| { white-space }, constant-scalar-integer-expression, { white-space }
	),
	{ white-space },
	{
		{ white-space },
		",",
		{ white-space },
		(
			  { white-space }, derived-dimension, { white-space }
			| { white-space }, constant-scalar-integer-expression, { white-space }
		)
	},
	{ white-space },
	"]"
	{ white-space } ;

E-2: According to E-1, the following is a valid constant-dimensions:

1
2
3
4
5
/* Lets define a matrix size: */
[
	: /* The first dimension is derived. */,
	3 /* The second fixed. */
]

E-3: The following is an illegal quoted-identifier due to white-space within its quotes:

1
2
3
4
5
'a . b [2 ] /* vector */
    .
    m [
3 , /* matrix access */ 4
]'

§2: Literals

GALEC supports Boolean, integer and floating-point literals, whereas floating-point literals must be in canonical form, such that two lexically non-equivalent floating-point literals indeed represent non-equivalent ℝ numbers:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
boolean = "false" | "true" ;

digit = (* ? Any ISO/IEC 10646:2020 code point in range [48, 57]: ? *)
    "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;

non-zero-digit = digit - ( "0" ) ;

integer =
      "0"
    | [ "-" ], positive-integer ;

positive-integer = non-zero-digit, { digit } ;

real =
      "0.0"
    | integer-place, decimal-places, [ exponent ] ;

integer-place = [ "-" ], non-zero-digit ;

decimal-places =
    ".",
    (* At least one digit followed by any sequence not ending with 0: *)
    digit,
    { digit } - ( { digit }, "0" ) ;

exponent = "e", ( "+" | "-" ), non-zero-digit, { digit } ;

literal = boolean | integer | real ;

The type and dimensionality of a literal is the type and dimensionality of its child. The type of boolean is Boolean, of integer and positive-integer it is Integer, and of real it is Real; their number of dimensions is 0.

Literals, booleans, integers, positive-integers and reals are called literals. A literal of type t is also just called a t.

Let l= be lexically-equivalent to a literal l; the value of l is l=.

R-1 (value of GALEC literals vs. ℤ and ℝ): Integer and real literals are distinguish from the mathematical concepts they are an abstraction of. For example, 1.3 denotes a Real whereas 1.3 is a real number of ℝ. An interpretation for further computation — e.g., in production code — likely maps 1.3 to a floating-point number close to, but still not equivalent to, 1.3. Likewise, 32768 is an Integer distinguish from 32768, a number within the set of integers ℤ. If Integer is mapped by later production code generation to signed 16-bit integers in two’s complement representation, the code generation will fail with an out-of-range error.

R-2 (canonical form of floating-point literals): To enforce a unique canonical form for floating-point literals, such that lexically non-equivalent floating-point literals indeed represent different values, has many advantages. For example, finding a magic number can be done without the need of regular expressions capturing all possible ways to denote the value as literal (e.g., 10 can be written 10.0, 10., 1.0e+1, 1e1, 0xA., 012., 10.00, 1E01, etc, in [ISO/IEC 9899:2024]). The GALEC notation also eases truncation when mapping to a specific floating-point precision for production code generation; and the originals of truncated values can be easily found. One example where truncation handling is required is to conduct Behavioral Model tests according to §4 of Section 5.2, where values must be truncated to the floating-point precision selected for testing. Using a unique canonical form also enforces a common style, that once used to, is easy readable.

R-3 (negative literals): Formal languages typically require the use of unary arithmetic negation to denote literal-based negative numbers. For example in [ISO/IEC 9899:2024] and [Modelica 3.7], -1.0 is not a literal but a unary arithmetic negation on the literal 1.0. GALEC, however, supports negative literals.

To have “native” negative literals aligns with common understanding and provides a simplified mental model. For example, §1.2 of Section 5.2 just refers to GALEC integers and reals for defining the syntax of values stored in reference trajectories files instead of having to deal with unary arithmetic operations of certain types. Another advantage is that literals can be checked as such for their value, for example, if it exceeds expected ranges or — considering GALEC floating-point literals must be in canonical form (cf. R-2) — to find magic numbers. Related to the latter, whitespace in the midst of literals is a non-issue in GALEC; code like -/* a negative number */3 or a * - 3 * b violates typical style guidelines anyway. And the requirement that the base of a power of operation must not be a negative literal (cf. §5.2:R-3 of Section 3.6) ensures a common denominator between GALEC and the [ISO/IEC 1539-1:2023] and [ISO/IEC 9899:2024] heritage of formal languages.

§3: Keywords & names

The names of GALEC entities that can be referenced like variables, functions, and error signals are clearly distinguished from its keywords. There are no context-dependent keywords or contexts in which keywords can be used as names.

Names are supported in two flavors, simple identifiers and quoted, with the latter enabling to encode structured qualifiers and query patterns as typical in many higher level modeling languages like [Modelica 3.7] into the name; this enables traceability for generated GALEC programs (cf. R-1).

The respective [ISO/IEC 14977:1996] syntax-rules are:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
keyword =
      "block" | "protected" | "public" | "end"
    | "function" | "signals" | "algorithm"
    | "input" | "output" | "parameter" | "constant"
    | "Boolean" | "Integer" | "Real"
    | "limit"
    | "if" | "signal" | "in" | "then" | "elseif" | "else"
    | "for" | "loop"
    | "not" | "not." |
    | "and" | "or" | ".and" | ".or" | "and." | "or." | ".and." | ".or."
    | "false" | "true"
    | "size"
    (* Reserved for future extensions: *)
    | "while" | "do" | "until"
    | "break" | "return"
    | "record"
    | "enumeration"
    | "_", [ simple-identifier | keyword ] ;

name = simple-identifier | quoted-identifier ;

simple-identifier =
    (
        alphabetic-character,
        { alphabetic-character | "_" | digit }
    ) - ( keyword ) ;

alphabetic-character =
    (* ? Any ISO/IEC 10646:2020 code point in ranges [65, 90] or [97, 122]: ? *)
      "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m"
    | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"
    | "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M"
    | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" ;

quoted-identifier = "'", quoted-identifier-qualifier, "'" ;

quoted-identifier-qualifier =
    quoted-identifier-element,
    [ quoted-identifier-dimensions ],
    { ".", quoted-identifier-element, [ quoted-identifier-dimensions ] } ;

quoted-identifier-element =
    (
        [ simple-identifier | keyword ],
        [ quoted-identifier-group ]
    ) - ( ) ;

quoted-identifier-group =
    "(",
    quoted-identifier-qualifier,
    { ",", quoted-identifier-qualifier },
    ")" ;

quoted-identifier-dimensions =
    "[",
    positive-integer,
    { ",", positive-integer },
    "]" ;

Names, simple-identifiers and quoted-identifiers are primitive names. Let α be lexically-equivalent to a primitive name N; α is the name of N. Syntactic terms with a name are called named. Let α be the name of a named syntactic term N; we say N has name α and N is named α.

Note, that §1-2 of Section 3.3, §2 and §4 of Section 3.6, and §3 of Section 3.5 extend the set of named syntactic terms by defining the names of definitions, variable references, function calls, and loop iterators based on above definition.

R-1 (complex source model entities and quoted-identifiers): The (physics) source models from which GALEC code stems often support structured entities with special query patterns. The data model of GALEC is deliberately very restricted however. Quoted-identifiers resembling the names and query patterns of such complex source model entities can be used to achieve traceability, i.e., denote source model origins in a unique and elucidating way in the spirit of literate and elucidative programming.

[Modelica 3.7] for example supports nested packages, models, records, and components with qualified names of arbitrary dimension (qualified multidimensional entities); [Modelica 3.7] tooling also typically flattens multidimensional entities to individual scalar entities for further numeric optimization. And the special der and pre operators can be used to denote the derivative of an entity or its value right before event iteration respectively. Using quoted-identifiers, these [Modelica 3.7] concepts can be mapped to respective GALEC variables intended to hold their value (which of course still must be computed by algorithmic means accordingly).

Note, that quoted-identifiers still enforce rules on the characters and structures that are permitted within their ' quotes. The quoted-identifier-elements separated by . within quoted-identifier-qualifiers can be used for separating the individual path-elements of complex names (qualified names); [ and ] of quoted-identifier-dimensions can be used to resemble indexing within multidimensions; and the quoted-identifier-qualifiers separated by , within ( and ) of quoted-identifier-groups can be used to list function arguments or group nested qualifiers. The intention of such structured names is to enable further processing; for example, automatic grouping according to the underlying original model structure a quoted-identifier assumably resembles.

E-1: Assume a GALEC variable shall represent the return value of the 3'rd element of a function call f(x, y) that is within an equation of the ci component of the 2'nd c component of a [Modelica 3.7] model, whereas x is a variable of the model and y is the derivative of the v field of a record instance r of the model. A respective GALEC variable could be named 'c[2].ci.f(x,der(r.v))[3]'.

E-2: The various x instances of the [Modelica 3.7] model

1
2
3
4
5
6
7
model A
    B a[2];
    model B
        C b[2];
        record C
            Real x[2];
    [[ arbitrary further declarations and equations defining all entities ]]

could be represented by GALEC variables

1
2
3
4
5
/* Each variable is a vector of size 2: */
Real 'a[1].b[1].x'[ 2 ];
Real 'a[1].b[2].x'[ 2 ];
Real 'a[2].b[1].x'[ 2 ];
Real 'a[2].b[2].x'[ 2 ];

respectively. Assuming that the first element of each is not used, a [Modelica 3.7] tool generating GALEC code could scalarize x completely and only generate the GALEC scalars

1
2
3
4
5
/* Each variable is a scalar: */
Real 'a[1].b[1].x[2]';
Real 'a[1].b[2].x[2]';
Real 'a[2].b[1].x[2]';
Real 'a[2].b[2].x[2]';

If we assume, the equations of the model use the derivatives of a[2].b[1].x, likewise named GALEC variables to hold the values would be Real 'a[2].b[1].der(x)'[ 2 ] or Real 'a[2].b[1].der(x[1])' and Real 'a[2].b[1].der(x[2])' respectively (the former if x is preserved as vector, the latter two if scalarized).

R-2 (reserved keywords): Keyword reserves certain character sequences for future language extensions; the respective sequences are not used elsewhere in the grammar.

The sequences while, do and until are reserved for a potential future introduction of non-bounded or more complicated loops, return and break for potential early function and loop exit statements, and record and enumeration for a potential extension with record and enumeration types. The keywords starting with _ (underscore) reserve names that might collide with internal compiler macros of further tooling; it is in the spirit of 6.11.7 of [ISO/IEC 9899:2024].

Such reservations do not imply by any means that the language indeed will be extended accordingly; they rather serve to preserve up-wards compatibility of code when respective language extensions are added.

E-1: Boolean break; is not a variable-definition due to break being a reserved keyword.

§4: Punctuation

Any character sequence not matched by §1-3 throughout the left-most derivation of a GALEC program is called a punctuation lexem, or just punctuation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
punctuation =
      "["  | "]"  | "{"  | "}"  | "("  | ")"
    | "."  | ","  | ":"  | ";"  | ":=" | ":=!"
    |  "+"  |  "-"  |  "*"  |  "/"  |  "^"
    | ".+"  | ".-"  | ".*"  | "./"  | ".^"
    |  "+." |  "-." |  "*." |  "/." |  "^."
    | ".+." | ".-." | ".*." | "./." | ".^."
    | "**"
    |  "<"  |  ">"  |  "<="  |  ">="  |  "=="  |  "<>"
    | ".<"  | ".>"  | ".<="  | ".>="  | ".=="  | ".<>"
    |  "<." |  ">." |  "<=." |  ">=." |  "==." |  "<>."
    | ".<." | ".>." | ".<=." | ".>=." | ".==." | ".<>." ;

R-1 (punctuation lexemes): The syntax-rule for punctuation is not required except for the definition of §5. Punctuation is not referenced by any other syntax-rule; instead punctuation lexemes are denoted by their respective terminal-string whenever needed.

§5: Longest match

GALEC lexemes are subject to longest match. For every left-most derivation of any GALEC program p according to the syntax-rules of GALEC, it must hold that the sequence of applications of the syntax-rules defined in §1-4 is the same as the sequence of §1-4 applications by the left-most derivation of p according to the [ISO/IEC 14977:1996] EBNF grammar Glexemes = { ? all meta-identifiers of §1-4 concatenated by | ? }, whereas Glexemes has the following longest match rule restricting the applicability of its syntax-rules.

Longest match rule: Let αβγδ be an arbitrary GALEC program p, with α being an arbitrarily long sequence of characters matched throughout a left-most derivation of p according to Glexemes, β and γ being arbitrary long but not empty sequences of characters, and δ being an arbitrary long sequence of characters. Let s1 and s2 be any two different syntax-rules of §1-4 that can be applied next throughout the left-most derivation of p according to Glexemes. Assume s1 would match β and s2 would match βγ; in that case s1 is not applicable.

E-1: Let α, β, γ and δ be as defined above, with α = block/**/, β = i, γ = 4, and δ starts with /*. The next syntax-rule applied must be name and it must match βγ; just matching β with name violates the longest match rule.

3.3. Blocks and definitions

§1: Variable definitions

A variable-definition v of the form

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
variable-definition =
    [ variable-causality ],
    variable-type,
    name,
    [ constant-dimensions ],
    ";" ;

variable-causality = "constant" | "parameter" | "input" | "output" ;

variable-type = "Boolean" | "Integer" | "Real" ;

constant-dimensions =
    "[",
    ( derived-dimension | constant-scalar-integer-expression ),
    { ",", ( derived-dimension | constant-scalar-integer-expression ) },
    "]" ;

derived-dimension = ":" ;

defines a variable with a certain name, causality, type, and dimensionality.

The name of v is the name of its 3rd child (name, cf. §3 of Section 3.2). The causality of v is state if the first child is empty, otherwise lexically-equivalent to the contained variable-causality. The type of v is lexically-equivalent to the contained variable-type.

Let s be the number of children of the 3rd child of the constant-dimensions of v; if v has no constant-dimensions, s = -2. The number of dimensions n of v is 1 + (½ × s), and we say v is n-dimensional; the size of each dimension is according to §4 of Section 3.8. If the number of dimensions of v is 0, v is scalar; otherwise it is multidimensional. Scalar variables are also just called a scalar; multidimensional variables a multidimension. If v is 1-dimensional it is called vector; if it is 2-dimensional matrix. The first dimension of a matrix is called its rows, the second its columns.

Variable-definitions are also just called variable; and a variable v with name n and of causality c is just called a c (e.g., an input, output or parameter) and we say n is a c.

§2: Function definitions

A function-definition f of the form

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
function-definition =
    "function",
    name,
    [ error-signal-interface ],
    (* Local inputs, followed by local outputs: *)
    { public-function-variable-definition },
    "protected",
    (* Local states: *)
    { protected-function-variable-definition },
    "algorithm",
    statement-sequence,
    "end",
    name,
    ";" ;

public-function-variable-definition = variable-definition ;

protected-function-variable-definition = variable-definition ;

defines a function with a certain name, algorithmic implementation, and signature, i.e., signaled errors (cf. §1.3: Functional error interface and exposed error signals), inputs, outputs, and their types and dimensionalities (cf. Section 3.8).

The two name children of f must be lexically-equivalent and are the name of f.

The causality of the variable-definition of a public-function-variable-definition must be input or output; for protected-function-variable-definitions it must be state. The variables of either are called local variable (of f); §3 of Section 3.5 extends the set of local variables of f by its loop iterators.

The local variables of a function-definition must be ordered: first local inputs, followed by local outputs, followed by local states (and — enforced by syntactic rules — followed by loop iterators).

Let S>f be the set of the local inputs of f; let Sf> be the set of local outputs of f. The inputs of f are the tuple T>f = (p1,…​,pn) with n = |T>f| = |S>f| and ∀pi,pj∈T>f; i,j∈ℕ+; i < j ≤ n: pi∈S>f ∧ pj∈S>f ∧ pi is preceding pj; likewise, the outputs of f are the tuple Tf> = (q1,…​,qm) with m = |Tf>| = |Sf>| and ∀qi,qj∈Tf>; i,j∈ℕ+; i < j ≤ m: qi∈Sf> ∧ qj∈Sf> ∧ qi is preceding qj. The input-arity of f is n; its output-arity is m. A local input of f is called the i'th input, if, and only if, it is the i'th element of T>f; likewise, a local output of f is called the i'th output, if, and only if, it is the i'th element of Tf>.

Function-definitions are also just called function (such that we can speak of the name of a function, its inputs and outputs, the type and dimensionality of its 3’rd output, etc). Since their names must be unique (cf. Section 3.7), we also denote a function simply by its name suffixed with an open and closed parenthesis (e.g., DoStep()).

§3: Blocks (GALEC programs)

A block b of the form

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
block =
    "block",
    name,
    (* Block inputs, followed by block outputs, followed by tunable parameters: *)
    { public-block-variable-definition },
    "protected",
    (* Block constants, dependent parameters, and block states in any order: *)
    { protected-block-variable-definition },
    { error-signal-definition },
    { protected-function-definition },
    "public",
    { public-function-definition },
    "end",
    name,
    ";" ;

public-block-variable-definition = variable-definition ;

protected-block-variable-definition = variable-definition ;

protected-function-definition = function-definition ;

public-function-definition = function-definition ;

is, according to [ISO/IEC 14977:1996], the start symbol of GALEC; it is a GALEC program.

The two name children of b must be lexically-equivalent and are the name of b.

The causality of the variable-definition of a public-block-variable-definition must not be constant or state; for protected-block-variable-definitions it must not be input or output. The variables of either are called block variable.

Block variables with causality parameter are called tunable, if they are part of a public-block-variable-definition; otherwise they are called dependent.

The block variables of a block must be ordered: first block inputs, followed by block outputs, followed by tunable parameters, followed by any order of block constants, dependent parameters and block states.

The variables of a block are distinguished into block-interface and internal variables, whereas the latter can be block-internal or local variables (cf. §2 of Section 3.4).

The functions within a block are called user-defined (in opposite to built-in functions, cf. Section 3.11). They are further distinguished into block-interface and block-internal functions (cf. §3 of Section 3.4).

E-1: The following block has one of each, a block constant, block input, block output, tunable parameter, dependent parameter, block state, and a function 'Update(bs)' with a local input, local output, and local state of various types and dimensionalities:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
block B
    /* Scalar block input named bi: */
    input Integer bi;
    /* Multidimensional block output named bo with 1 dimension: */
    output Real bo[ 3 ];
    /* Multidimensional tunable parameter named 'b[1].tp' with 2 dimensions: */
    parameter Real 'b[1].tp'[ 3, 3 ];

protected
    /* Scalar block constant named 'b[1].c[2,1]': */
    constant Real 'b[1].c[2,1]';
    /* Multidimensional dependent parameter named bdp with 2 dimensions: */
    parameter Real bdp[ 3, 3 ];
    /* Multidimensional block state named bs with 2 dimensions: */
    Real bs[ 3, 3 ];

    function 'Update(bs)'
    /* Local variables: */
        /* Scalar local input: */
        input Real li;
        /* Scalar local output: */
        output Boolean lo;
    protected
        /* Multidimensional local state with 2 dimensions: */
        Real ls[ size(block.bdp, 1), size(block.bs, 2) ];
    algorithm
        ls := li * (block.bdp * block.bs);
        lo := allFinite2D(ls);
        block.bs := (if lo then ls else block.bs);
    end 'Update(bs)';

public
    function InitializeConstants
    protected
    algorithm
        block.'b[1].c[2,1]' := 2.0e+1 * pi();
    end InitializeConstants;

    function InitializeTunableParameters
    protected
    algorithm
        block.'b[1].tp' := {
            { -1.0, 1.0, 1.903 },
            { 1.1, -1.005, 1.9e-1 },
            { 1.27, 1.5, -2.021e-10 }};
    end InitializeTunableParameters;

    function InitializeDependentParameters
    protected
    algorithm
        block.bpd := block.'b[1].c[2,1]' * block.'b[1].tp';
    end InitializeDependentParameters;

    function InitializeInputs
    protected
    algorithm
        block.bi := 1;
    end InitializeInputs;

    function InitalizeStatesAndOutputs
    protected
    algorithm
        block.bs := {
            { 1.0, 1.0, 1.0 },
            { 1.0, 1.0, 1.0 },
            { 1.0, 1.0, 1.0 }};
        block.bo := { 0.0, 0.0, 0.0 };
    end InitalizeStateAndOutput;

    function DoStep
    protected
    algorithm
        if 'Update(bs)'(real(block.bi)) then
            block.bo := block.bs * { 1.0, 1.0, 1.0 };
        end if;
        if signal in OVERFLOW /* by real(block.bi) */ then
            /* ±∞ li input correctly handled by 'Update(bs)'. */
        end if;
    end DoStep;
end B;

3.4. Block-interface and life-cycle

This Section investigates the utilization of GALEC programs (i.e., blocks) that are due for deployment in a target environment (i.e., specific hardware and software setup) — it defines a general scheme for the system integration of eFMUs.

§1: Target environment, system integration, block instance & block-interface

GALEC defines an operational interface for blocks — called block-interface — that can be used for system integration. System integration thereby means any kind of required interaction to utilize a block within a target environment, typically instantiations, calibrations, and samplings (i.e., provisioning the new inputs from the target environment, computing the resulting states and outputs, and provisioning the new outputs to the target environment).

A single block can be instantiated many times within a target environment; each instance is operationally isolated (i.e., has its own state — its own set of variable values on which its functions operate). There are no restrictions on the number or kind of block instances (different blocks, the same block, or any combination thereof can be instantiated arbitrarily often within the same target environment).

Any interaction of the target environment with a block instance must be via its block-interface (even instances of the same block must interact via their block-interface). The block-interface of a block constitutes of its block-interface variables and block-interface functions; interactions with it must adhere to §2-4.

R-1 (system integration of production code according to GALEC block-interface): Production Code containers do not have to verbally follow the GALEC block-interface as described by the manifest of the Algorithm Code container they are linked to (cf. Chapter 4 and Chapter 6). Production code can be highly tailored for various target environments and therefore has no standardized interface. However, the manifest of a Production Code container defines the production code entities implementing the block-interface of its linked Algorithm Code manifest. It is via this mapping that production code can be system integrated in accordance with §2-4.

§2: Block-interface variables

The block-interface variables of a block are its constant, input, output, and parameter (tunable and dependent) block variables. Variables that are not block-interface variables are called internal (and according to §1 are not visible for interaction with the target environment). Internal variables that are also block variables are called block-internal variables.

R-1 (intended purpose of variables): The intended purpose of block-interface variables is:

  • Block constant: Variable whose value never changes after initialization and which will always initialize to the very same value for a given target environment.

  • Tunable parameter: Parameter available for tuning by the target environment; can be changed occasionally, and not necessarily, before or after sampling.

  • Dependent parameter: Parameter whose value is derived from tunable parameters and therefore must be recomputed whenever any tunable parameter changes.

  • Block input: Input provisioned by the target environment for each sampling.

  • Block output: Result provisioned to the target environment by each sampling. Like block states (see below), also block outputs can model inner state.

Local variables and block states are the only kind of internal variables, whereas only block states are block-internal (with emphasize on the block root of the compound block-internal). The intended purpose of internal variables is:

  • Block state: Variable modeling an inner state, i.e., a value that must be preserved from one sampling to the next, enabling samplings to not only depend on block inputs and parameters but rather also depend on previous samplings or influence future samplings.

  • Local variable: Variable whose value does not have to be preserved from one sampling to the next.

Block variables (regardless if block-interface or block-internal) are persistently stored in block instances, such that their values survive block-interface function calls and therefore can be used in call sequences of such. Each block instance has its individual set of variable values (e.g., changing some tunable parameter t of a block instance b1 does not change t of another block instance b2 of the same block).

The block-interface variables of a block instance must not be read or written by the target environment while any of its block-interface functions is in execution. Different block-interface variables of a block instance can be read and written concurrently by the target environment; concurrent reading and writing of the same variable is prohibited. The block-interface variables of separate block instances can be read and written concurrently by the target environment. Block constants, dependent parameters and block outputs must never be written by the target environment. Any read/write interactions of the target environment that are not explicitly forbidden by §2-4 are permitted (e.g., the target environment can query the block inputs and tunable parameters of a block instance for their values).

§3: Block-interface functions

The block-interface functions of a block are the functions declared within its public-function-definitions (cf. §3 of Section 3.3); the functions within its protected-function-definitions are called block-internal (and according to §1 are not visible for interaction with the target environment).

Block-interface functions must be without local in- or outputs. A block must have exactly the following six block-interface functions (for a definition of inter-functional∃/∀ and value-reference-only-after-assigning, cf. §1 of Section 3.9; for a definition of assign to and value-reference, cf. §2 of Section 3.5 and §2 of Section 3.6 respectively):

  1. InitializeConstants: Must inter-functional∀ value-reference-only-after-assigning assign to all block constants. Must not inter-functional∃ assign to or value-reference any other block variables than constants. The target environment must never read block constants before having called this function at least once.

  2. InitializeTunableParameters: Must inter-functional∀ value-reference-only-after-assigning assign to all tunable parameters; must not inter-functional∃ assign to any other block variables than tunable parameters. Must not inter-functional∃ value-reference to any other block variables than constants or tunable parameters. The target environment must never read tunable parameters before either, having them written or having called this function at least once.

  3. InitializeDependentParameters: Must inter-functional∀ value-reference-only-after-assigning assign to all dependent parameters; must not inter-functional∃ assign to any other block variables than dependent parameters. Must not inter-functional∃ value-reference to any other block variables than constants, tunable parameters or dependent parameters. The target environment must never read dependent parameters before having called this function at least once.

  4. InitializeInputs: Must inter-functional∀ value-reference-only-after-assigning assign to all block inputs; must not inter-functional∃ assign to any other block variables than inputs. Must not inter-functional∃ value-reference to any other block variables than constants, parameters or inputs. The target environment must never read block inputs before either, having written them or having called this function at least once.

  5. InitializeStatesAndOutputs: Must inter-functional∀ value-reference-only-after-assigning assign to all block states and block outputs; must not inter-functional∃ assign to any other block variables than states and outputs. The target environment must never read block outputs before having called this function at least once.

  6. DoStep: Must not inter-functional∃ assign to any other block variables than states and outputs.

The first five functions are called initialization functions; DoStep() is called sampling function. Calling InitializeDependentParameters(), InitializeStatesAndOutputs() or DoStep() is also called recalibration, reinitialization or sampling respectively and we say that the respective block instance is recalibrated, reinitialized or sampled.

R-1 (limitation on six pre-declared block-interface functions): The limitation that no other functions than the current six block-interface functions can be exposed for interaction with the target environment will be likely removed in future versions of the standard. Doing so requires extensions of the Algorithm Code manifest however, to describe function signatures with in- and outputs; and likely further semantic restrictions of the block life-cycle to ensure correct interplay with block variables and initialization.

The block-interface functions of a single block instance must be called in sequence by the target environment; concurrent execution of such is prohibited. The block-interface functions of separate block instances can be executed in concurrently.

§4: Block life-cycle

The permitted interactions of the target environment with a block instance via its block-interface are further restricted by the following state machine, specifying a universal life-cycle for block instances, called block life-cycle:

block life cycle

The block life-cycle state machine is defined from the perspective of a block instance deployed in a target environment conducting all computations (whether block instance related or not):

  1. The state actions that are function calls (e.g., DoStep() of state "sampling") mean that the respective block-interface function of the block instance is executed by the target environment.

  2. The transitions are events only. All named transitions are triggered by the target environment. All unnamed transitions are implicitly triggered when the action of their source state finished.

  3. The states of the state machine are the internal statuses in which the block instance can be (they say nothing about the target environment). For example, any of the "idle" states means that the block instance is doing nothing; none of its functions is in execution (but the target environment could be busy executing a block-interface function of some other block instance or compute anything else unrelated to this block instance). And state "initializing (dependent)" means that the block instance is recalibrating, i.e., its InitializeDependentParameters() function is busy recomputing all dependent parameters (while the target environment could perform additional computations, unrelated to this block instance, concurrently).

Due to 1-3, time is only spent in states, but not transitions.

According to the block life-cycle state machine, initialization functions must have been executed in sequence before any sampling (i.e., DoStep() call). And whenever a tunable parameter is set, the InitializeDependentParameters() function must have been executed at least once before the next sampling (such that, according to §3, all dependent parameters are recalibrated); otherwise, a protocol error is given and the block behavior is undefined ("idle (protocol error)" state). Several tunable parameter changes can be bundled though; it is not necessary to execute InitializeDependentParameters() after setting each individual new tunable parameter (although it is permitted to call it arbitrary often, even if tunable parameter values are unchanged), but sufficient to do so once for all before the next sampling. Likewise, the values of block inputs have to be set — i.e., either updated or deliberately reset via InitializeInputs() by the target environment, or concluded to be still valid for the next sampling — before calling DoStep(); if a block input is not explicitly set by the target environment before a sampling, it simply has its previous value (which might be its initialization value). It is also the target environment’s responsibility to conduct samplings in time, executing DoStep() exactly once for each "sampling clock ticks" event; and ensure — according to §3 — no previous block-interface function calls, including previous samplings, are still in execution.

R-1 (onion-layered causality between the different kinds of block variables): The assign and reference restrictions of block-interface functions (cf. §3), together with the call-order restrictions of the block life-cycle state machine regarding initialization, recalibration, and sampling, define onion-layered causalities (and therefore vice-versa dependencies) between the different kinds of block variables and block-interface functions. The design guarantees for example, that sampling can use constants, tunable parameters and dependent parameters, but never change their values. Likewise, tunable parameters can be set to constant values for their initialization, and the values of dependent parameters can in turn be derived by complex algorithms from tunable parameters.

These well-defined causalities guarantee well-defined degrees of variability as required by typical applications of sampled systems. Block inputs, states and outputs have the highest variability; they are provisioned anew and recomputed respectively each sampling. Tunable and dependent parameters have the next-lower level of variability; they are only provisioned anew and recomputed respectively throughout recalibration. Constants naturally have the lowest level of variability.

If tunable parameters or block inputs are not explicitly set by the target environment before calling InitializeDependentParameters() and InitializeStatesAndOutputs() respectively, the call-sequence (1) InitializeConstants(), (2) InitializeTunableParameters(), (3) InitializeDependentParameters(), (4) InitializeInputs() and (5) InitializeStatesAndOutputs() is called default initialization. For a given target environment, default initialization will always yield the same initial values for all block variables.

R-2 (default vs. input-dependent initialization): The target environment can skip default initialization of tunable parameters via InitializeTunableParameters() by explicitly provisioning an initial value for every tunable parameter or changing the value of some tunable parameters after the last InitializeTunableParameters() call. This can result in block inputs not being default initialized, if InitializeInputs() uses tunable or dependent parameters. And even if tunable parameters are default initialized, block inputs might not be if the target environment provisions explicit values for such before calling InitializeStatesAndOutputs(); in particular, the InitializeInputs() call can be skipped if initial values are explicitly provisioned by the target environment for every block input.

This enables input-dependent initialization, which can be essential to avoid instabilities in case of physical environments with various starting conditions. A typical example are highly fluctuating ambient temperatures — there might be no reasonable default value to initialize temperature dependent states. Any assumed default value might cause initial block states to be to far off from reality such that the block instance requires many samplings (i.e., a significant time period) to swing-in or worse never stabilizes.

R-3 (design-space of production code and system integration): Production Code generators and further system integration are free to realize a GALEC block by any means they see fit as long as its operational semantic is satisfied. They can — matching the application requirements — achieve a mutual agreement that block-interface functionality is not supported, like recalibration or reading of block constants, tunable parameters, or inputs from the target environment, given that the use-case and system integration scenario does not require such. In general however, Production Code generators must support the full block-interface and life-cycle to be eFMI Standard compliant.

Examples of system integration scenario specific design-space agreements are:

  1. Not generate and call the five initialization functions, but instead statically execute them in sequence and store the default start values in read only memory of the target environment or only load them once when the target environment boots.

  2. Not generate a dedicated DoStep() function, but instead inline the implementation in the target environment.

  3. Not write tunable parameters from the target environment, transforming tunable and dependent parameters to become constants which can be constant-folded.

  4. Store block variables globally, leveraging on knowing that there is exactly one instance and not several (no need to support individual block-instances).

  5. Not persistently store block inputs in block instances (cf. §2), but instead provide new values for every input at each sampling, for example as function arguments to DoStep().

  6. Not support reading block constants, tunable parameters or inputs from the target environment, considering that such either never change or are anyway provided by the target environment in the first place.

  7. Not support reading dependent parameters from the target environment even if recalibration is supported; nevertheless, dependent parameters still must be updated according to the block life-cycle and can respectively influence block states and outputs when sampling.

Particularly (3) is a common integration scenario, since recalibration typically is only performed during the development phase of a cyber-physical system and no longer supported in production systems.

E-1: The following [ISO/IEC 9899:2024] pseudo-code snippets sketch typical system integration scenarios for blocks.

All examples share the following conventions. It is assumed that the Production Code generator mapped the block-interface functions to equally named [ISO/IEC 9899:2024] functions that expect the block variables to operate on as argument, e.g., a struct-pointer; to that end, c is a pointer to the struct holding the values of all block variables (it encapsulates the state of a block instance). Prose text bracket by [[ and ]] is pseudocode; it denotes arbitrary [ISO/IEC 9899:2024] code implementing the respective action, but does not interact any further with the block-interface and c than denoted.

The most common integration scheme, with default initialization and support for recalibration throughout samplings, is:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*
    Default initialization, assigning every block variable a value:
*/
InitializeConstants(c);
InitializeTunableParameters(c);
InitializeDependentParameters(c);
InitializeInputs(c);
InitializeStatesAndOutputs(c);
[[ process initial default block outputs ]]

/*
    Sampling cycle:
*/
while ([[ block not shutdown ]])
{
    if ([[ recalibration desired ]])
    {
        [[ set new tunable parameters ]]
        InitializeDependentParameters(c); /* Recompute dependent parameters. */
    }
    [[ set new block inputs ]]
    [[ wait until sampling clock ticks ]]
    DoStep(c); /* Recompute block states and outputs. */
    [[ process new block outputs ]]
}

A more simple integration scenario may not utilize recalibration throughout sampling, but only once throughout initialization to set (specific) tunable parameters:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
/*
    Initialization with non-default tunable parameters:
*/
InitializeConstants(c);
InitializeTunableParameters(c); /* Can be skipped if all are set explicitly. */
[[ set new tunable parameters ]]
InitializeDependentParameters(c);
InitializeInputs(c);
InitializeStatesAndOutputs(c);
[[ process initial non-default block outputs ]]

/*
    Sampling cycle:
*/
while ([[ block not shutdown ]])
{
    [[ set new block inputs ]]
    [[ wait until sampling clock ticks ]]
    DoStep(c); /* Recompute block states and outputs. */
    [[ process new block outputs ]]
}

An even more simple integration scenario may not require recalibration at all, effectively transforming tunable and dependent parameters to constants since they cannot change after initialization. A Production Code generator can optimize this scenario, leveraging on enhanced constant-folding. The respective initialization functions can be statically executed, and the computed values stored as read-only data:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/*
    Default initialization assuming the initial values of block constants,
    tunable parameters and dependent parameters are already stored in
    read-only data segments :
*/
InitializeInputs(c);
InitializeStatesAndOutputs(c);
[[ process initial default block outputs ]]

/*
    Sampling cycle:
*/
while ([[ block not shutdown ]])
{
    [[ set new block inputs ]]
    [[ wait until sampling clock ticks ]]
    DoStep(c); /* Recompute block states and outputs. */
    [[ process new block outputs ]]
}

An advanced integration scenario might also require several different recalibrations and input modifications depending on the state of the target environment:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
    Initialization with non-default tunable parameters and block inputs:
*/
InitializeConstants(c);
[[ set and process initial non-default tunable parameters ]]
InitializeDependentParameters(c);
[[ process initial non-default dependent parameters
   set and process initial non-default block inputs ]]
InitializeStatesAndOutputs(c);
[[ process initial non-default block outputs ]]

/*
    Sampling cycle:
*/
while ([[ block not shutdown ]])
{
    /* Handle default setup: */
    [[ set new block inputs ]]

    /* Handle first special case, modifying the default: */
    v1 = [[ some value provided by the target environment ]];
    t1 = [[ read tunable parameter t1 ]];
    o1 = [[ read block output o1 ]]; /* Previous sampling, or initial if first. */
    if (o1 / t1 > v1)
    {
        [[ set block input i1 to v1 ]]
        if (t1 > 2*v1)
        {
            [[ set tunable parameter t1 ]]
            InitializeDependentParameters(c); /* Recompute dependent parameters. */
        }
    }

    /* Handle second special case (may amend the first): */
    v2 = [[ some value provided by the target environment ]];
    t2 = [[ read tunable parameter t2 ]];
    if (t2 < v2)
    {
        [[ set tunable parameter t2 ]]
        InitializeDependentParameters(c); /* Recompute dependent parameters. */
        [[ set block input i2 to some dependent parameter ]]
    }

    /* Everything is prepared for next sampling: */
    [[ wait until sampling clock ticks ]]
    DoStep(c); /* Recompute block states and outputs. */
    [[ process new block outputs ]]
}

3.5. Statements

The algorithmic instruction répertoire of GALEC is very concise with only five kinds of statements (cf. §1) that can be categorized into tasks related to computing new variable values (i.e., assignment, cf. §2) and selecting between program execution alternatives (i.e., control-flow, cf. §3).

For the latter, conditional and repetitive execution via if-statements and for-loops are supported. GALEC thereby provides no means for unbounded or conditional repetitive execution as typical in imperative programming languages, for example, while in [ISO/IEC 9899:2024]; instead, repetitive execution is according to an execution time independent, strictly monotonically increasing order with well-defined start bound, termination bound and step size — hence, with a statically well defined number of iterations. In combination with recursion-free functions, bounded iteration guarantees termination of block-interface triggered computations like initalization, recalibration, reinitalization and sampling (cf. §1 of Section 3.8). Comprehensibility of control-flows is further increased by the absence of exception related statements, for example, try/catch blocks in [ISO/IEC 14882:2024]. GALEC has no exceptional control-flows cross-cutting the ordinary control-flow; instead errors are systematically propagated and handled by if-statements (cf. §1 of Section 3.10).

Regarding assignments, three operations are provided: (1) assigning a new value to a variable based on a side effect free computation via a single-assignment, (2) calling a function for its side-effects, typically combined with discarding outputs, and/or to assign multiple function outputs to different variables via a multi-assignment acting as procedural operation, and (3) limiting variables according to their ranges via a limit-assignment (cf. §3 of Section 3.10). An important language design characteristic hereby is, that each type of assignment is specific in its scope of side effects (i.e., inter-functional assignments to block variables), such that potential for side effects, including such of called functions (cf. §2:R-1), is made explicit: (1) none, except the assignment at hand, (2) additional side effects of called functions, and (3) assignment only if out-of-range, kind of declarative based on user-defined variable ranges.

At the same time, the limited répertoire of statements — in particular control-flow related — significantly eases the definition of the side effect analysis of Section 3.9 and thereby is a cornerstone for enabling advanced inter-functional control-flow based analysis that, for example, guarantee well-defined initialization of block variables (cf. §3 of Section 3.4) and consecutive usage of block states throughout samplings (cf. §2 of Section 3.9).

§1: General statement categories

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
statement =
    (
        (* Assignments including procedural operations: *)
          single-assignment
        | multi-assignment
        | limit-assignment
        (* Control-flow statements: *)
        | if-statement
        | for-loop
    ),
    ";" ;

statement-sequence = { statement } ;

Statements and the 1’st child of such are called statement.

§2: Assignments including procedural operations

Single-assignments and multi-assignments of the form

1
2
3
4
5
6
7
8
single-assignment = reference, ":=", expression ;

multi-assignment =
    "(",
    [ ( reference | ":" ), { ",", ( reference | ":" ) } ],
    ")",
    ( ":=" | ":=!" ),
    function-call ;

are called assignment. The 1’st child of a single-assignment and the 2’nd child of a multi-assignment are called its left-hand; the last child its right-hand.

The type and dimensionality of the designation of the left-hand of a single-assignment s must be that of its right-hand. The execution semantic of s is to assign the value of its right-hand to the designation of its left-hand.

Let A⇐ = (a1, …​, an) be the sequence of : and reference children of the left-hand of a multi-assignment s, let f be the function the right-hand of s refers to, and let Tf> = (q1,…​,qm) be the outputs of f. It must hold that |A⇐| = |Tf>|. And ∀i∈ℕ+; 1 ≤ i ≤ n we say s discards qi if, and only if, ai is lexically-equivalent to :; otherwise (i.e., if ai is a reference), the type and dimensionality of the designation of ai must be that of qi. The execution semantic of s is to evaluate its right-hand (cf. function-call evaluation, §4 of Section 3.6) and afterwards assign to the designation of every ai that is not discarded the value of the respective qi.

A multi-assignment whose 4’th child is lexically-equivalent to :=! is said to act as procedural operation. Multi-assignments must, or must not, act as procedural operation based on the side effects of the function their right-hand refers to; the respective semantic rules are given in §2 of Section 3.9.

R-1 (deliberate exclusion of function call statements): GALEC provides no function call statement concept as typical in imperative programming languages like [ISO/IEC 9899:2024] or [ISO/IEC 7185:1990]. Just calling a function for its side effects and ignoring its outputs (if any) otherwise requires a multi-assignment acting as procedural operation whereas outputs of the called function must be explicitly discarded.

E-1: The following code fragment is invalid:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
    [[ ⋯ ]]

    Boolean on;

    [[ ⋯ ]]

    function disable
        output Boolean on;
    protected
    algorithm
        on := block.on;
        block.on := false;
    end disable;

    function f
    protected
    algorithm
        disable(); /* Invalid: Syntactic rules violation. */
        [[ ⋯ ]]

disable() cannot just be called as a stand-alone function call statement. Instead, the intend to just disable block.on without interest in its old state must be made explicit via ( : ) :=! disable();. Even if disable() would have no outputs, just calling it requires a multi-assignment of the form () :=! disable(); acting as procedural operation. And according to §3 of Section 3.9, disable() cannot be called within an expression like in if disable() then or self.on := disable(); because it has side effects; and according to §2 of Section 3.9, calling a function without side effects via a multi-assignment that acts as a procedural operation is not permitted either.

GALEC also differs w.r.t. languages that differentiate between functions with and without outputs, like functions vs. procedures in [ISO/IEC 7185:1990]. In GALEC the difference it not made when defining a function or procedure, but at the function call-site which decides whether outputs are of relevance or not and whether the call can have side effects or not. An assignment is either (1) just a pure assignment operation without side effects (i.e., not a procedural operation), (2) an assignment with side effects (i.e., a procedural operation with some of its outputs used for assignment), or (3) just for side effects (i.e., a procedural operation with all outputs discarded).

This design is deliberate and has been chosen for the sake of clarity. It makes the intention of function-calls explicitly clear at call-sites and discloses unexpected side effects or outputs that need further investigation.

A limit-assignment of the form

1
2
3
4
5
6
7
limit-assignment =
    "limit",
    (
          "block"
        | "function"
        | reference, { ",", reference }
    ) ;

is syntactic sugar, that for all purposes of syntactic relations and other semantic rules is first of all transformed to a sequence of if-statements as defined in §3 of Section 3.10.

§3: Control-flow statements

Let s be an if-statement of the form

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
if-statement =
    "if",
    (* Branch-condition: *)
    ( expression | error-signal-check ),
    "then",
    (* Branch-body: *)
    statement-sequence,
    {
        "elseif",
        (* Branch-condition: *)
        ( expression | error-signal-check ),
        "then",
        (* Branch-body: *)
        statement-sequence
    },
    (* Fallback: *)
    [
        "else",
        (* Branch-body: *)
        statement-sequence
    ],
    "end",
    "if" ;

error-signal-check =
    "signal",
    [ simple-identifier ],
    [
        [ "not" ],
        "in",
        simple-identifier,
        { ",", simple-identifier  }
    ],
    [ "or", expression ] ;

The 2’nd and 5-2’nd children of s are called branch-condition; the 4’th, 5-4’th, and 6-2’nd children are called branch-body, whereas the 6’th child (if any) is called fallback. The closest contained expression of each branch-condition of s must be of type Boolean and scalar.

The branching-sequence of s is the tuple Bᗕ = ( (c1, s1),…​,(cn, sn), (sn+1) ) where n is the number of branch-conditions of s, sn+1 is the optional fallback, and for which holds ∀i∈ℕ+; 1 ≤ i ≤ n: ci is the i’th branch-condition of s and si its i’th branch-body. Each element of Bᗕ is called a branch. Branches are checked for execution in sequence according to Bᗕ: First branch-conditions are short-circuit evaluated until the first one satisfied (either, due to a captured error signal, or, if that is not the case, because the value of its closest contained expression is true) or the fallback branch is reached; in either case, the respective branch-body is executed. Afterwards, regardless if any branch-body has been executed or not, execution continues with the exit node of the control-flow block of s as defined in §1 of Section 3.9.

Let s be a for-loop of the form

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
for-loop =
    "for",
    (* Loop-condition: *)
    bounded-iteration,
    "loop",
    (* Loop-body: *)
    statement-sequence,
    "end",
    "for" ;

bounded-iteration =
    [ loop-iterator-definition, "in" ],
    (* Start bound: *)
    constant-scalar-integer-expression,
    [
        ":",
        (* Iteration step-size: *)
        constant-scalar-integer-expression
    ],
    ":",
    (* Termination bound: *)
    constant-scalar-integer-expression ;

loop-iterator-definition = name ;

The 2’nd child of s is called loop-condition; the 4’th child loop-body. The 2’nd, 3-2’th and last child of the loop-condition of s are called the start bound, iteration step-size and termination bound of s respectively.

Loop-iterator-definitions are also called loop iterator and are local variables of the function containing their for-loop (i.e., extend the set of local variables of a function defined in §2 of Section 3.3). Loop iterators are named like their name child (i.e., extend the set of named syntactic terms defined in §3 of Section 3.2). Their type is Integer and they are scalar.

Let i⊥, i± and i⊤ be the statically-evaluated values of the start bound, iteration step-size and termination bound respectively; if s has no iteration step-size, i± = 1 if i⊥ < i⊤ and i± = -1 otherwise. It must hold that i± ≥ 1 if i⊥ < i⊤ and i± ≤ -1 otherwise. The execution semantic of s is (i is a scalar Integer value not used otherwise; entry and exit node refer to control-flow blocks as defined in §1 of Section 3.9):

  1. i becomes i⊥.

  2. If s has a loop iterator, it is assigned i.

  3. If i⊥ < i⊤ ⋀ i ≤ i⊤ or i⊥ ≥ i⊤ ⋀ i ≥ i⊤ continue execution with the entry node of the loop-body of s (i.e., execute the loop-body of s), otherwise continue with 5.

  4. i becomes i + i±. Continue with 2.

  5. Continue execution with the exit node of s.

3.6. Expressions

This section defines the syntax, type and dimensionality of GALEC expressions, assuming that the semantic rules of the dimensionality analysis — in particular regarding statically-evaluated expressions — as defined in Section 3.8 are satisfied. The execution of an expression — as defined in this section — always yields a value of its type and dimensionality, for which reason it is called evaluation. Speaking of the value of an expression implies its evaluation, whereas it is defined by the syntactic usage-context if it is statically- or dynamically-evaluated (cf. §2 of Section 3.8). Note that GALEC expressions are side effect free by definition (cf. §3 of Section 3.9); even function calls within expressions will never inter-functional assign to block variables.

For the sake of clarity, GALEC does not support implicit type conversions as typical for imperative programming languages like [ISO/IEC 9899:2024] or [ISO/IEC 7185:1990]. A binary operation on an Integer and Real argument requires explicit casting using the integer() or real() build-in functions (cf. §2 of Section 3.11), which in turn indicate underflow, overflow, or [IEEE 754-2019] not a number issues via respective error signals (§1 of Section 3.10). Likewise, operators are not overloaded and are dimensionality-specific; there exist dedicated scalar (e.g., +, *, and), element-wise (e.g., .+, +., .+., .*, *., .*., .and, and., .and.), and multidimensional mathematics (e.g., matrix multiplication or dot product of vectors via **) variants. Strict typing in combination with explicit operators help to expose unintended type and dimensionality mismatches that otherwise would be covered behind “automagical” resolution rules (Arthur Charles Clark’s third adage [1]).

Expressions comply with the error handling rules of Section 3.10, such that errors are either propagated by dedicated values like [IEEE 754-2019] -∞, +∞, or not a number, or, if that is not possible, respective error signals are set (§2 of Section 3.10); this comprises in particular NAN error signals by relational operations on qNaN values and OVERFLOW error signals whenever arithmetic operations on Integer values cannot evaluate the mathematical correct value due to range restrictions.

§1: General expression categories and grouping

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
(* Statically-evaluated expressions: *)
constant-scalar-integer-expression = expression ;

(* Dynamically-evaluated expressions: *)
expression =
    (* Literals and references: *)
      literal
    | reference
    (* Multidimension constructors and dimension queries: *)
    | multidimension-constructor
    | dimension-query
    (* Function calls and conditional expressions: *)
    | function-call
    | if-expression
    (* Unary and binary operations: *)
    | unary-operation
    | binary-operation
    (* Explicit grouping: *)
    | parenthesized-expression ;

parenthesized-expression = "(", expression, ")" ;

Expressions and their parts insofar their syntactic rule is defined in §1-5 (except binary-operators and its derivations, and the reference child of dimension-querys, cf. §5 and §3), as well as constant-scalar-integer-expressions and literals (cf. §2 of Section 3.2), are called expression.

The type, dimensionality and value of constant-scalar-integer-expressions and expressions is the type, dimensionality and value of their child. The type, dimensionality and value of a parenthesized-expression is that of its expression child.

§2: Literals and variable references

1
2
3
4
5
6
7
8
9
reference = local-reference | block-reference ;

local-reference = name, [ constant-dimensions ] ;

block-reference =
    "block",
    ".",
    name,
    [ constant-dimensions ] ;

The syntactic rule, type, dimensionality and value of literals are defined in §2 of Section 3.2.

References, local-references and block-references are named like the first name derived through their derivation and are also called variable reference. The type of a variable reference is the type of the variable it refers to (cf. §2 of Section 3.7); its dimensionality is the dimensionality of the variable it refers to if it contains no constant-dimensions, otherwise it is scalar.

The constant-dimensions of a variable reference (if any) must not contain derived-dimensions.

Variable references that are an expression are called value-reference. TODO: definition of their value.

R-1 (variable references are not inevitably expressions): According to §1, only variable references part of an expression are expressions themselves. Variable references within the left-hand of assignments, but not used for indexing (i.e., not part of a constant-scalar-integer-expression of constant-dimensions), are not expressions; they do not evaluate to a value, although they have a type and dimensionality. Likewise, the reference child of a dimension-query is not an expression (cf. §3:R-1).

Cf. also to §4:R-1 for function-calls that are not expressions.

R-2 (variable references and multidimensional slicing): GALEC does not support multidimensional slicing; variable references to multidimensional variables either refer to the whole multidimension or a single element of it (i.e., a scalar). The purpose of this restriction is to ease the implementation of eFMI tooling, in particular production code generators.

Future versions of the eFMI Standard will presumably relax the definition of constant-dimensions for variable references, such that references to multidimensional variables can slice them w.r.t. given dimensional ranges and/or derived-dimensions. For example, for variables Integer m1[3, 2] and Integer m2[2, 3] we could slice the first column of m1 into the second row of m2 via m2[2, :] := m1[:, 1], or the last two elements of the second row of m2 into the third row of m1 via m1[3, :] := m2[2, size(m2, 2) - 1 : size(m2, 2)]. Full support of multidimensional slicing likely would be further decoupled from value-references, but be defined for expressions in general. For example, one could extract the first row of the matrix multiplication of m1 with m2 via (m1 ** m2)[1, :]. Such extension would require careful design to not foil the side effect analysis of Section 3.9 which is based on control-flow aware restrictions on value-references and assignments.

§3: Multidimension constructors and dimension queries

Let c be a multidimension-constructor of the form

1
2
3
4
5
6
7
multidimension-constructor =
    "{",
    multidimension-constructor-element,
    { ",", multidimension-constructor-element },
    "}" ;

multidimension-constructor-element = expression | multidimension-constructor ;

The type of c is the type of its 2’nd child. The types and dimensionalities of the multidimension-constructor-elements children of c must be equivalent. Let n be the number of such and e = (i1, …​, ie) be their dimensionality. The number of dimensions of c is |e| + 1; its dimensionality is (n, i1, …​, ie).

The type, dimensionality and value of a multidimension-constructor-element is the type, dimensionality and value of its child. TODO: value of c.

Let e be a dimension-query of the form

1
dimension-query = "size", "(", reference, ",", constant-scalar-integer-expression, ")" ;

The type and dimensionality of e is Integer and scalar.

The reference of e must refer to a multidimensional variable v and be without constant-dimensions. Let v have dimensionality (s1, …​, sn) and i be the statically-evaluated value of the constant-scalar-integer-expression of e; it must hold that 1 ≤ i ≤ n. The value of d is si (i.e., the size of the i'th dimension of v).

R-1: According to §1, the reference child of a dimension-query is not an expression; although it has a type and dimensionality, it is not evaluated and therefore has no value.

§4: Function calls and conditional expressions

Let fr be a function-call of the from

1
function-call = name, "(", [ expression, { ",", expression } ], ")" ;

The name of fr is the name of its 1’st child. Let f be the function it refers to (cf. Section 3.7). If fr is within an expression, f must have output-arity 1; in that case, the type and dimensionality of fr is the type and dimensionality of the only output of f. The arguments of fr are the tuple A>f = (e1,…​,en) where |A>f| is the number of expression children of fr and with ∀i∈ℕ+; 1 ≤ i ≤ n: ei is the i’th expression child of fr. Let T>f = (p1,…​,pm) be the inputs of f. It must hold that |A>f| = |T>f| (the number of arguments of fr must be equivalent to the input-arity of f) and ∀i∈ℕ+; 1 ≤ i ≤ n: the type and dimensionality of ai and pi must be equivalent.

The evaluation of fr follows three sequential steps, whereas every execution of f has its own set of values for its local variables: (1) ∀i∈ℕ+; 1 ≤ i ≤ n: ei is evaluated and its value used for pi in (2) (arguments are evaluated in any order), (2) f is executed, and, (3) in case fr is within an expression, the output of (2) becomes the value of fr.

R-1 (function-calls are not inevitably expressions): Not every function-call is an expression; according to §1, only such part of an expression are expressions themselves. This is to support by means of multi-assignments the execution of functions with multiple outputs, and/or — if acting as procedural operation — side effects. To that end, the function-call right-hands of multi-assignments are not expressions, relieving them from the requirements of expressions to have a unique type and dimensionality, evaluate to a single value, and being side effect free (cf. §3 of Section 3.9). Note that the arguments of a function-call are always expressions however, and the arguments of the right-hand of a multi-assignment are no exception (hence, only the function called by the right-hand itself can have side effects, but not any function called throughout the evaluation of any of its arguments).

Cf. also to §2:R-1 for variable references that are not expressions.

R-2 (strict function argument evaluation vs. call by value vs. call by reference; copy elision & return value optimization): GALEC function-calls use applicative order; they are strict, although the evaluation of function arguments is unordered (considering §3 of Section 3.9, function arguments can in fact be evaluated concurrently). Strict argument evaluation is required for deterministic error signaling (cf. §1 of Section 3.10).

GALEC does not enforce to pass arguments by value however. Considering that local inputs never must be assigned (cf. §2 of Section 3.9), implementations are free to be call by value or reference as best-suited case-by-case regarding optimizations. Likewise regarding function outputs that are assigned to variables, for which implementations can avoid local memory allocation and final copy-assignments and instead directly use the respective function call-site variable throughout function execution if such optimization does not influence program execution semantic besides performance (in [ISO/IEC 14882:2024] this kind of optimizations are called copy elision and return value optimization (RVO) and, due to pointer and reference semantic and expressions with side-effects, are much harder to apply than for GALEC).

To avoid temporary variables and copying holds for expressions in general, in particular when such define multi-dimensional values: final destination variables (i.e., designations of the right-hand of assignments) can be used instead of temporary expression values if semantics permit. And local variables can be used as buffer for intermediate values of multi-dimensional expressions, or deallocated, if they are not used otherwise anymore for any possible further control-flow (i.e., their life-time ended).

Let e be an if-expression of the form

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
if-expression =
    "(",
    "if",
    (* Branch-condition: *)
    expression,
    "then",
    (* Branch-body: *)
    expression,
    {
        "elseif",
        (* Branch-condition: *)
        expression,
        "then",
        (* Branch-body: *)
        expression
    },
    "else",
    (* Branch-body: *)
    expression,
    ")" ;

The 3’rd and 6-2’nd children of e are called branch-condition; the 5’th, 6-4’th, and 8’th children are called branch-body. The branch-conditions of e must be of type Boolean and scalar. The types and dimensionalities of the branch-bodies of e must be equivalent; the type and dimensionality of e are that of its branch-bodies.

The branching-sequence of e is the tuple Bᗕ = ( (c1, v1),…​,(cn, vn), (vn+1) ) where n is the number of branch-conditions of e, vn+1 is its last branch-body, and for which holds ∀i∈ℕ+; 1 ≤ i ≤ n: ci is the i’th branch-condition of e and vi its i’th branch-body. Each element of Bᗕ is called a branch. Branches are short-circuit evaluated in sequence according to Bᗕ: First branch-conditions are evaluated until the first one being true or the last branch is reached; then the respective branche’s branch-body is evaluated, yielding the value of e.

§5: Unary and binary operations

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
unary-operation =
    (
          ( "-" | "-." ), ( reference | function-call )
        | ( "not" | "not." ), ( parenthesized-expression | if-expression )
    ) ;

binary-operation = expression, binary-operator, expression ;

binary-operator = arithmetic-operator | relational-operator | logical-operator ;

arithmetic-operator =
       "+"  |  "-"  |  "*"  |  "/"  |  "^"
    | ".+"  | ".-"  | ".*"  | "./"  | ".^"
    |  "+." |  "-." |  "*." |  "/." |  "^."
    | ".+." | ".-." | ".*." | "./." | ".^."
    | "**" ;

relational-operator =
       "<"  |  ">"  |  "<="  |  ">="  |  "=="  |  "<>"
    | ".<"  | ".>"  | ".<="  | ".>="  | ".=="  | ".<>"
    |  "<." |  ">." |  "<=." |  ">=." |  "==." |  "<>."
    | ".<." | ".>." | ".<=." | ".>=." | ".==." | ".<>." ;

logical-operator =
       "and"  |  "or"
    | ".and"  | ".or"
    |  "and." |  "or."
    | ".and." | ".or." ;
§5.1 Operators and arguments

Unary-operations and binary-operations are also just called operation. The 1’st child of a unary-operation and the 2’nd child of a binary-operation are called its operator. The 2’nd child of a unary-operation is called its argument. The 1’st and 3’rd child of a binary-operation o are called its first and second argument respectively; they are the arguments of o.

Let ⊕ be lexically-equivalent to the operator o⊕ of an operation o; we call o a ⊕ operation and o⊕ the ⊕ operator. If, and only if, o is a unary-operation it and its operator are called unary; otherwise binary.

E-1: The expression -v is a unary - operation, whereas i1 - i2 is a binary - operation; both can be either, statically- or dynamically-evaluated (cf. §2 of Section 3.8) depending on their application context. For example, in A[i1 - i2] := -v * A[i1 - i2] the binary - operations are statically-evaluated whereas the unary - operation is dynamically-evaluated.

not and not. operations are always unary and and, .and, and., .and., or, .or, or., and .or. operations are always binary. Note, that they can be statically-evaluated, like in A[(if (remainderUp(i, 2) == 0) and (i <= size(A, 1)) then i else size(A, 1))].

§5.2 Operator precedence and associativity

The following table defines a unique disambiguation for the syntactic ambiguities of binary-operations by means of an operator precedence and associativity for sequences of operators with equivalent precedence:

Operator classes (highest precedence to lowest)

Associativity of contained operators

^, .^, ^., .^.

right-to-left

*, /, **, .*, *., .*., ./, /., ./.

left-to-right

+, -, .+, +., .+., .-, -., .-.

left-to-right

<, >, <=, >=, .<, <., .<., .>, >., .>., .<=, <=., .<=., .>=, >=., .>=.

left-to-right

==, <>, .==, ==., .==., .<>, <>., .<>.

left-to-right

and, .and, and., .and.

left-to-right

or, .or, or., .or.

left-to-right

Binary-operations must satisfy the defined operator precedence and associativity.

A binary-operation o satisfies operator precedence, if, and only if, it does not contain binary-operations whose operator has a different operator precedence than the operator of o and which themselves are not contained within a precedence-overriding non-terminal part of o. The precedence-overriding non-terminals are: reference, dimension-query, function-call, parenthesized-expression, if-expression and multidimension-constructor.

Operator associativity is satisfied if, and only if, binary-operations are derived left-most if their operator’s associativity is left-to-right and right-most otherwise.

R-1 (explicit precedence for expressions mixing binary operations of various precedences): Instead of using the precedence table for automatic disambiguation of binary operation precedence, GALEC forces the use of precedence-overriding non-terminals, e.g., parentheses, braces, and brackets. This might look like adding unnecessary burden on GALEC programmers and code generators. The chosen design is backed by practical experience however. In the safety-critical domain typical mandatory development guidelines enforce similar rules, for example, [MISRA C:2025] Rule 12.1: “The precedence of operators within expressions should be made explicit”. Deriving algorithmic solutions from physics-equations also often yields huge expressions; even if the original equations are intuitive without explicit parentheses, the expressions of derived solutions are not anymore. A typical example are A matrices for linear solver calls, constructed by combining many different equations. Considering the overhead of explicit parentheses for small expressions compared to the gain in clarity for large ones, the best choice for a standard that shall enforce non-functional code quality clearly is to require the use of parentheses whenever operations of different precedence are combined.

The following examples highlight the operator precedence and associativity rules of GALEC.

E-1: The parenthesis of (a or b) and c cannot be omitted because or and and have different operator precedences which is prohibited without precedence-overriding non-terminals (like parenthesized-expressions). Likewise, a * b + c is invalid because * and + have different operator precedences. But a * v[b + c] and { a * b } . c+ and a * f(b + c) are valid since references, multidimension-constructors and function-calls are precedence-overriding.

E-2: The parenthesis of a^(2*b) cannot be omitted because a^2*b is an invalid expression (^ and * have different operator precedences) and (a^2)*b is not equivalent. For example, a^(2*b) yields 64 if a is 2 and b is 3 whereas (a^2)*b yields 12.

E-3: The parenthesis of (a^b)^c cannot be omitted because a^b^c is equivalent to a^(b^c). For example, (a^b)^c yields 1 if a is -1, b is 3, and c is 2 whereas a^(b^c) yields -1.

E-4: The value assigned to a in a := (-b)^2; always will be positive whereas for a := 0 - (b^2); and a := -1*(b^2); it always will be negative; parentheses cannot be omitted in any of these cases. For example, a := -b^2; and a := -2^b; are invalid since the base of power of operations must not be a unary-operation nor a negative literal (cf. R-3). Likewise a := -(b^2); is an invalid expression since the unary - operation is only supported for references and function-calls (cf. §5, syntax-rule of unary-operation).

E-5: The strict left-to-right associativity of a <> b <> c is important for the expression to have a well-defined — i.e., unique — type. For example, if a and b are of type Integer and c is of type Boolean, (a <> b) <> c is type-correct whereas a <> (b <> c) is illegal.

R-2 (operator precedence and associativity vs. strict evaluation order of expressions): Operator precedence and associativity does by no means imply a strict evaluation order for the arguments of operations, nor their parts. A production code generator can, for example, leverage on commutative and distributive properties of expressions to rearrange their evaluation order; such is, for example, interesting to balance expression parts with function-calls for concurrent evaluation considering expressions are always side effect free (cf. §3 of Section 3.9). Of course, such transformations must be execution semantic invariant considering application requirements, which typically tolerate minor floating-point rounding effects due to changed execution orders, for example when reordering a * b * c to c * a * b.

The first argument (i.e., the base) of ^, .^, ^., and .^. operations must not be a unary-operation; and the value of literal bases must be ≥ 0.

R-3 (explicit precedence for negated bases of power of operations): Unary-operation and negative literal bases are prohibited in power of operations to avoid operator precedence confusion for expressions like -2n for which no common mathematical nor formal language interpretation exists. In formal languages dedicated to numeric computation — like [ISO/IEC 1539-1:2023] or [Modelica 3.7] — -2n typically yields negative values for odd n, whereas general purpose programming languages — like [ISO/IEC 9899:2024] — typically lack power of operators but are designed around the rule of thumb that unary operators have higher precedence than binary operators which then would yield a positive value for hypothetical power of operator extensions. In GALEC, both audiences would be surprised due to its native support for negative literals (cf. §2:R-3 of Section 3.2); -2n would be positive for even n whereas -vn would be negative. To avoid any confusion, explicit parenthesized-expressions therefore must be used in GALEC depending on the intended meaning: (-2)^n or -1.0 * (2^n) and (-v)^n or -1.0 * (v^n) respectively. Enforcing explicit parentheses becomes even more evident considering multi-dimensional operations, like (-.block.M).^2, where a common understanding of precedence cannot be reasonably assumed.

§5.3 Type, dimensionality and value

Except for ^, .^, ^. and .^. operations, the arguments of an operation must be equally typed. The arguments of arithmetic-operators and relational-operators — except ==, <>, .==, ==., .==., .<>, <>., and .<>. operators — must be of type Integer or Real. The arguments of /, ./, /. and ./. operations must be of type Real. The arguments of logical-operators must be of type Boolean. The argument of unary - and -. operations must be of type Real or Integer; the argument of unary not and not. operations must be of type Boolean.

Except for ^, .^, ^. and .^. operations and operations with an operator that is a relational-operator, the type of an operation is the type of its arguments. The type of ^, .^, ^. and .^. operations is Real; the type of operations with an operator that is a relational-operator is Boolean.

R-1 (Real type restriction of /, ./, /. and ./. operations; absence of %, .%, %. and .%. operators): Division of Integer values via the /, ./, /. or ./. operator is prohibited since there exists no common mathematical or formal language interpretation of such. Often, integer division is target environment specific. For example in [ISO/IEC 9899:1990], integer division with a negative operand has an implementation-defined behavior, whereas in [ISO/IEC 9899:2024] it corresponds to divisionTowardZero(). Programming languages differ on their interpretation of integer division and remainder; particularly regarding the latter a plethora of mod function and % operator interpretations exist. The problem is related to the implicitly applied rounding of integer divisions; GALEC is explicit however and provides a systematic scheme of rounding-related built-in functions (cf. §2 of Section 3.11), like roundUp(), divisionUp() and remainderUp() or roundTowardZero(), divisionTowardZero() and remainderTowardZero() for the rounding strategies to round plus and minus half up or toward zero respectively. Instead of some implicit-rounding /, ./, /., ./., %, .%, %. and .%. operators on Integer values, the desired built-in function and explicit type casts via real() and integer() can be used.

R-2 (equality-tests of Real typed variables): The support of Real arguments for ==, <>, .==, ==., .==., .<>, <>. and .<>. operations is mostly intended for tests against magic literal numbers like 0.0 or 1.0, for example, to enable if-statements protecting against division by zero. Since tests for exact equality of Real variables are otherwise error-prone due to limited floating-point precision and resulting rounding errors, tools are advised to warn about such although they are not prohibited. Equality tests of Real typed variables cannot be prohibited easily anyway, since such can be encoded in a plethora of different schemes using negation, other relational-operators, and temporary variables, like:

1
2
3
4
5
        [[ ⋯ ]]
        b1 := r1 > r2;
        b2 := r1 < r2;
        if not(b1 or b2) /* r1 == r2 */ then
            [[ ⋯ ]]

R-3 (target environment specific ^, .^, ^. and .^. operations implementation): The ^, .^, ^. and .^. operators provide all kind of type-combinations for its base and exponent arguments. It is not restricted to just Real arguments, because specialized — and therefore more efficient — implementations for different base and exponent type combinations exist, often provided as target environment specific hardware operations. By enabling both, Real and Integer typed bases and exponents, Production Code tools can choose the most efficient implementation available in a target environment. The return type is always Real however, because (1) the range of Real typically is larger than that of Integer and power easily yields large values, and (2) to properly handle corner cases of negative exponents and zero arguments according to [IEEE 754-2019].

Let value(x) be the value of an expression x, implying that x must be evaluated.

The dimensionality of a unary-operation o is the dimensionality of its argument; for - and not operations the argument must be scalar, otherwise it must be multidimensional. Let a1 be the argument of o; the value of o is:

Unary operator

Value

-

Arithmetical negation (i.e., sign change): -1 × value(a1).

not

Logical negation: ¬value(a1).

⊕. with ⊕∈{ -, not }

Unary element-wise application: Multidimensional value vnew with the dimensionality of a1 and for each element index i the value of the i'th element of vnew is the ⊕ of the i'th element of value(a1).

Let o be a binary-operation whose operator is lexically equivalent to α. If α starts and ends with a end of record point (.), the arguments of o must have equivalent dimensionalities. If α starts with a end of record point, the first argument must be multidimensional; otherwise, it must be scalar. If α ends with a end of record point, the second argument must be multidimensional; otherwise, it must be scalar. The dimensionality of o is the dimensionality of the first argument if it is multidimensional and otherwise the dimensionality of the second argument. Let a1 be the first argument of o and a2 be the second argument (with A = { +, -, *, /, ^ }, R = { <, >, <=, >=, ==, <> } and L = { and, or }):

Binary operator

Value

+

Addition: value(a1) + value(a2) (i.e., the sum of the summand a1 and the summand a2).

-

Subtraction: value(a1) - value(a2) (i.e., the difference of the minuend a1 and subtrahend a2).

*

Multiplication: value(a1) × value(a2) (i.e, the product of factor a1 and factor a2).

/

Division: value(a1) ÷ value(a2) (i.e., the fraction of the dividend a1 and divisor a2).

^

Exponentiation: be where b is value(a1) and e is value(a2) (i.e., the power of base a1 and exponent a2). The value in case of Integer typed base or exponent follows the rules of Real based arguments (i.e., [IEEE 754-2019]).

⊕∈R

Inequality, equality: Comparison of value(a1) and value(a2) according to ⊕ (i.e., value(a1) ≥ value(a2) if ⊕ is >=, value(a1) ≠ value(a2) if ⊕ is <>, etc).

and

Logical conjunction: value(a1) ∧ value(a2) (no short-circuit evaluation).

or

Logical disjunction: value(a1) ∨ value(a2) (no short-circuit evaluation).

.⊕ with ⊕∈(A ∪ R ∪ L)

Left-sided element-wise application: Multidimensional value vnew with the dimensionality of a1 and for each element index i the value of the i'th element of vnew is vi ⊕ value(a2) whereas vi is the i'th element of value(a1).

⊕. with ⊕∈(A ∪ R ∪ L)

Right-sided element-wise application: Multidimensional value vnew with the dimensionality of a2 and for each element index i the value of the i'th element of vnew is value(a1) ⊕ vi whereas vi is the i'th element of value(a2).

.⊕. with ⊕∈(A ∪ R ∪ L)

Element-wise application: Multidimensional value vnew with the dimensionality of a1 and a2 and for each element index i the value of the i'th element of vnew is vi1 ⊕ vi2 whereas vi1 and vi2 are the values of the i'th elements of value(a1) and value(a2) respectively.

Operations on Real arguments — whether arithmetical negations, arithmetic-operators or relational-operators — must comply with [IEEE 754-2019] except that -0 and +0 cannot be distinguished in GALEC by any means (e.g., relational operations evaluate to false if any of their arguments is not a number; 0.0 / 0.0 evaluates to not a number; -1.0 / 0.0 evaluates to -∞; 1.0 / 0.0 evaluates to +∞; { 0.0, 1.0 } ./. { 0.0, 0.0 } and { 0.0, 1.0 } ./ 0.0 evaluate to the value of { nan(), plusInfinite() }; allTrue1D(({ 1.0, -1.0, 1.0, -1.0 } ./. { 0.0, 0.0, -1.0 * 0.0, -1.0 * 0.0 }) .==. { plusInfinite(), minusInfinite(), plusInfinite(), minusInfinite() }) evaluates to true; etc).

R-4 (logical operators are not short-circuit evaluated): The scalar logical operations and and or and their element-wise variants .and, and., .and., .or, or. and .or. for multidimensional arguments are not short-circuit evaluated. Although expressions are side effect free (cf. §3 of Section 3.9), this is of importance because error signals could be set throughout the evaluation of the second argument, which in turn can influence further program execution due to if-statements checking for the respective error signals (cf. §1 of Section 3.10).

For example, f() and ((a / b) < c) with value(a) = value(b) = 0 must set the NAN error signal even if the output of the f() function-call is false (according to §2 of Section 3.10, relational operators like < must signal NAN if the value of any of their arguments is qNaN, and according to [IEEE 754-2019], 0 ÷ 0 yields qNaN). If-expressions can be used to achieve short-circuit evaluated logical operations; for example, (if f() then (a / b) < c else false) cannot signal NAN if f() evaluates to false without signaling NAN itself.

Logical operations are not short-circuit evaluated for two reasons: (1) consistency between the scalar and element-wise variants, and (2) to enable efficient concurrent evaluation, in particular of the element-wise variants. Regarding (1), it has to be considered that short-circuit evaluation of operations on multidimensionals has intricate consequences and requires significant implementation effort (it is on the same page as lazy evaluation). Regarding (2), note that short-circuit evaluation comprises program execution branching, which is a major culprit for concurrency requiring complicated concepts like branch prediction to be efficient.

R-5 (reduction of Boolean multidimensionals to scalars): To reduce the multidimensional value of binary-operations with an element-wise relational-operator to an actual (in)equality check (i.e., a Boolean scalar), the anyTrue1D(), anyTrue2D(), allTrue1D(), and allTrue2D() built-in functions can be used. For example, to check if two Real matrices m1 and m2 are not equivalent can be expressed in GALEC as anyTrue2D(m1 .<>. m2). Likewise allTrue2D(m1 .<. m2) checks if all elements of m1 are smaller than their respective m2 element; and anyTrue2D(m1 .< 0.0) and anyTrue2D(0.0 >. m1) checks if any element in m1 is smaller than 0.

Let o be a ** operation, a1 be its first argument, a2 its second, and d1 and d2 be the dimensionalities of a1 and a2 respectively. The dimensionality and value of o are (with m,x,n∈ℕ+):

Case

Dimensionality

Value

d1 = d2 = (x)

()

Dot product of value(a1) and value(a2).

d1 = (m, x) ∧ d2 = (x, n)

(m, n)

Matrix multiplication of value(a1) with value(a2).

d1 = (x) ∧ d2 = (x, n)

(n)

Let { { v1, …​, vn } } of dimensionality (1, n) be the value of the matrix multiplication of value(a1) with value(a2) whereas value(a1) is treated as a row vector of dimensionality (1, x): value(o) = { v1, …​, vn }.

d1 = (m, x) ∧ d2 = (x)

(m)

Let { { v1 }, …​, { vm } } of dimensionality (m, 1) be the value of the matrix multiplication of value(a1) with value(a2) whereas value(a2) is treated as a column vector of dimensionality (x, 1): value(o) = { v1, …​, vm }.

Any other case is invalid.

3.7. Name analysis

The name space, scope, name resolution (i.e., lookup) and variable life-time rules of GALEC are concise. There are only two flat name spaces, the block- and the function-level, whereas block-level lookup must be explicitly denoted via block. preceding the name to lookup (cf. §2); lookup of called functions always is implicitly on the block-level and therefore does not require block. (cf. §3). The scopes and life-times of variables are respectively aligned. Block variables are always visible (and selectable via block.), with their values outliving function calls; each block instance has its set of block variables, whereas their values are the block instance state (cf. §2 of Section 3.4). Local variables are only visible within the function containing their definition; each function execution has its own set of local variable values and their life-time starts and ends with it (cf. §4 of Section 3.6). This simple language design exposes the kind of an entity to lookup by its use-context (i.e., it is clear by syntax if a name refers to a function, block variable, or local variable), making dependencies on the state of block instances explicit — a characteristic going well in line with other side effect analysis, like side effect free expressions (cf. §3 of Section 3.9) — and reduces the danger of confusion by avoiding shared names with complicated shadowing rules (cf. §1:R-1). Using quoted-identifier based names (§3:R-1 of Section 3.2), GALEC is nevertheless suited as code generation target for modeling languages with complex nested name spaces including hiding of outer-scopes.

§1: Unique definitions and their name space & scope

Let Eblock be the set of all block variables and functions of a block; and let Ebuilt-in be the set of all built-in functions (cf. Section 3.11). It must hold that ∀e1,e2∈(Eblock ∪ Ebuilt-in), e1≠e2: e1 and e2 have different names.

Local variables must not be named like functions (whether user-defined or built-in; but they can be named like block variables). The local variables within a function, except loop iterators, must be named differently.

The loop iterators within a function f must not be named like any local variables of f that are not a loop iterator. Let i1 and i2 be two different loop iterators within a function, whereas the for-loop of i2 is contained in the for-loop of i1: i1 and i2 must have different names.

R-1 (name spaces, scopes and hiding of outer-scope entities): W.r.t. the terminology used by the [ISO/IEC 9899:2024] and [MISRA C:2025] standards, GALEC supports two name spaces, no hiding of outer-scope declarations, and well-defined variable scopes.

Block variables and functions share a name space; likewise, functions and local variables share a name space. Given a reference, lookup in block-scope is denoted by block., which as a bonus improves program readability by making dependencies on block variables shared between functions (i.e., dependencies on block instance state) explicit; without it, lookup is for a local variable within the containing function only.

Although function-calls can be clearly distinguished from variable lookup due to the name-following argument list embraced by ( and ), the design for a shared name space with variables is deliberate; it helps with program readability by avoiding any potential confusion between equally named variables and functions.

Enabling the reuse of loop iterator names within separate loops (i.e., for-loop siblings) does not violate the design that hiding of outer-scope entities is not possible in GALEC. It helps to improve program readability by enabling to reuse common index names as typically used in mathematics, like i and j to denote the rows and columns of a matrix.

The scoping rules of GALEC are simple: block variables and functions are whole program visible; local variables only within their respective function, or, if they are loop iterators, only within their respective loop.

E-1: The following block demonstrates the different GALEC name spaces and their scopes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
block B
    input Integer x[ 2, 2 ];
    output Integer y[ 2, 2 ];
protected
    /*
        It is not permitted to define another x function or variable here.
        Likewise, defining a pi would be invalid since pi() is a built-in function.
    */
public
    function InitializeConstants
    protected
    algorithm
    end InitializeConstants;

    function InitializeTunableParameters
    protected
    algorithm
    end InitializeTunableParameters;

    function InitializeDependentParameters
    protected
    algorithm
    end InitializeDependentParameters;

    function InitializeStateAndOutputs
    protected
    algorithm
        block.y := block.x;
    end InitializeStateAndOutputs;

    function DoStep
        /*
            Defining a pi input or output here would be invalid since pi() is a
            built-in function. Likewise defining a local state InitializeInputs
            would be invalid since that is already a user-defined function.
        */
    protected
        /* Local variables can be named like block variables since... */
        Integer x[ size(block.x, 1), size(block.x, 2) ];
    algorithm
        for i in 1 : size(x, 1) loop
            for j in 1 : size(x, 2) loop
                /* ...referencing is unambiguous via block: */
                x[ j, i ] := block.x[ i, j ];
            end for;
        end for;
        /* Loop iterator names can be reused in separate loop nestings: */
        for i in 1 : size(x, 1) loop
            for j in 1 : size(x, 2) loop
                x[ i, j ] := i * j * x[ i, j ];
            end for;
        end for;
        block.y := x;
    end DoStep;

    function InitializeInputs
    protected
        /* Local variable names can be reused in separate functions: */
        Integer x;
    algorithm
        x := 1;
        for i in 1 : size(block.x, 1) loop
            for j in 1 : size(block.x, 2) loop
                block.x[ i, j ] := x;
                x := x * x;
            end for;
            /*
                Another for-loop with an i loop iterator would be invalid here
                since the name is already used by an outer for-loop.
            */
        end for;
    end InitializeInputs;
end B;

§2: Variable lookup

Let vr be a block-reference (cf. §2 of Section 3.6). There must exist a block variable vblock named like vr; according to §1, vblock must be unique and we say vr refers to vblock.

Let vr be a local-reference (cf. §2 of Section 3.6). If vr is contained within a for-loop sloop whose loop iterator vloop is named like vr, sloop must be unique according to §1 and we say vr refers to vloop. Otherwise, there must exist a local variable vlocal within the function f of which vr is part of and vlocal must be named like vr; according to §1, vlocal must be unique within f and we say vr refers to vlocal.

A reference (cf. §2 of Section 3.6) refers to the variable its child refers to.

§3: Function lookup

Let fr be a function-call (cf. §4 of Section 3.6). If fr is named like a built-in function fbuilt-in (cf. Section 3.11), we say fr refers to fbuilt-in. Otherwise, there must exist a function fblock named like fr; according to §1, fblock must be unique and we say fr refers to fblock.

3.8. Termination and dimensionality analyses

Every multidimensional block variable in GALEC has a fixed size and multidimensional local variables of functions have a call-site specific fixed size. Hence, the maximum algorithmic memory requirements of a GALEC program are decidable and a worst memory consumption can be guaranteed. Since sizes are known, indexing within multidimensionals can be statically checked to guarantee that for every possible program execution all element queries are valid, i.e., out-of-bounds indexing is impossible (like, for example, buffer overflows in [ISO/IEC 9899:2024]). The dimensionality analysis required to provide such guarantees is subject of this chapter.

At the core of dimensionality analysis is to mark all places related to sizes and indexing — including iteration within fixed bounds over multidimensionals — using a dedicated expression, the constant-scalar-integer-expression (cf. §2). Wherever computations on multidimensions are applicable, whether to define sizes in variable definitions or for indexing, a constant-scalar-integer-expression is used. Due to special restrictions on constant-scalar-integer-expressions they can be statically-evaluated, i.e., once before program execution according to the GALEC block life-cycle (cf. Section 3.4). Local variables with derived-dimension enable the definition of functions working on any dimensional sizes; the actual size of a derived-dimension is defined by the fixed sizes of the arguments known at function call-site. A function call-site based inter-functional dimensionality analysis propagating sizes starting from the block level (cf. §4) ensures, that a dimensionality analysis is conducted for every possible size of the derived-dimensions of local variables, whereas the number of possible sizes is limited by the number of function-calls due to GALEC programs being recursion-free (cf. §1).

The latter is also relevant to guarantee termination of functions, i.e., that there exists for every function an upper bound of operations it executes regardless of actual arguments and block instance state. Given recursion-freeness, only iterative statements could cause non-termination, which is impossible since GALEC for-loops are bounded by constant-scalar-integer-expressions defining a lattice of finite height the for-loop monotonically traverses (cf. §3 of Section 3.5). This relation between termination and dimensionality analyses also applies vice-versa: considering that dimensional sizes cannot be defined by ordinary value references (i.e., runtime values) but only constant-scalar-integer-expressions, the only means for unbounded memory requirements would be via recursive, non-terminating function-calls allocating infinite many local variables. And likewise, indexing can only be exhaustively checked for safety if there exists a finite number of indexing combinations, which thanks to guaranteed termination is the case.

A program is only a valid GALEC program if it passes termination and dimensionality analyses (i.e., satisfies §1-4); in other words, GALEC programs guarantee by definition maximum algorithmic operations and memory requirements, and safe indexing.

§1: Static function call graph, recursion-freeness and function-reachability

Let Cf be the set of names of the functions referenced by the function-calls contained in a function f; Cf is called the local function call set of f and we say for each function fc whose name is in Cf that it is locally called by f and that f locally calls fc.

The static function call graph Gᗕ (a directed, node-labeled graph) of a GALEC program is defined as follows: For every function f (including built-in functions, cf. Section 3.11), Gᗕ contains a node labeled with the name of f; for every function fc locally called by a function f, we add a directed edge from f to fc.

Let n be a node of Gᗕ and nr be a node reachable from n; let f be the function named like the label of n and fr the function named like nr. We say fr is transitively called by f and f transitively calls fr.

Gᗕ must be cycle-free.

All block-internal functions must be transitively called from block-interface functions (thus, let Ninterface and Ninternal be the sets of nodes of Gᗕ labeled with the name of a block-interface or block-internal function respectively: ∀ninternal∈Ninternal, ∃ninterface∈Ninterface: ninternal is reachable from ninterface).

R-1 (recursion and dead code; function-reachability required for side effects analysis): Cycle-freeness of the static function call graph is one — of several — prerequisite to guarantee termination since it eliminates the possibility for (infinite) recursion. Transitive reachability of block-internal functions from block-interface functions is one — besides no infinite recursion and others — prerequisite to avoid dead code (note that GALEC does not guarantee absence of dead code, cf. §1:R-4 of Section 3.9) because block-internal functions cannot be called from the target environment either (cf. §1 of Section 3.4).

Function-reachability is also important to ensure block-internal function implementations are sound w.r.t. assignment and value-reference restrictions; only if a function is used within the context of at least one block-interface function, it can be decided which assignment and value-reference restrictions apply (cf. §2:R-2 of Section 3.9).

One consequence of interest is the interplay with multi-assignment restrictions, in particular when such can act as procedural operation with side effects (cf. §2 of Section 3.9 and §3:R-1 of Section 3.5). Block-internal functions without outputs and any inter-functional side-effects will, the one way or the other, be invalid. If not called (indirectly) from any block-interface function, function-reachability is violated; if called via a single-assignment expression or within an expression, output-arity is violated; if called via a multi-assignment, acting as procedural operation is violated, either because they :=! assign but there is no side effect or they don’t but then violate that the called function must have at least two outputs.

§2: Statically- and dynamically-evaluated expressions

Expressions part of, or that are, a constant-scalar-integer-expression are called statically-evaluated; otherwise they are called dynamically-evaluated.

R-1 (statically-evaluated is defined for whole (sub)expressions, not just a single syntax-rule): Note, that the characteristic to be statically-evaluated holds for all sub-expressions of a constant-scalar-integer-expression. And since constant-scalar-integer-expression is a chain syntax-rule for expression, the kind of expressions that can be used for defining dimensional sizes and indexing are powerful.

Let e be a statically-evaluated expression of the form

1
constant-scalar-integer-expression = expression ;

According to §1 of Section 3.6, the type, dimensionality and value of e are that of its child; additionally, the type of e must be Integer and its dimensionality must be scalar. If the parent of e is a constant-dimensions, the value of e must be ≥ 1.

References contained in statically-evaluated expressions must either, be the 3’rd child of a dimension-query (cf. §3 of Section 3.6) or refer to a loop-iterator-definition (cf. §2 of Section 3.7). Function-calls contained in statically-evaluated expressions must refer to built-in functions (cf. Section 3.11). The evaluation of statically-evaluated expressions must not signal any errors (cf. §1 of Section 3.10).

R-2 (statically-evaluated expressions are block instance independent): Considering that built-in functions must not reference block variables (cf. §1 of Section 3.11) and loop-iterator-definitions are unrelated to block variables either (cf. §2 of Section 3.7), statically-evaluated expressions cannot value-reference block variables. Their value is independent of block instances, i.e., initialization, recalibration, reinitialization or sampling. They can be evaluated once before program execution according to the GALEC block life-cycle (cf. Section 3.4), for example, throughout production code generation; hence, statically-evaluated.

Dynamically-evaluated expression on the other hand can directly or indirectly via function-calls value-reference block variables. According to §3:R-1 of Section 3.9, neither, statically- nor dynamically-evaluated expressions, can assign to block variables via function-calls.

R-3 (statically-evaluated does not imply static evaluation beyond dimensionality analysis): To be statically-evaluated has no implications for, or requirements on, program execution or production code; its sole purpose is for dimensionality-analysis — to which end static evaluation is required — to provide memory-consumption and indexing guarantees. Production code generators can indeed statically evaluate all indexing (e.g., by function inlining and loop unrolling), or instead leave constant-scalar-integer-expressions as they are and compute such throughout program execution, or any combination thereof as is best suited for the application requirements and target environment.

§3: Dimensionality restrictions

Block variables must not contain derived-dimensions or dimension-queries.

R-1 (independent block variable dimensionality): GALEC does not support block variables with related dimensionality, like:

1
2
3
4
5
6
7
8
9
block B
    input Real i[ 3 ];
    output Real o[ /* Invalid (not supported): */ size(i, 1) ];
    [[ ⋯ ]]
protected
    Real m[
        /* Invalid (not supported): */ 2 * size(i, 1),
        /* Invalid (not supported): */ size(m, 1) ];
    [[ ⋯ ]]

This restriction eases the definition of inter-functional dimensionality propagation and soundness (cf. §4) and the implementation of eFMI tooling, but likely will be relieved in future versions of the eFMI Standard. Generally, a means for statically-evaluated, declarative macros would be nice; something like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
/* Statically-evaluated, declarative macros: */
ISIZE = OSIZE = 3 = integer(real(MSIZE) / 2.0);

/* Actual block: */
block B
    input Real i[ ISIZE ];
    output Real o[ OSIZE ];
    [[ ⋯ ]]
protected
    Real m[ MSIZE, MSIZE ];
    [[ ⋯ ]]

Local outputs and states must not contain derived-dimensions (but local inputs can of course). Let q be a dimension-query part of the i'th child of the constant-dimensions of a local variable v; let vreferenced be the variable the reference child of q refers to, and let j be the value of the constant-scalar-integer-expression child of q; vreferenced must either, (1) be a block variable, or (2) be before v, or (3) be v and j < i.

R-2 (dimensional size dependencies of local variables must be cycle-free, static evaluation order of dimensional size definitions): The semantic rules for dimension-queries of local variables essentially ensure that dimensional sizes can be understood in reading order, implying that the constant-scalar-integer-expressions defining such can be statically evaluated in order, implying in turn that dependencies between dimensional sizes are cycle-free. Dependency of a higher dimensional size on a lower for the same variable are allowed however (case 3). Hence, a local input can, for example, require its arguments to be square matrices of any size via input Real m[ :, size(m, 1) ]; but the dimensional relation cannot be defined vice-versa since m[ size(m, 2), : ] is invalid.

In line with R-1, the limitation on reading order for dimensional size dependencies might be lifted in future eFMI Standard versions and instead become non-cyclic or even fixpoint based.

E-1: The constant-dimensions of the in- and output of the following function are not in order; the dimensionality of x depends on the dimensionality of the following y definition:

1
2
3
4
5
6
7
8
    function f
        input Real x[ 2 * size(y, 1) ]; /* Invalid: y not yet defined. */
        output Real y[ : ]; /* Invalid: Output has derived-dimension. */
    algorithm
       for i in 1 : 2 : size(x, 1) loop
           y[ divisionUp(i, 2) ] := x[ i ] * x[ i + 1 ];
       end for;
    end f;

A valid solution is:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
    function f
        input Real x[ : ];
        output Real y[
            (if remainderUp(size(x, 1), 2) == 0
            then divisionUp(size(x, 1), 2)
            else 0 /* Invalid if x has odd number of elements. */) ];
    algorithm
       for i in 1 : 2 : size(x, 1) loop
           y[ divisionUp(i, 2) ] := x[ i ] * x[ i + 1 ];
       end for;
    end f;

Note, that besides switching dimensional size dependencies, above solution also explicitly ensures that x has an even number of elements. If not, the requirement that dimensional sizes must be ≥ 1 is violated (cf. §2). However, the explicit check is not required and just output Real y[ divisionUp(size(x, 1), 2) ] can be used instead since the x[ i + 1 ] indexing within the for-loop will be invalid if x has an odd number of elements (cf. §4). Finally note, that there is no need to handle the NAN and OVERFLOW error signals of the divisionUp() and remainderUp() built-in functions since they are called within statically-evaluated expressions (cf. §2).

§4: Inter-functional dimensionality propagation and soundness

3.9. Side effect analysis

In contrast to typical imperative programming languages, like [ISO/IEC 9899:2024] or [ISO/IEC 7185:1990], GALEC leverages global program analyses based on inter-functional control-flows across well-defined static control-flow graphs (cf. §1) to guarantee (1) quasi-constant local inputs and loop iterators (constant w.r.t. function call-site arguments and bounded-iterations, cf. §2), (2) variables are initialized before being value-referenced for every possible control-flow (cf. §2), (3) variables and block-interface functions are reasonably used (e.g., sampling does not change parameters, cf. §2), (4) expressions with function calls are free of side effects (i.e., free of assignments to block variables such that expression parts can be concurrently evaluated, cf. §3), and (5) statements that can be safely concurrently executed (i.e., are commutable, cf. §4).

All these analyses are mandatory, except for commutable statements where a simple defensive approach is to support only sequential execution; in other words, except for target environment specific characteristics like value ranges or floating-point inaccuracies, GALEC programs guarantee by definition to be free of undefined, non-deterministic or implementation-dependent behavior due to side effects.

§1: Static control-flow graphs and inter-functional control-flows

The static control-flow graph G⦺f (a directed, connected, node-labeled graph) of a user-defined function f is defined as follows (note that nodes with a label are uniquely labeled with a syntactic term x part of f, and we just refer to x in the following if we mean the node labeled with x; further, every single statement and statement sequence s contained in f is represented by a unique control-flow block with a unique entry and exit node, and we just refer to s if we mean the control-flow block for s; it is clear by context, if we refer to a single node of a control-flow block or the block itself, i.e., if we refer to a node or a node-induced subgraph):

  1. Statement-sequence control-flow blocks: G⦺f contains a control-flow block for every statement-sequence s🞷 contained in f, consisting of an entry and exit node without label and for every child s of s🞷 the control-flow block for s (which exist according to 2-4).

  2. For-loop control-flow blocks: G⦺f contains a control-flow block for every for-loop contained in f, consisting of an entry and exit node without label, a node labeled with its loop-condition, and the control-flow block for its loop-body (which exists according to 1).

  3. If-statement control-flow blocks: G⦺f contains a control-flow block for every if-statement contained in f, consisting of an entry and exit node without label, a node for each branch-condition labeled with the respective branch-condition, and the control-flow block for each of its branch-bodies (which exist according to 1).

  4. Primitive control-flow blocks: G⦺f contains a control-flow block for every statement contained in f not already covered by 1-3, consisting of an entry and exit node without label and a node labeled with the statement.

  5. Statement-sequence control-flow edges: Let s🞷 be as defined in 1, and bentry be the entry node of s🞷 and bexit its exit node. If s🞷 has no children, G⦺f has an edge from bentry to bexit. Otherwise, let si be the i'th child of s🞷 and n be the number of children of s🞷. G⦺f has an edge from bentry to the entry node of s1 and an edge from the exit node of sn to bexit. For every si,si+1∈S🞷 with i∈ℕ+, 1 ≤ i < n, G⦺f has an edge from the exit node of si to the entry node of si+1.

  6. For-loop control-flow edges: Let bentry be the entry node of a for-loop, bexit its exit node, bcondition its loop-condition node, and bbody-entry and bbody-exit the entry and exit nodes of its loop-body respectively. G⦺f has edges from bentry to bcondition, from bcondition to bexit, from bcondition to bbody-entry, and from bbody-exit to bcondition.

  7. If-statement control-flow edges: Let bentry be the entry node of a if-statement, bexit its exit node, bcondition(i) the node of its i’th branch-condition, and bbody-entry(i) and bbody-exit(i) the entry and exit nodes of its i’th branch-body respectively. G⦺f has edges from every bbody-exit(i) with i∈ℕ+, 1 ≤ i ≤ |branch-bodies| to bexit, from bconditions(i) to bexit if |branch-conditions| = |branch-bodies|, from bentry to bcondition(1), from every bcondition(i) to bcondition(i+1) with i∈ℕ+, 1 ≤ i < |branch-conditions|, from bcondition(|branch-conditions|) to bbody-entry(|branch-bodies|) if |branch-conditions| < |branch-bodies|, and from every bcondition(i) to bbody-entry(i) with i∈ℕ+, 1 ≤ i ≤ |branch-conditions|.

  8. Primitive control-flow block edges: Let bentry be the entry node of a control-flow block according to 4, bexit its exit node, and bstatement its statement node. G⦺f has edges from bentry to bstatement and from bstatement to bexit.

The static control-flow graph G⦺f of a built-in function f consists of a single control-flow block with an unlabeled entry node connected to an unlabeled exit node.

Let f be a function and G⦺f be its static control-flow graph. Since the syntax-rule for functions contains a single statement-sequence s🞷 and no statements otherwise, the control-flow block in G⦺f for s🞷 is called the control-flow block for f.

R-1 (properties of static control-flow graphs): The control-flow blocks of a static control-flow graph G⦺f are node-induced subgraphs; they are nested starting from a single control-flow block (the control-flow block for f). The nesting of control-flow blocks reflects syntactic closest container relations between their statements (cf. §3 of Section 3.1).

Static control-flow graphs are finite for the obvious reason that they never have multi-edges and their number of nodes is finite since they are either, uniquely labeled with syntactic terms (and their number is limited per GALEC program) or are the entry or exit node of such. And there only exists a finite number of static control-flow graphs because the number of built-in functions is finite and GALEC programs can only contain a finite number of user-defined functions.

A control-flow c = (x1, …​, xn) is a tuple of nodes of static control-flow graphs with |c| ≥ 2 and where x1 and x|c| are the entry and exit nodes of the same control-flow block b respectively (hence, x1 and x|c| are nodes of the same static control-flow graph, which is not necessarily the case for other nodes of c); we call c a control-flow of b, and, if b is the control-flow block for a function f, a control-flow of f; and ∀i∈ℕ+; 1 ≤ i ≤ n we say c visits xi (as i’th node). Control-flows must be intra-functional or inter-functional.

A control-flow c = (x1, …​, xn) is intra-functional, if, and only if, there exists a static control-flow graph G⦺f such that ∀i∈ℕ+; 1 ≤ i ≤ |c|: xi is a node of G⦺f and ∀i∈ℕ+; 1 ≤ i < |c|: G⦺f has an edge from xi to xi+1 (hence, c defines a path within a single static control-flow graph through a certain control-flow block).

Inter-functional control-flows follow — beside the paths within static control-flow graphs — also virtual paths across different graphs; in fact, inter-functional control-flows must adhere to not statically-evaluated function-calls of nodes by always following one of the possible function-call sequences (if there are any). To define inter-functional control-flows, let Θ(x) be the set of all possible execution sequences of not statically-evaluated function-calls of a node x of a static control-flow graph:

  • Θ(x) must consider only not statically-evaluated function-calls contained in x, and x itself if it is such, assuming all combinations of truth-values are possible for short-circuit evaluations.

  • If x is a error-signal-check, its expression child e (if any) is treated as subject to a short-circuit evaluation that might skip the evaluation of e.

  • If the execution-order of function-calls is not defined or restricted by any semantic rule, Θ(x) must consider all valid permutations.

  • Each element of Θ(x) is a tuple of function-calls, where tuple elements (i.e., function-calls) are ordered w.r.t. the order in which they are encountered throughout the respective execution of x (hence, Θ(x) never contains a tuple t = (…​, f1, …​, f2, …​) if f1 contains f2).

  • For example, if x is not, and contains no, not statically-evaluated function-call, then Θ(x) = { () }; hence, for control-flow block entry and exit nodes Θ(x) = { () }. If x is block.v * f1(f2() + f3(), f4()), then Θ(x) = { (f2, f3, f4, f1), (f2, f4, f3, f1), (f3, f2, f4, f1), (f3, f4, f2, f1), (f4, f2, f3, f1), (f4, f3, f2, f1) }. And if x is (if v1[imin(size(v1, 1), size(v2, 1))] then block.v2 else (if f1() or f2() then f3() else f4(f6()) and f5(f7()))), then Θ(x) = { (), ( f1, f3 ), ( f1, f2, f3 ), ( f1, f2, f6, f4 ), ( f1, f2, f6, f4, f7, f5 ) }. If x is signal a or f(), then Θ(x) = { (), (f) }.

A control-flow c = (x1, …​, xn) is inter-functional, if, and only if, ∀i∈ℕ+; 1 ≤ i < |c|, either, (1) i > 1 and xi is an exit node and xi-1 is not an exit node, or, (2) xi is not an exit node and the following algorithmic check holds for xi (the algorithm updates an indexing variable j for denoting different nodes xj of c while checking xi; i.e., i and xi are constant throughout a single application of the algorithmic, but deciding if c is inter-functional typically requires |{ x | x is a non-exit node visited by c}| - 1 applications):

  1. j becomes i + 1.

  2. If xj and xi are nodes of the same static control-flow graph, it must hold that ()∈Θ(xi); continue with 3. Otherwise, it must hold that ∃α∈Θ(xi), α ≠ () such that iterating all elements of α in sequence, whereas f∈α is the current element of the iteration, the following iteration steps 2a-c hold:

    1. j ≤ |c| ⋀ xj is the entry node of the static control-flow graph of f (i.e., c must follow the f call).

    2. ∃k∈ℕ+; j < k ≤ |c|: xk is the exit node of the static control-flow graph of f ⋀ ∄l∈ℕ+; j < l < k: xl is the exit node of the static control-flow graph of f (i.e., c must leave the f call).

    3. j becomes k + 1.

  3. It must hold that j ≤ |c| ⋀ there exist an edge from xi to xj (i.e., c must continue with any direct successor of xi).

R-2 (properties of control-flows): Consider that according to R-1 static control-flow graphs are always finite; for every control-flow block of a static control-flow graph therefore exists a maximum intra-functional control-flow length after which no new visiting order for nodes — like x1 is visited (directly) before x2 — can be encountered. Further, the number of static control-flow graphs is finite, inter-functional call cycles are impossible since the static function call graph must be cycle-free according to §1 of Section 3.9, and |Θ(x)| is always finite since syntactic terms can only contain a finite number of function-calls limiting the number of possible permutations. It follows that the number of control-flows to consider for semantic rules is finite, and therefore such are decidable.

Note that the decision algorithm if a control-flow is inter-functional is only correct because inter-functional call cycles are impossible; in case of cycles, step 2b would mismatch the exit nodes of recursions, continuing the check if a node of a control-flow c satisfies inter-functional requirements with a wrong node of c. Further, side effect free expressions (cf. §3) lever Θ(x) by enabling many possible function-call sequences, in particular in combination with short-circuit evaluation. If expressions could contain competing side effects, some evaluation-order ruling would be required (assuming non-deterministic behavior is unacceptable) which in turn restricts the function-call permutations of Θ(x). But such ruling can be inadvertently restrictive; for example, although simple the approach to evaluate function-call or binary operator arguments always in order (i.e., from left to right) would also impede potential concurrent evaluation of function-calls within expressions (cf. §3:R-1). A more advanced approach would be to leave Θ(x) as is and instead use inter-functional control-flow restrictions to prohibit only side effects that are critical (cf. §3:R-2).

Since the nodes of a control-flow are uniquely labeled with syntactic terms (if they are labeled), we just use the syntactic term to denote properties of control-flow nodes; such definitions can in particular be w.r.t. parts of syntactic terms. We also use existential and universal quantification subscripts to denote if an intra- or inter-functional definition is w.r.t. a single or all possible control-flows respectively.

R-3 (data-flow analysis by means of conditional control-flows): The combination of node-induced control-flows with syntactic terms as node labels is a powerful concept. A control-flow describes a possible program execution, and restrictions on the visited syntactic terms can force additional behavior leveraging the whole range of semantic rules. Such conditional control-flows can conveniently define typical data-flow analysis, like detection of futile assignments that are dead-code.

E-1: A scalar variable v is inter-functional∃ value-referenced by a function, if, and only if, for any function there exists an inter-functional control-flow with a node whose label is, or contains, a value-reference to v; and v is intra-functional∀ assigned by a function f, if, and only if, every possible intra-functional control-flow of f has a node whose label is, or contains, an assignment to v. Likewise, an assignment s to a local state v is dead-code, if, and only if, intra-functional∀ ∄n visited after s ⋀ n contains a value-reference to v.

A common control-flow property is to value-reference-only-after-assigning; a control-flow value-reference-only-after-assigning a scalar variable v, if, and only if, it either does not value-reference v or does so only after assigning to v; it value-reference-only-after-assigning a multi-dimensional variable v, if, and only if, for all elements i of v, it either does not value-reference i or does so only after assigning to i.

Static control-flow graphs are subject to many semantic rules defining their validity: §3 of Section 3.4 restricts the control-flows of block-interface functions and thereby block-internal functions (cf. §2:R-2) to achieve well-defined block-variable initialization and intended usage (according to §2:R-1 and §4 of Section 3.4); and §2 enforces well-defined initialization of local variables and reasonable usage and assignment of such (e.g., that for every local state a control-flow using it exists and likewise assignments are with consequence for some control-flow).

R-4 (analyses based on static control-flow graphs are approximations of abstract interpretation or even dynamic analyses): Restrictions based on control-flows are static, i.e., only approximations of possible program execution behavior without any knowledge of actual values of a block instance. They are defensive in that a violation can be concluded although erratic behavior like undefined values or non-deterministic behavior is impossible throughout program execution. And vice-versa, passing static analysis does not guarantee absence of execution behavior typically considered an apparent runtime error, e.g., block states having [IEEE 754-2019] not a number values or unreachable program logic (i.e., dead code).

E-1: In the code fragment

1
2
3
4
5
6
7
        [[ ⋯ ]]
        if true then
            f1();
        else
            f2();
        end if;
        [[ ⋯ ]]

both control-flows, the one calling f1() and the other calling f2(), are considered possible, although the branch-condition always is true. As a consequence, the program is invalid according to §2:R-2 if f1() contains an assignment to a constant and f2() a value-reference to a block state even if both are only called in above if-statement.

E-2: The code fragment

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
    [[ ⋯ ]]

    function f
        output Boolean b;
    protected
    algorithm
        if true then
            b := true;
        end if;
    end f;

    [[ ⋯ ]]

is invalid according to §2 because local output b is not assigned to for every possible control-flow due to the fall-through control-flow of the if-statement.

E-3: Assume f2() is only called by the following code fragment

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
     [[ ⋯ ]]
     function DoStep
     protected
     algorithm
         if true then
             () :=! f1();
         else
             () :=! f2();
         end if;
     [[ ⋯ ]]

Function-reachability of the static function call graph (cf. §1 of Section 3.8) is not violated although the fallback branch is apparently dead code.

§2: Assignment and value-reference restrictions

Assignments must never assign to local inputs or loop iterators. Multi-assignments must not assign more than once to the same scalar variable or variable element. Let f be the function the right-hand of a multi-assignment s refers to. If, and only if, f inter-functional∃ assigns to (an element of) a block variable, s must act as procedural operation; and vice-versa, if, and only if, there exists no inter-functional control-flow for f that assigns (an element of) a block variable, s must not act as a procedural operation. If s does not act as procedural operation, it must assign to at least one variable or variable element and the output-arity of f must be greater one.

Local variables of user-defined functions, except inputs and loop iterators, must be intra-functional∀ value-reference-only-after-assigning by their containing user-defined function; local outputs (if they are multidimensionals each of their elements) must additionally be intra-functional∀ assigned. Local variables of user-defined functions, except outputs, must be intra-functional∃ value-referenced by their containing user-defined function; if they are multi-dimensionals, each of their elements must be intra-functional∃ value-referenced.

For every assignment s to (an element i of) a local state v their containing user-defined function must intra-functional∃ ∃n visited after s ⋀ n value-references v (or its i’th element).

R-1: To prohibit assignments to loop iterators is a prerequisite of the termination and dimensionality analyses defined in Section 3.8; otherwise, at runtime computed values — for which it is not possible in general to define convergence within a lower and upper bound — could update iteration variables, bearing the risk of out-of-bounds indexing and never converging loop-iteration.

To prohibit assignment to function inputs increases code comprehensibility, and enables call by reference optimization for function-call arguments (cf. §4:R-2 of Section 3.6).

The multi-assignment restrictions are required for unambiguous assignment, to ensure that whenever acting as procedural operation there indeed is potential for side effects and otherwise not, and restrict the use of multi-assignments to only exceptional cases with side effects or multiple outputs that cannot be handled by single-assignments.

Value-reference-only-after-assigning of local variables, except inputs and loop iterators, guarantees proper initialization of such before any use. Note that value-reference-only-after-assigning of local variables does not imply assignment; there can be control-flow paths where a local variable is never value-referenced and therefore does not require initialization. Only for local outputs intra-functional∀ assignment is required.

For convenience, function outputs can also be value-referenced within the algorithm computing them (as long as value-reference-only-after-assigning is satisfied) but are of course not required to do so. To require that the value (of each element if multidimensional) local variables, except outputs, is used at least in one possible control-flow is a sanity check; violations indicate dead code and program errors.

Likewise — for being dead code indicating program errors — futile assignments to (elements of) local states are prohibited.

Assignments and value-references to block variables are restricted w.r.t. the individual block-interface functions, as defined in §3 of Section 3.4. Further, block constants and parameters must be inter-functional∃ value-referenced by some function f whereas f has no inter-functional∃ assignment to the variable; if they are multi-dimensionals, each of their elements must be inter-functional∃ value-referenced by some function f whereas f has no inter-functional∃ assignment to the element. Block inputs and states must be inter-functional∃ value-referenced by the sampling function; if they are multi-dimensionals, each of their elements must be inter-functional∃ value-referenced by the sampling function. Block states must be inter-functional∃ assigned to and value-referenced without value-reference-only-after-assigning by the sampling function (but not necessarily each element if they are multidimensionals, but just some). Block outputs must be inter-functional∃ assigned to by the sampling function; if they are multidimensionals, each of their elements must be inter-functional∃ assigned to by the sampling function.

R-2 (block-interface functions indirectly restrict the assignments and value-references of block-internal functions): There are no dedicated restrictions on block-internal functions regarding assignments and value-references to block variables. Such are defined indirectly in terms of inter-functional control-flow restrictions which from a block-interface function apply on the block-internal functions called in its context. For example, a block-internal function f indirectly called throughout recalibration must, according to §3 of Section 3.4, not assign to anything but local variables and dependent parameters, nor may it value-reference block states or block outputs; if f is also called throughout reinitialization, and to that end assigns or value-references a block state, the program is invalid.

R-3: The restrictions that block variables, and in case they are multidimensionals their elements, are value-referenced are sanity checks; violations indicate dead code, program errors or wrong choice of causality.

Block constants and parameters are only meaningful if used by other functions than their respective initialization functions (why initialize something unneeded?). In general, non-input block variables that are only value-reference-only-after-assigning used in a single function should be modeled as local variable instead (which is enforced by above control-flow restrictions).

Block inputs and states (if they are multidimensionals each of their elements) should be used somehow when sampling, i.e., value-referenced by at least one possible sampling control-flow. In particular, block states are only meaningful if their value is updated and used from one sampling to another. Note however, that this is neither required for every element of a block state if it is multidimensional nor does a control-flow assigning after value-referencing have to be taken each sampling. To allow that multidimensional block states can contain some, but not all, elements that in fact could be modeled as local variable or even block parameter or constant is to ease further multidimensional arithmetics. Otherwise, temporary multidimensionals would have to be composed as local variables from the different causalities contributing. This would be cumbersome and inefficient.

Block outputs (if they are multidimensionals each of their elements) should be assigned to by the sampling function; otherwise, they are better modeled as constants or dependent parameters. Note however, that the respective restriction is only inter-functional∃ and not inter-functional∀; not every sampling has to assign (all elements of) each block output. Some can stay the same for a sampling but might be updated by another (given different control-flows).

§3: Side effect free expressions

Expressions must not contain any function-call referring to a function that contains an assignment to a block variable or, according to the static function call graph (cf. §1 of Section 3.8), transitively calls any function doing so.

R-1 (side effect free expressions and production code optimization): Function-calls whose execution assigns to block variables are therefore only permitted as multi-assignment right-hands, which, according to §4:R-1 of Section 3.6, are not expressions.

E-1: Calling a function f for its output, whereas f inter-functional∃ assigns a block variable, requires the use of a multi-assignment. The following program fragment is invalid for example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
    [[ ⋯ ]]

    Boolean b; /* Block state. */

    [[ ⋯ ]]

    function f
        input Boolean i;
        output Boolean o;
    protected
    algorithm
        o := block.b;
        block.b := i;
    end f;

    function g
    protected
    algorithm
        [[ ⋯ ]]
        if f(true) /* Invalid: Condition expression has side effect. */ then
        [[ ⋯ ]]

Instead, a help variable and a multi-assignment acting as procedural operation have to be used:

1
2
3
4
        [[ ⋯ ]]
        ( b ) :=! f(true); /* Valid: Right-hand is not an expression. */
        if b /* Valid: Condition expression has no side effect. */ then
        [[ ⋯ ]]

Using a single-assignment would be invalid too:

1
2
3
4
        [[ ⋯ ]]
        b := f(true); /* Invalid: Right-hand is an expression with side effect. */
        if b /* Valid: Condition expression has no side effect. */ then
        [[ ⋯ ]]

These rules ensure that expressions are side effect free, i.e., the evaluation of an expression will never change the state of a block instance. As a consequence, expressions are free of any competing side effects where the order of sub-expression evaluation, like that of function arguments, could matter. But expressions can contain value-references to block variables of course, and doing so while executing a function-call is no exception. Expressions therefore can depend on the state of block instances although they cannot change it.

Side effect free expressions enable many production code optimizations, like concurrent evaluation of function arguments or expression parts balanced (for example, by reordering according to commutative and distributive properties, cf. §5.2:R-2 of Section 3.6) including in particular concurrent evaluation of the function-calls contained in an expression.

R-2 (advanced expression side effect analysis based on inter-functional control-flows): Instead of prohibiting side effects for expressions all together (i.e., assignments to block variables throughout expression evaluation), one could leverage on inter-functional control-flows to decide if there are any competing value-references and assignments to the same variable, or even specific elements of multi-dimensionals. Essentially the reasoning along the lines for commutable statements in §4 could be used to prohibit only critical side effects but allow non-critical. Although well-defined and preserving all benefits of R-1 (like concurrent evaluation potential), human comprehensibility might be a concern, however, if the mental model is that expressions are for computing values only but not to update the state of block instances. To that end, and to reduce specification complexity, this approach has not been taken.

§4: Commutable statements and program execution

Let G⦺🞷 be a static control-flow graph (cf. §1); let s1 and s2 be control-flow blocks of G⦺🞷. s1 is a direct control-flow predecessor of s2, and s2 a direct control-flow successor of s1, if and only if, G⦺🞷 has an edge from the exit node of s1 to the entry node of s2.

Let Ax be the set of variables assigned to by the possible inter-functional∃ control-flows of a control-flow block x, and Vx bet the set of variables value-referenced; and let E+x be the set of error signals set by the statement-sequence, statement, or function of which x is the control-flow block for and let E-x be the error signals unset (cf. §1 of Section 3.10). A direct control-flow predecessor p and its successor s are commutable, if, and only if, (Ap ∩ Vs) ∪ (As ∩ Vp) = ∅ and (E+s ∩ E-p) ∪ (E+p ∩ E-s) ∪ (E-p ∩ E-s) = ∅.

Commutable control-flow blocks can be swapped — without impact on the truth value of syntactic and semantic rules, including program execution — as follows. Let s1 and s2 be commutable, with s1 being the direct control-flow predecessor of s2. Edges having the entry node of s1 as target instead target the entry node of s2; and vice-versa, edges having the exit node of s2 as source instead originate from the exit node of s1. Edges from the exit node of s1 to the entry node of s2 are reversed (i.e., the direct control-flow predecessor/successor relation becomes inverse).

Assume each static control-flow graph has been subject of arbitrary many commutable control-flow block swaps. Execution of a block-interface function f starts at the entry node of its static control-flow graph and continues according to the inter-functional control-flow unfolding w.r.t. the execution of statements and evaluation of expressions defined in Section 3.5 and Section 3.6 respectively, whereas commutable control-flow blocks can be concurrently executed but non-commutable must be executed sequentially.

R-1 (advanced, control-flow blocks crossing, transformations of static control-flow graphs): The current definition of commutable control-flow blocks does not comprise all kind of execution-semantic-invariant order-of-execution-transformations that could be concluded from inter-functional control-flows. In particular, control-flow blocks can only be swapped as a whole within a static control-flow graph (rearranging parts across control-flow blocks, like pulling statements out of a block, or between control-flow graphs is not permitted), although there are cases where such transformations can be beneficial (not only for concurrent evaluation but also, for example, for optimized register allocation or to avoid computations). Improvements in that direction have not been taken because of specification complexity, but production code generators are free to do any execution-semantic-invariant order-of-execution-transformations. The defined commutable statement rule mainly serve as a proof of concept of the guarantees the design of GALEC enables.

3.10. Error handling

GALEC incorporates dedicated language means for systematic, reliable and guaranteed error handling. Three integrated concepts can be distinguished: (1) error signals with enforced signal handling seamlessly incorporated into normal program control-flow, (2) well-defined floating point operations with guaranteed quiet not a number propagation and (3) variable ranges for guaranteed block saturation. Together, these concepts enable delayed, but ensured error handling avoiding any need to immediately check each and every possible failing operation by means of a plethora of exceptions.

The following sections present these three concepts.

§1: Error Signals

§1.1: Error-signal-declaration semantic

An error-signal-declaration D of the from

1
error-signal-declaration = "signal", simple-identifier, ";" ;

is called an error signal. The name of an error signal is the name of its contained simple-identifier; its name must be unique within the block D is part of.

Let Cpredefined be the following sequence of characters

1
2
3
4
5
6
signal INVALID_ARGUMENT;
signal OVERFLOW;
signal NAN;
signal SOLVE_LINEAR_EQUATIONS_FAILED;
signal NO_SOLUTION_FOUND;
signal UNSPECIFIED_ERROR;

Cpredefined implicitly follows the characters matched by the 5th child of block; its error signals are called predefined. Any other error signals are called user-defined.

R-1 (purpose of pre-defined error signals / Runtime-semantic): Above specification implies that pre- and user-defined error signals are error signals and can therefore be explicitly signaled and checked by user-code.

The typical application of pre-defined error signals is however not block function internal error handling, but to expose block-interface function errors to the runtime environment (cf. §1.3 and §1.6). The intended meaning of each pre-defined error signal is:

  • INVALID_ARGUMENT: A domain error occurred due to invalid (combination of) built-in or user-defined function arguments, block-interface inputs or tunable parameters.

  • OVERFLOW: A floating-point operation yielded -∞, +∞ or 0 although the real-arithmetic result is different.

  • NAN: A floating-point operation yielded qNaN. Usually only signaled if the operation is not visible otherwise (e.g., by block-interface outputs becoming qNaN) and therefore could slip-through unnoticed if not signaled.

  • SOLVE_LINEAR_EQUATIONS_FAILED: Solving a linear system of equations failed.

  • NO_SOLUTION_FOUND: A solution for a mathematical problem cannot be found, e.g., if interpolation fails or an optimization problem cannot be solved.

  • UNSPECIFIED_ERROR: Not further specified error. Typically used if none of the above more specialized error signals fits.

§1.2: Error-signal-statement semantic

A error-signal statement S of the form

1
2
3
4
error-signal-statement =
    "signal",
    simple-identifier,           (* Set of signals set, at least one AND/OR signal-closure propagation *)
    { ",", simple-identifier } ; (* Set of signals set, at least one AND/OR signal-closure propagation *)

has the following semantic:

  1. Each simple-identifier s of S referring to a signal-closure variable s in scope sets all the signals of s whenever S is executed (cf. §1.4 for the definition of signal-closure variables).

  2. Any other simple-identifier s of S must refer to an error signal e. Whenever S is executed, e is set.

  3. The union of all error signals set by S is called the signal-set of S.

§1.3: Functional error interface and exposed error signals

A function-definition f of the form

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
function-definition =
    "function",
    name,
    [ error-signal-interface ],
    (* Local inputs, followed by local outputs: *)
    { public-function-variable-definition },
    "protected",
    (* Local states: *)
    { protected-function-variable-definition },
    "algorithm",
    statement-sequence,
    "end",
    name,
    ";" ;

error-signal-interface = "signals", simple-identifier, { ",", simple-identifier }, ";" ;

has the following semantic w.r.t. error handling:

  1. Let all simple-identifiers contained in the 3rd child of f form the signal-set S of f. Each element s of S must refer to an error signal e; each such e is called an exposed error signal of f and f is said to expose e.

  2. Block-interface functions must not expose user-defined error signals.

  3. The signal-set of f must be identical to the out-reachable-signals-set an imaginary final statement following the last statement of f would have (cf. §1.5 for the definition of out-reachable-signals-set).

§1.4: Error-signal-check semantic

An error-signal-check of the form

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
error-signal-check =
    "signal",
    [ simple-identifier ],     (* Optional signal-closure *)
    [
        [ "not" ],                    (* Optional signal-test-negation *)
        "in",
        simple-identifier,            (* Set of signals tested, at least one *)
        { ",", simple-identifier  },  (* Set of signals tested, at least one *)
    ],
    [ "or", expression ] ;     (* Optional fallback-condition *)

has the following semantic:

  1. A signal-closure is a scoped variable that captures the current error-state (i.e., all the currently set error signals). Its scope is, similar to loop iterators, the branch-body of the error-signal-check — called error-signal-check-body. A signal-closure must never be assigned to.

  2. We define the signal-test-set of an error-signal-check as follows (cf. §1.5 for the definition of in-reachable-signals-set ):

    • At least one signal tested is given: If, and only if, no signal-test-negation is given, the signal-test-set comprises all signals tested; otherwise, it comprises the signals of the in-reachable-signals-set of the error-signal-check minus the set of all signals tested.

    • No signal tested is given: The signal-test-set is the in-reachable-signals-set; the error-signal-check is called unrestricted.

The signal-test-set must be non-empty and a subset of the in-reachable-signals-set of the error-signal-check.

  1. An error-signal-check is signal-satisfied, if, and only if, any of the signals of its signal-test-set is set when it is executed.

  2. An error-signal-check is conditional-satisfied, if, and only if, it is not signal-satisfied and has an optional fallback-condition that is satisfied when the error-signal-check is executed.

  3. An error-signal-check is satisfied if it is signal-satisfied or conditional-satisfied.

  4. The error-signal-check-body B of an error-signal-check C is the executed branch-body of its if-statement, if, and only if, C is satisfied. In this case, all signals of the signal-test-set of C are unset immediately before the execution of B but after initializing the signal-closure if any.

§1.5: Error signal propagation semantic: static signal propagation analysis and reachable-signals-set

§1.3 and §1.4 require that (1) functions only expose error signals that can be signaled within their body but are not checked thereafter for any of their possible control-flows and (2) error-checks only check for error signals that can be set according to their preceding control-flow. To enforce these restrictions, a static analysis deciding which error signals could be set at any point of execution is required.

To that end, we define for expressions and statements which additional error signals they can set — their signal-set — and for statements and the branches of if-statements, particularly error-signal-check branches, which error signals can be set right before their execution and right after — their in-reachable-signals-set and out-reachable-signals-set.

The signal-sets of expressions and statements are:

  1. The signal-set of a function-call is the referred function’s signal-set. The signal-set of any other expression is the union of the signal-sets of its contained function-calls.

  2. The signal-set of single-assignments and multi-assignments is the signal-set of their right-hand.

  3. The signal-set of a for-loop is the out-reachable-signals-set of its last statement.

  4. The signal-set of an if-statement is the union of the out-reachable-signals-sets of the last statements of its branch-bodies.

The in-reachable-signals-sets and out-reachable-signals-sets of statements and the branches of if-statements are:

  1. The in-reachable-signals-set of the first statement S of a function-body is the empty set.

  2. The in-reachable-signals-set of the first branch-condition of an if-statement S is the in-reachable-signals-set of S; for any further branch-condition of S it is the out-reachable-signals-set of its preceding branch-condition (important: preceding branch-condition, not branch-body of preceding branch).

  3. The in-reachable-signals-set of the branch-body of a branch B of an if-statement is the out-reachable-signals-set of the branch-condition of B.

  4. The in-reachable-signals-set of any other statement S is the union of the out-reachable-signals-sets of all its preceding statements (according to control-flow).

  5. The out-reachable-signals-set of an error-signal-check branch-condition is its in-reachable-signals-set minus its signal-test-set, finally unified with the signal-set of its fallback-condition if any. The out-reachable-signals-set for a non error-signal-check branch-condition is its in-reachable-signals-set unified with the signal-set of its condition.

  6. The out-reachable-signals-set of an if-statement is the out-reachable-signals-set of its last branch-condition unified with its signal-set.

  7. The out-reachable-signals-set of any other statement is its in-reachable-signals-set unified with its signal-set.

§1.6: Production Code and exposing error signals to the runtime environment

Since block-interface functions can only expose the 6 pre-defined error signals (cf. §1.3), a definition of signal-communication with the runtime environment is only required for such. To that end a unique mapping of each pre-defined error signal to a unique bit position within a 32 bit integer value is defined. These mappings are bidirectional, such that all exposed error signals can be returned to the runtime environment encoded in a single 32 bit integer value. The bit positions of the pre-defined error signals are:

  • Bit 0: INVALID_ARGUMENT

  • Bit 1: OVERFLOW

  • Bit 2: NAN

  • Bit 3: SOLVE_LINEAR_EQUATIONS_FAILED

  • Bit 4: NO_SOLUTION_FOUND

  • Bit 5: UNSPECIFIED_ERROR

Bit positions 6 to 15 of the returned error value are reserved for the future if there is need to add further pre-defined error signals in later specification versions; for now these bits must be never set by error values returned to the runtime environment.

To enable easy Production Code generator implementation by encoding all error signals — i.e., pre- and user-defined — in single, uniquely laid out (i.e., uniform bit position accessible) 32 bit integer values, GALEC programs must contain at most 16 user-defined error signals (i.e., 32 - 6 pre-defined - 10 reserved).

R-1 (need for bit-wise pre-defined error signals for Behavioral Model representation based testing): It is important to enable reference testing of the exposed error signals of block-interface functions. Besides the common case to ensure no errors are encounted, also testing for expected errors — if for example a block is misused outside its required operational range — are deliberately supported by eFMI Behavioral Model representations (cf. §1.1 and §4 of Section 5.2). Such tests require a reference trajectory for the expected error signals, whose values are in turn compared to the actual error signal values exposed by tested production or binary code. Hence, a well-defined encoding of exposed error signal values is required. To that end, exposed error signal values are restricted to pre-defined error signals encoded according to §1.6 (cf. also §1.1:R-1).

Examples

E-1: The following example sketches a typical mixed-mode coding style, where some error cases are avoided in the first place by special operation modes of the controller and others are treated after something failed by testing for respective error signals:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
    Safe common control-code, potentially selecting or deselecting special
    modes of operation:
*/
...
v := f(A); /* Assume f may signal the error f_ERROR. */
...
if signal in f_ERROR or not(check(v)) then
    /*
        Error-handling path if f(A) signaled an f_ERROR or
        returned a v not satisfying some check:
    */
    ...
elseif block.operation_mode == 1 then
    /*
        Safe control-code for some special operation mode:
    */
    ...
elseif block.operation_mode == 2 then
    /*
        Safe control-code for some special operation mode:
    */
    ...
else
    /*
        Control-code for normal mode of operations:
    */
    ...
    x := solveLinearEquations(A, b * v);
    ...
    if signal in SOLVE_LINEAR_EQUATIONS_FAILED then
        /*
            Handle the special case that the system of linear equations
            has no solution:
        */
        ...
    elseif signal then
        /*
            Handle any other unexpected error of the NORMAL operation mode:
        */
        ...
    end if;
end if;

if signal s then
    /*
        The common control-code or the special modes of operation that are
        supposed to be safe missed some error case or introduced
        errors themselves. We now can set the block outputs and state
        variables to some reasonable default values, e.g., reinitialize
        the controller, and propagate the unexpected error signals to the runtime environment:
    */
    ...
    signal s;
end if;

E-2: The following example summarises all possible combinations of error signaling and checking:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
function f
/*
    (1) Signal interface of functions (signals exposed to callees):
*/
signals invalid_gear_switch, to_high_velocity;
protected
algorithm
    ...
    /*
        (2) Universal signal checks, catching and un-setting all signals set:
    */
    if signal then
        ...
    end if;
    ...
    /*
        (3) Specialized signal checks, catching and un-setting
            all signals within a specific set:
    */
    if signal in error1, error2 then
        ...
    end if;
    ...
    /*
        (4) Restricted universal signal checks, catching any signal that is
            not within a certain set:
    */
    if signal not in invalid_gear_switch, to_high_velocity then
       ...
    end if;
    ...
    /*
        (3) Checks with signal variables capturing all signals
            set at the check point:
    */
    if signal s then
        ...
        /*
            (4) Propagation of signal variable, i.e., reset all
                captured signals (they have been unset by the previous check):
        */
        signal s;
        ...
    else
        ...
    end if;
    ...
    if ... then
        ...
        /*
            Explicit setting of signals, i.e., signaling of errors:
        */
        signal invalid_gear_switch, to_high_velocity;
        ...
    end if;
    ...
    /*
        (*) And all kind of combinations of the above
            (signals to check with signal variables, signal
            propagation and explicit signaling):
    */
    if signal s in f1_error, f2_error or condition1 then
        ...
        signal s, invalid_gear_switch;
        ...
    elseif signal s not in invalid_gear_switch, to_high_velocity or condition2 then
        ...
        signal s;
        ...
    end if;
    ...
    /*
        Catch all signals not exposed according to the function's interface:
    */
    if signal not in invalid_gear_switch, to_high_velocity then
    end if;
end f;

E-3: The following example shows typical violations of error signal propagation, demonstrating the advantages of a strict static signal-propagation analysis for code hardening:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
function f
/*
    Invalid: Exposed error signal can never be signaled.

    Error1 is always handled on all possible control-flow
    paths within the function.

    Invalid: Uncatched error signal not exposed.

    There exists a control-flow path within the function
    on which Error2 is signaled, but never handled.
*/
signals UNSPECIFIED_ERROR;
    input Real i;
    output Real o;
protected
algorithm
    if i > 100.0 then
        signal Error1;
    elseif i > 200.0 then
        signal Error2;
    end if;
    o := 2.0 * i;
    if signal in Error1 or o > 350.0 then
        o := 350.0;
    end if;
end f;

function DoStep
/*
    Invalid: Uncatched error signal not exposed.

    There exists a control-flow path within the function
    on which UNSPECIFIED_ERROR is signaled, but never handled.

    Invalid: Block-interface function exposes not
             pre-defined error signal.

    Error1 is not a pre-defined error signal.
*/
signals Error1;
protected
algorithm
    ...
    f(1.0);
    ...
    if signal s then
        ...
        s := Error1; /* Invalid: Signal-closures must not be assigned to. */
    elseif signal in Error1 then
        /*
            Invalid: Signal-test-sets must be non-empty.

            The preceding branch already handles all error signals since it
            is an unrestricted error-signal-check.
        */
    end if;

    signal Error1;

    if signal in Error1, UNSPECIFIED_ERROR then
        /*
            Invalid: The signal-test-set is not a subset of the
                     in-reachable-signals-set.

            UNSPECIFIED_ERROR can never be set at this point.
        */
        ...
        signal UNSPECIFIED_ERROR;
    elseif signal in UNSPECIFIED_ERROR then
        /*
            Invalid: The signal test-set is not a subset of the
                     in-reachable-signals-set.

            UNSPECIFIED_ERROR can never be set at this point.
            The signal-set of the error-signal-check-body of the
            preceding branch cannot be handled by this branch;
            it requires handling in a completely separate if-statement.
        */
    end if;

    signal Error1;
    if signal in Error1 then
    end if;
    if signal in Error1 then
        /*
            Invalid: Signal-test-sets must be non-empty.

            The preceding if-statement already implicitly unsets
            Error1 when its single error-signal-check is satisfied.
        */
    end if;

    signal Error1;
end DoStep;

function Startup
protected
algorithm
    /* signal in E; */
    /*
        The following if-statement is invalid even if the
        previous line is uncommented.
    */
    if signal not in E then /* Invalid: Signal-test-sets must be non-empty. */
    end if;
end Startup;

Example 4: The following function fragment investigates interesting corner-cases of error signal propagation. It is well-suited to exercise the formal definitions of signal-set, in-reachable-signals-set and out-reachable-signals-set of if-statements. The left-out code hooks denoted by …​ are assumed to be arbitrary code not setting or checking error signals.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
function f
    signals f_Error;
    output Boolean b;
protected
algorithm
    b := true;
    signal f_Error;
end f;

function DoStep
    ...
algorithm
    ...
    if signal then /* Unset all error signals. */
    end if;
    signal in TestDefinitions1, TestDefinitions2;
    if signal in TestDefinitions1 then
        ...
        signal TestDefinitions3;
        ...
    elseif signal in TestDefinitions2 then
        ...
        if signal TestDefinitions3 then
            ...
        end if;
        ...
    elseif signal in TestDefinitions3 then
        ...
    end if;
    /*
        At this point still TestDefinitions2 and TestDefinitions3 WILL be
        set because only the first branch was tested, its test signal-satisfied,
        the tested signal TestDefinitions1 unset and its body executed.
    */
    ...
    if signal then /* Unset all error signals. */
    end if;
    signal TestDefinitions1, TestDefinitions2;
    if signal in TestDefinitions1 then
        ...
        if signal in TestDefinitions2 then
            ...
        end if;
        ...
    end if;
    /* At this point no error signals WILL be set. */
    ...
    /*
        Assume for the following code an execution where NotSetSignal
        is not set:
    */
    if signal not in NotSetSignal then /* Unset all error signals except NotSetSignal. */
    end if;
    i := 2;
    if signal in NotSetSignal or f() /* Cf. definition of f above! */ then
        i := 2 * i;
    elseif signal in f_Error then
        i := 2 * i;
        signal f_Error;
    /*
    The following branch would be invalid, because f_Error can never be set when it is tested:
    elseif signal in f_Error then
        i := 2 * i;
    */
    end if;
    /* At this point i WILL be 8 and f_Error set. */
end DoStep;

§2: -∞, +∞ and quiet not a number propagation

GALEC assumes that the target environment of the generated production code is compliant to [IEEE 754-2019]. Even if GALEC code is as much as possible target environment independent, there are corner cases in which the properties of the target environment need to be taken into account in GALEC. If a target environment is not fully compliant to [IEEE 754-2019], it should still be possible to map GALEC code to such since only a small subset of [IEEE 754-2019] is used and/or potential deviations in corner cases might still be acceptable [(for example, if a processor does not support -∞ or +∞ handling, but saturates automatically to the largest/smallest representable floating point number)].

The language assumes, following Section 6 of [IEEE 754-2019], that exception handling of the processor is configured so that an overflow of Real numbers is handled automatically by the processor for all language operators without generating exceptions by mapping negative and positive overflows to -∞ and +∞ respectively (e.g. 2.0 < 1.0 / 0.0 is true). With built-in function isInfinite(r) it can be inquired whether a Real variable r is -∞ or +∞ (e.g. isInfinite(1.0 / 0.0) returns true).

The language also assumes that [IEEE 754-2019] exception handling of the processor is always configured to never generate an exception in case of underflow of Real numbers (so deviating from the default exception handling of Section 7.5 of [IEEE 754-2019]).

If the result of a mathematical operation on Real numbers is mathematically undefined (for example lg(-1.0) or 0.0 / 0.0), then the standard operators of the language return quiet not a number (qNaN) as defined by Section 7.5 of [IEEE 754-2019]. It is assumed that the processor is configured so that qNaN values are automatically propagated through all operations without generating exceptions (hence quiet not a number). With built-in function isNan(r) it can be inquired whether a Real variable r has qNaN as value or not.

All relational operators (<, >, <=, >=, ==, <>) trigger error signal NAN if one of their operands is qNaN. In such a case the operator returns false. Conceptually, every relational operator a ⊕ b is mapped to a built-in function call f_⊕(a, b) with f_⊕ defined as:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function f_⊕
   signals NAN;
   input Real a;
   input Real b;
   output Boolean y;
algorithm
   if isNan(a) or isNan(b) then
      signal NAN;
      y := false;
   else
      y := a ⊕ b;
   end if;
end f_⊕;

[In C this function can be implemented efficiently for example as the expression (isNan(a) || isNan(b) ? (error_signal |= Bitmask setting NAN, 0) : a ⊕ b).]

All built-in functions that can have qNaN input arguments and are not able to propagate qNaN because the output argument(s) are not of type Real trigger the NAN error signal (cf. §2:R-1 of Section 3.11).

[Note, potential issues as sketched in Agner 2019 are not critical because relational operators and built-in functions trigger the NAN error signal if a qNaN value cannot be propagated.]

For some built-in functions ⊕ with potential domain errors causing qNaN results, also companion built-in functions are provided that do not return qNaN provided none of the arguments is qNaN. These functions are named ⊕Safe and avoid domain errors by automatic limitation of their input argument(s) (cf. §2 of Section 3.11).

§3: Variable Ranges, explicit and implicit limitation and block saturation

All variables can be declared with range attributes min and/or max; variables with range attributes are called ranged.

Ranged variables are limited to their defined range at a particular point of execution by means of limit-assignments of the form:

1
2
3
4
limit-assignment =
    "limit",
    ( "block" | reference ),
    { ",", ( "block" | reference ) } ;

If a variable v is ranged with lower bound ⊥ and upper bound ⊤, then the statement limit v; is equivalent to v := (if v < ⊥ then ⊥ elseif v > ⊤ then ⊤ else v);. If v has only a lower bound ⊥, limit v is equivalent to v := (if v < ⊥ then ⊥ else v);. If v has only an upper bound ⊤, limit v; is equivalent to v := (if v > ⊤ then ⊤ else v);. Limiting a non-ranged entity has no effect.

[Above definition implies that limitation on qNaN values has no effect (the variable’s value remains qNaN).]

limit can also be used to limit all state variables according to their ranges (using keyword block), or all nested state variables of a certain state component (by referring to that very state component):

1
2
limit block; /* Limits all ranged state variables. */
limit c; /* Assume c refers to a state component: limits all nested state variables of c. */

A single limit statement can limit a set of entities. For example,

1
limit block.c.d.vc, block.v, block.c, l;

limits the variable block.c.d.vc (assuming block.c.d refers to a state component and d is one of its variables), the state variable block.v (assuming block.v refers to a state variable), all nested variables of the state component block.c (assuming block.c refers to a state component) and the local variable l.

Every block-interface function implicitly limits all state entities whenever the function is entered and when it returns, except Startup(), which only limits on returning. The implicit semantic is:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function Startup
protected
    ...
algorithm
    ...
    /* initialize stuff */
    ...
    limit block; /* Implicit by semantic of language. */
end Startup;

function DoStep
protected
   ...
algorithm
   limit block; /* Implicit by semantic of language. */
   ...
   /* compute stuff */
   ...
   limit block; /* Implicit by semantic of language. */
end DoStep;

function InitializeDependentParameters
protected
   ...
algorithm
   limit block; /* Implicit by semantic of language. */
   ...
   /* compute stuff */
   ...
   limit block; /* Implicit by semantic of language. */
end InitializeDependentParameters;

Every function implicitly limits its inputs whenever the function is entered and its outputs when it returns.

[Implicit limitation at the very beginning and end of block-interface functions means, that from the perspective of the runtime environment ranged state variables are effectively saturated at their defined ranges; the block as such is saturated and guarantees operation within its limits (except for state variables with qNaN values that need special error handling).

Production Code generators are free to optimize and minimize limitation of variables. For example, limitation of constants, tunable parameters and dependent parameters will never be required in DoStep(), since such cannot be assigned new values and their limitation is already performed in Startup() and InitializeDependentParameters() respectively. Limitation of inputs is only needed at the very beginning of DoStep() code, because inputs are not changed afterwards. Limitation of outputs is only needed at the end of the DoStep() code. Limitation of states needs to be performed only at the end of Startup() and the end of DoStep(), because the states are just passed between DoStep() calls and then it is guaranteed that a state that is limited at the end of the previous DoStep() call remains limited at the very beginning of the next DoStep() call. Furthermore, interval arithmetic analyses can be used to conclude that a variable will never be outside of its valid range, such that limitation code for it can be avoided.

The rationale why limitation is not implicitly performed on every assignment to a ranged variable (i.e., why GALEC has no strict saturation arithmetic) is, that numerical algorithms and particularly integration typically fail if values are not continuous over time. For example, an integration algorithm such as a Runge-Kutta method of order 4 may not work as expected, if states are limited during one step because the smoothness requirements of the integration method are violated. Furthermore, limitations in the middle of computations often inadvertently break algebraic characteristics like distributivity and commutativity that are essential for symbolic processing and optimization. These pitfalls of limitation are however not violated by the implicit limitations at the very start and end of block-interface functions; the block as such — its interface — is saturated from the perspective of the runtime environment. Throughout the execution of a block-interface function however, variables may very-well get values assigned outside of their defined ranges. ]

§4: Error Handling Recommendations

In practice it is typically required that all block outputs are guaranteed to never be qNaN and always be within their defined ranges. To that end, the following actions are recommended:

  • Define ranges for state variables, particularly block inputs, outputs and tunable parameters. Implicit limitation will guarantee, that the state variables are in their defined ranges when a block-interface function returns.

  • Before leaving DoStep(), check that none of the block outputs is qNaN and that the error signal is not NAN. If one of these conditions does not hold, take appropriate actions, for example restore the state from the previous sample instant, compute the block outputs with a backup algorithm (e.g. P-controller) that does not produce qNaN values, or provide a default block output, e.g. zero. In any case, the returned outputs should never be qNaN.

  • Use the ⊕Safe built-in functions if possible, in order that qNaN values are not generated (cf. §2 of Section 3.11).

3.11. Built-in Functions

GALEC provides a set of built-in functions for typical mathematical operations (like solving linear equation systems or interpolation), to abstract from target environment specific characteristics (like type ranges), enable target environment specific optimizations for common routines and properly integrate such with the error handling concepts of Section 3.10.

§1: Scope of built-in functions

All built-in functions are implicitly available such that function lookup (cf. §3 of Section 3.7) can find them without the need to be defined anywhere in the GALEC program; the signatures and semantic of built-in functions are according to §2. The implementation of built-in functions must not assign to or value-reference block variables. Otherwise, built-in functions are ordinary GALEC functions by all means.

L-1 (implications of built-in functions being ordinary functions) Since built-in functions are ordinary functions, it follows that their names must be unique and cannot be used by user-defined functions or variables (cf. §1 of Section 3.7), their in- and outputs are automatically limited if ranged (cf. §3 of Section 3.10), error signals set in the environment of the function-call site are not visible when they start execution (cf. §1.5 of Section 3.10), they return error signals according to their function signature (cf. §1.3 of Section 3.10), etc.

According to §2 of Section 3.8, statically-evaluated expressions must be applied already for Production Code generation since they define dimensional-sizes, multidimensional queries and loop iteration which are subject of value-related well-formedness constraints; built-in function calls within statically-evaluated expressions are no exception. The well-formedness and results of such statically-evaluated built-in function calls depend on the target environment however. For example, in a 32-bit floating-point environment the expression integer(roundUp((2.0^31) - 1.0)) likely is an error due to an integer overflow, which in turn would result in integer signaling OVERFLOW which is not permitted within statically-evaluated expressions (cf. §2 of Section 3.8). Likewise, the value of a statically-evaluated expression calling the epsReal built-in function depends on the target environment.

§2: Signatures and semantic of built-in functions

The following table summarizes all built-in functions, their signatures (as required for respective function-calls) and semantic.

For most scalar argument built-in functions also vector and matrix argument versions exist. The table defines such lifted versions together with their scalar versions by listing the supported dimensionalities via Lifts to. The lifted versions have the same function signatures as their scalar version (signaled errors, number of in- and outputs and their types and ranges), only with the dimensionality of in- and outputs consistently lifted from scalar to a certain multidimension. Their semantic is an element-wise application of their respective scalar version on all input arguments and return the resulting multidimensional(s). Any error signals of scalar function applications are just propagated.

The semantic of each built-in function (right table column) is defined from the most common towards the most specific case, i.e., from the error-free standard behavior towards special corner cases and error signaling. The priority is vice-versa however; first the special cases are checked in reverse order before the standard case, whereas the first case satisfied for the given arguments that defines a return value is applied. Any error signaling case satisfied throughout this reverse resolution that is not aborting the resolution by defining a return result is also applied (i.e., the respective error signaled).

E-1 (from most specific towards common case built-in function resolution): To exemplify how to read the built-in function definition table, consider the following definition:

function f
  signals S1, S2;
  input Real x1;
  input Real x2
    (min = -1.0);
  output Real y;

The f of x1 and x2.

Signals S1 and returns 0.0 if x1 is 0.
Returns -∞ if x1 is -∞.
Signals S2 if x2 is +∞.
Returns qNaN if x1 or x2 are qNaN.

The following table summarizes the result and errors signaled for some example arguments:

x1 x2 y errors signaled

qNaN

+∞

qNaN

-∞

qNaN

qNaN

-∞

+∞

-∞

S2

0.0

+∞

0.0

S2, S1

+∞

+∞

f of +∞ and +∞

S2

+∞

-∞

f of +∞ and -1.0

pi()

euler()

f of π and ℯ

Note, that x2 is lower-bound limited at -1.0, for which reason it would make no sense to define the case "Returns -∞ if x1 is -∞" as "Returns -∞ if x1 or x2 are -∞".

The built-in functions of GALEC are:

Properties of Integer

function minInteger
  output Integer i;

Target environment specific smallest Integer.

function maxInteger
  output Integer i;

Target environment specific largest Integer.

Properties of Real

function minReal
  output Real r;

Target environment specific smallest r <> minusInfinite().

function maxReal
  output Real r;

Target environment specific largest r <> plusInfinite().

function posMinReal
  output Real r;

Target environment specific smallest r > 0.0.

function epsReal
  output Real r;

Target environment specific smallest r > 0.0 such that 1.0 + r <> 1.0.

function nan
  output Real r;

Target environment specific quiet not a number representation (qNaN).

function isNan
  input Real r;
  output Boolean b;

true if r is a target environment specific not a number representation (including qNaN); otherwise false.

function minusInfinite
  output Real r;

Target environment specific -∞ representation.

function plusInfinite
  output Real r;

Target environment specific +∞ representation.

function isInfinite
  input Real r;
  output Boolean b;

true if r is -∞ or +∞; otherwise false.

function isFinite
  input Real r;
  output Boolean b;

true if r is finite (neither -∞ nor +∞ nor qNaN); otherwise false.

Multidimensional properties of Real

function hasNan1D
  input Real r[:];
  output Boolean b;

true if at least one element of r is qNaN; otherwise false.

function hasNan2D
  input Real r[:, :];
  output Boolean b;

true if at least one element of r is qNaN; otherwise false.

function hasInfinite1D
  input Real r[:];
  output Boolean b;

true if at least one element of r is -∞ or +∞; otherwise false.

function hasInfinite2D
  input Real r[:, :];
  output Boolean b;

true if at least one element of r is -∞ or +∞; otherwise false.

function allFinite1D
  input Real r[:];
  output Boolean b;

true if all elements of r are not -∞, +∞ or qNaN; otherwise false.

function allFinite2D
  input Real r[:, :];
  output Boolean b;

true if all elements of r are not -∞, +∞ or qNaN; otherwise false.

Numeric type conversions

All built-in functions in this category:

  • Lift to 1-2D.

function real
  signals OVERFLOW;
  input Integer i;
  output Real r;

Convert Integer i to nearest (cf. [IEEE 754-2019]) Real.

Returns -∞ if i < roundTowardZero(minReal()).
Returns +∞ if i > roundTowardZero(maxReal()).
Signals OVERFLOW if the integer value of i cannot be exactly (cf. [IEEE 754-2019]) represented as Real.

function integer
  signals NAN,
          OVERFLOW;
  input Real r;
  output Integer i;

Convert Real r to Integer by truncation (roundTowardZero(r)).

Signals OVERFLOW and returns 0 if NAN is not signaled and r cannot be represented as Integer (i.e., if r is -∞ or +∞ or r < minInteger() or r > maxInteger()).
Signals NAN and returns 0 if r is qNaN.

Direct Real rounding

All built-in functions in this category have a single argument r and:

  • Return -∞ if r is -∞.

  • Return +∞ if r is +∞.

  • Return qNaN if r is qNaN.

  • Lift to 1-2D.

function roundDown
  input Real r;
  output Real r_rounded;

Round r to nearest integer toward -∞ (also known as floor function).

function roundUp
  input Real r;
  output Real r_rounded;

Round r to nearest integer toward +∞ (also known as ceiling function).

function roundTowardZero
  input Real r;
  output Real r_rounded;

Round r to nearest integer toward 0 (also known as truncation).

function roundAwayZero
  input Real r;
  output Real r_rounded;

Round r to nearest integer away 0 (also known as round toward ±∞).

Nearest Real rounding (using a tie-breaking rule)

All built-in functions in this category have a single argument r and:

  • Return -∞ if r is -∞.

  • Return +∞ if r is +∞.

  • Return qNaN if r is qNaN.

  • Lift to 1-2D.

function roundHalfDown
  input Real r;
  output Real r_rounded;

Round r to nearest integer; if the fractional part f is 0.5 toward -∞, f < 0.5 toward 0, otherwise away 0 (also known as round half toward -∞).

function roundHalfUp
  input Real r;
  output Real r_rounded;

Round r to nearest integer; if the fractional part f is 0.5 toward +∞, f < 0.5 toward 0, otherwise away 0 (also known as round half toward +∞).

function roundHalfTowardZero
  input Real r;
  output Real r_rounded;

Round r to nearest integer; if the fractional part f is ≤ 0.5 toward 0, otherwise away 0 (also known as round half away ±∞).

function roundHalfAwayZero
  input Real r;
  output Real r_rounded;

Round r to nearest integer; if the fractional part f is ≥ 0.5 away 0, otherwise toward 0 (also known as round half toward ±∞).

function roundHalfToEven
  input Real r;
  output Real r_rounded;

Round r to nearest integer; if the fractional part f is 0.5 the even nearest integer, f < 0.5 toward 0, otherwise away 0 (also known as convergent rounding, statistician’s rounding, Dutch rounding, Gaussian rounding, odd–even rounding or bankers' rounding).

function roundHalfToOdd
  input Real r;
  output Real r_rounded;

Round r to nearest integer; if the fractional part f is 0.5 the odd nearest integer, f < 0.5 toward 0, otherwise away 0.

Rounded Integer division

All built-in functions in this category have two arguments dividend and divisor and:

  • Signal OVERFLOW and return 0 if NAN is not signaled and the result cannot be represented as Integer (including the case that divisor is 0 but not dividend).

  • Signal NAN and return 0 if dividend and divisor are 0 (i.e., division by 0).

function divisionDown
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer quotient;

Divide dividend by divisor, rounding the result to the nearest integer toward -∞ (also known as floored division).

function divisionUp
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer quotient;

Divide dividend by divisor, rounding the result to the nearest integer toward +∞ (also known as ceiled division).

function divisionTowardZero
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer quotient;

Divide dividend by divisor, rounding the result to the nearest integer toward 0 (also known as truncated division).

function divisionAwayZero
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer quotient;

Divide dividend by divisor, rounding the result to the nearest integer away 0.

function divisionHalfDown
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer quotient;

Divide dividend by divisor, rounding the result to the nearest integer; if the fractional part f is 0.5 toward -∞, f < 0.5 toward 0, otherwise away 0.

function divisionHalfUp
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer quotient;

Divide dividend by divisor, rounding the result to the nearest integer; if the fractional part f is 0.5 toward +∞, f < 0.5 toward 0, otherwise away 0.

function divisionHalfTowardZero
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer quotient;

Divide dividend by divisor, rounding the result to the nearest integer; if the fractional part f is ≤ 0.5 toward 0, otherwise away 0.

function divisionHalfAwayZero
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer quotient;

Divide dividend by divisor, rounding the result to the nearest integer; if the fractional part f is ≥ 0.5 away 0, otherwise toward 0.

function divisionHalfToEven
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer quotient;

Divide dividend by divisor, rounding the result to the nearest integer; if the fractional part f is 0.5 the nearest even integer, f < 0.5 toward 0, otherwise away 0.

function divisionHalfToOdd
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer quotient;

Divide dividend by divisor, rounding the result to the nearest integer; if the fractional part f is 0.5 the nearest odd integer, f < 0.5 toward 0, otherwise away 0.

Remainder of rounded Integer division

All built-in functions in this category have two arguments dividend and divisor and:

  • Signal OVERFLOW and return dividend if NAN is not signaled and any of the following cases is given:

    • The result cannot be represented as Integer (including the case that divisor is 0 but not dividend).

    • No result can be provided such that ((divisionα(dividend, divisor) * divisor) + remainderα(dividend, divisor)) == dividend holds, where α is the name suffix of the respective remainder built-in function.

  • Signal NAN and return dividend (i.e., 0) if dividend and divisor are 0 (i.e., division by 0).

function remainderDown
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer remainder;

Remainder of dividend divided by divisor with the quotient rounded to the nearest integer toward -∞.

function remainderUp
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer remainder;

Remainder of dividend divided by divisor with the quotient rounded to the nearest integer toward +∞.

function remainderTowardZero
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer remainder;

Remainder of dividend divided by divisor with the quotient rounded to the nearest integer toward 0.

function remainderAwayZero
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer remainder;

Remainder of dividend divided by divisor with the quotient rounded to the nearest integer away 0.

function remainderHalfDown
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer remainder;

Remainder of dividend divided by divisor with the quotient rounded to the nearest integer; if the fractional part f is 0.5 toward -∞, f < 0.5 toward 0, otherwise away 0.

function remainderHalfUp
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer remainder;

Remainder of dividend divided by divisor with the quotient rounded to the nearest integer; if the fractional part f is 0.5 toward +∞, f < 0.5 toward 0, otherwise away 0.

function remainderHalfTowardZero
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer remainder;

Remainder of dividend divided by divisor with the quotient rounded to the nearest integer; if the fractional part f is ≤ 0.5 toward 0, otherwise away 0.

function remainderHalfAwayZero
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer remainder;

Remainder of dividend divided by divisor with the quotient rounded to the nearest integer; if the fractional part f is ≥ 0.5 away 0, otherwise toward 0.

function remainderHalfToEven
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer remainder;

Remainder of dividend divided by divisor with the quotient rounded to the nearest integer; if the fractional part f is 0.5 the nearest even integer, f < 0.5 toward 0, otherwise away 0.

function remainderHalfToOdd
  signals NAN,
          OVERFLOW;
  input Integer dividend;
  input Integer divisor;
  output Integer remainder;

Remainder of dividend divided by divisor with the quotient rounded to the nearest integer; if the fractional part f is 0.5 the nearest odd integer, f < 0.5 toward 0, otherwise away 0.

Multidimensional Boolean functions

function anyTrue1D
  input Boolean v[:];
  output Boolean b;

true if any element of v is true; otherwise false.

function anyTrue2D
  input Boolean m[:, :];
  output Boolean b;

true if any element of v is true; otherwise false.

function allTrue1D
  input Boolean v[:];
  output Boolean b;

true if all elements of v are true; otherwise false.

function allTrue2D
  input Boolean m[:, :];
  output Boolean b;

true if all elements of v are true; otherwise false.

Relational Integer functions

All built-in functions in this category:

  • Lift to 1-2D.

function imin
  input Integer x1;
  input Integer x2;
  output Integer y;

Minimum of x1 and x2.

function imax
  input Integer x1;
  input Integer x2;
  output Integer y;

Maximum of x1 and x2.

Relational Real functions

All built-in functions in this category:

  • Lift to 1-2D.

function rmin
  input Real x1;
  input Real x2;
  output Real y;

Minimum of x1 and x2.

Returns qNaN if x1 or x2 are qNaN.

function rmax
  input Real x1;
  input Real x2;
  output Real y;

Maximum of x1 and x2.

Returns qNaN if x1 or x2 are qNaN.

Mathematical Real constants and functions

function euler
  output Real y;

Target environment specific, most-precise representation of Euler’s number ℯ (= 2.71828182845904523536…).

function fractionalPart
  input Real x;
  output Real y;

Signed fractional part of x.

Returns 0.0 if x is -∞ or +∞.
Returns qNaN if x is qNaN.

Lifts to 1-2D.

function sign
  input Real x;
  output Real y;

Sign of x (if x is negative: -1.0, positive: 1.0, zero: 0.0).

Returns qNaN if x is qNaN.

Lifts to 1-2D.

function absolute
  input Real x;
  output Real y;

Absolute value of x.

Returns qNaN if x is qNaN.

Lifts to 1-2D.

function sqrt
  input Real x;
  output Real y;

Square root of x. Equivalent to x^5.0e-1.

Returns 0.0 if x == 0.0.
Returns +∞ if x is +∞.
Returns qNaN if x < 0.0 or x is qNaN.

Lifts to 1-2D.

function exp
  input Real x;
  output Real y;

Euler’s number ℯ raised to the power of x (i.e., the natural exponential function). Equivalent to euler()^x.

Returns 1.0 if x == 0.0.
Returns 0.0 if x is -∞.
Returns +∞ if x is +∞.
Returns qNaN if x is qNaN.

Lifts to 1-2D.

function ln
  input Real x;
  output Real y;

Logarithm of x to base ℯ, Euler’s number (i.e., the natural logarithm).

Returns -∞ if x == 0.0.
Returns 0.0 if x == 1.0.
Returns +∞ if x is +∞.
Returns qNaN if x < 0.0 or x is qNaN.

Lifts to 1-2D.

function lg
  input Real x;
  output Real y;

Logarithm of x to base 10 (i.e., the common logarithm).

Returns -∞ if x == 0.0.
Returns 0.0 if x == 1.0.
Returns +∞ if x is +∞.
Returns qNaN if x < 0.0 or x is qNaN.

Lifts to 1-2D.

function divisionSafe
  signals INVALID_ARGUMENT;
  input Real dividend;
  input Real divisor;
  input Real epsilon
    (min = posMinReal());
  output Real quotient;

Divide dividend by divisor, except if divisor < epsilon in which case dividend divided by epsilon is returned.

Signals INVALID_ARGUMENT if divisor < -epsilon.

Returns qNaN if dividend, divisor or epsilon are qNaN.

R-1 (strictly positive divisors in physics): A general approach for a meaningful safe division that avoids 0 / 0 (not a number) or just division by 0 (±∞) is impossible. A common case in the physics-domain are, however, time-varying denominators that are guaranteed to never change sign thanks to strictly positive divisors > 0. Examples are division by density, mass fraction, gear efficiency or slip; in none of these cases the divisor can be negative. It still can be close to 0, and therefore could underflow due to imprecision of floating-point arithmetic operations.

The divisionSafe built-in function should be used in this cases. Its epsilon argument defines an explicit lower-bound for the divisor, whereas the INVALID_ARGUMENT error signal captures misuses where the divisor clearly (i.e., outside the epsilon-band around 0) is negative. Note, that minor negative divisors within epsilon are permitted without causing denominator sign changes.

function sqrtSafe
  input Real x
    (min = 0.0);
  output Real y;

sqrt(x) limited at 0 for x < 0.0.

Returns qNaN if x is qNaN.

Lifts to 1-2D.

function lnSafe
  input Real x
    (min = 0.0);
  output Real y;

ln(x) limited at 0 for x < 0.0.

Returns qNaN if x is qNaN.

Lifts to 1-2D.

function lgSafe
  input Real x
    (min = 0.0);
  output Real y;

lg(x) limited at 0 for x < 0.0.

Returns qNaN if x is qNaN.

Lifts to 1-2D.

Trigonometric Real constants and functions

The arguments and results of all built-in functions in this category are in radians, not degrees.

function pi
  output Real y;

Target environment specific, most-precise representation of π (= 3.14159265358979323846…), the ratio of a circle’s circumference to its diameter.

function sin
  input Real x;
  output Real y;

Sine of x.

Returns qNaN if x is -∞, +∞ or qNaN.

Lifts to 1-2D.

function cos
  input Real x;
  output Real y;

Cosine of x.

Returns qNaN if x is -∞, +∞ or qNaN.

Lifts to 1-2D.

function tan
  input Real x;
  output Real y;

Tangent of x.

Returns qNaN if x is an odd multitude of π/2 or isInfinite(sin(x) / cos(x)).
Returns qNaN if x is -∞, +∞ or qNaN.

Lifts to 1-2D.

L-1 (tangent function poles): The first special case to handle the poles of the tangent function is likely of no relevance for production code since common floating-point representations are incapable to represent π/2, or multitudes thereof, exactly.

function asin
  input Real x;
  output Real y;

Inverse of sin(x) in the range -π/2 ≤ y ≤ π/2.

Returns qNaN if (x < -1.0) or (x > 1.0) or x is qNaN.

Lifts to 1-2D.

function acos
  input Real x;
  output Real y;

Inverse of cos(x) in the range 0 ≤ y ≤ π.

Returns qNaN if (x < -1.0) or (x > 1.0) or x is qNaN.

Lifts to 1-2D.

function atan
  input Real x;
  output Real y;

Inverse of tan(x) in the range -π/2 < y < π/2.

Returns -π/2 if x is -∞.
Returns π/2 if x is +∞.
Returns qNaN if x is qNaN.

Lifts to 1-2D.

L-2 (arcus tangent function poles): It is likely that isNan(tan(atan(minusInfinite()))) and/or isNan(tan(atan(plusInfinite()))) do not hold in production code — although they mathematically should — since common floating-point representations are incapable to represent π/2 exactly.

function atan2
  input  Real y;
  input  Real x;
  output Real z;

Four-quadrant, two-argument inverse tangent in the range -π < z ≤ π, using the signs of y and x to determine the quadrant of the result (angle in the Cartesian plane, between the positive x-axis and the ray from the origin to the point (x, y)).

Returns 0 if (1) y = 0.0 and x > 0, or (2) x is +∞ and isFinite(y) and y ≠ 0.
Returns sign(y) × 1/2 × π if (1) y is ±∞ and isFinite(x), or (2) x = 0 and y ≠ 0.
Returns sign(y) × 3/4 × π if y is ±∞ and x is -∞.
Returns sign(y) × 1/4 × π if y is ±∞ and x is +∞.
Returns sign(y) × π if x is -∞ and isFinite(y) and y ≠ 0.
Returns qNaN if (1) y = 0 and x ≤ 0, or (2) y or x are qNaN.

Lifts to 1-2D.

L-3 (two-argument inverse tangent function poles): GALEC does not support any way to distinguish between -0 and +0; the sign built-in function for example just returns 0.0 in case of ±0 and therefore cannot be used to distinguish -0 from +0, and a means to access the bit-wise representation of a floating-point number for its sign bit — like the C standard library function signbit (ISO/IEC 9899:2024) — is missing. This design is deliberate to enable symbolic optimization that otherwise would be very fragile.

The atan2 operation of [IEEE 754-2019] is also defined for y = ±0 ∧ x ≤ ±0 however, cases where the result z depends on the signs of zero-valued y or x:

  • if x < 0 ∨ x = -0: atan2(-0,x) = -π, atan2(+0,x) = +π

  • if x > 0 ∨ x = +0: atan2(-0,x) = -0, atan2(+0,x) = +0

Thus, the result z jumps from -π to +π if y changes from -0 to +0 for x < 0 ∨ x = -0; or likewise, z jumps from -π to 0 if x changes from -0 to +0 for y = 0. Instead, the GALEC atan2 built-in function returns qNaN if the result depends on the sign of any ±0 arguments (i.e., if y = ±0 ∧ x ≤ ±0), denoting a domain error.

function sinh
  input  Real x;
  output Real y;

Hyperbolic sine of x.

Returns -∞ if x is -∞.
Returns +∞ if x is +∞.
Returns qNaN if x is qNaN.

Lifts to 1-2D.

function cosh
  input  Real x;
  output Real y;

Hyperbolic cosine of x.

Returns +∞ if x is ±∞.
Returns qNaN if x is qNaN.

Lifts to 1-2D.

function tanh
  input  Real x;
  output Real y;

Hyperbolic tangent of x.

Returns -1.0 if x is -∞.
Returns 1.0 if x is +∞.
Returns qNaN if x is qNaN.

Lifts to 1-2D.

function tanSafe
  input Real x;
  output Real y;

tan(x) limited at -π/2 for x ≤ -π/2 and π/2 for x ≥ π/2.

Returns -∞ if x ≤ -π/2.
Returns ∞ if x ≥ π/2.
Returns qNaN if x is qNaN.

Lifts to 1-2D.

L-4 (safe/limited tangent inaccuracy): x is not ranged and therefore not automatically limited for the reasons explained in L-1 and L-2. The function signature

function tanSafe
  input Real x(
      min = pi() / -2.0
    , max = pi() / 2.0);
  output Real y;

would limit out of range values to some Real xs that is the nearest target environment specific floating-point representation of ±π/2, but not exactly ±π/2; isInfinite(tanSafe(xs)) therefore likely would not hold when its implementation is backed by tan(xs) (cf. L-1). For that reason, tanSafe does not just limit x, but guarantees that any x with (x <= (pi() / -2.0)) or (x >= (pi() / 2.0)) yields minusInfinite() or plusInfinite() respectively, whereby the conditional check uses target environment specific values (the result of computing pi() / -2.0 and pi() / 2.0 on the target environment). As a consequence, tanSafe(pi() / -2.0) will always yield -∞ whereas tan(pi() / -2.0) only might — but according to L-1 likely will not — and likewise for tanSafe(pi() / 2.0) vs. tan(pi() / 2.0).

function asinSafe
  input Real x(
      min = -1.0
    , max = 1.0);
  output Real y;

asin(x) limited at -1 for x <= -1.0 and 1 for x >= 1.0.

Returns qNaN if x is qNaN.

Lifts to 1-2D.

function acosSafe
  input Real x(
      min = -1.0
    , max = 1.0);
  output Real y;

acos(x) limited at -1 for x <= -1.0 and 1 for x >= 1.0.

Returns qNaN if x is qNaN.

Lifts to 1-2D.

Systems of equations

function solveUnivariatePolynomial
  input Real a[:];
  input Real x;
  output Real b;

Solution b of the univariate polynomial b = a[n] + a[n-1] × x + a[n-2] × x2 + …​ + a[1] × x(n-1) with n = size(a, 1).

function solveLinearEquations
  signals
    SOLVE_LINEAR_EQUATIONS_FAILED;
  input Real A[:, size(A, 1)];
  input Real b[size(A, 1)];
  output Real x[size(A, 1)];

Solution x for linear equations system A × x = b.

Signals SOLVE_LINEAR_EQUATIONS_FAILED and returns x with all elements qNaN if A is singular, no unique solution exists, or hasNan2D(A) or hasNan1D(b).

Interpolation in 1D/2D/3D

All built-in functions in this category support:

  • Constant bottom and linear interpolation (selected via interpolation argument 1 and 2 respectively).

  • Hold last value and linear through last two boundary points extrapolation (selected via extrapolation argument 1 and 2 respectively).

The abszissa values for which to interpolate are xα with α∈{1,2,3} for the first, second, and third dimension respectively. The vectors of abszissa values — named xα_data with α∈{1,2,3} for the first, second and third dimension — must have at least two elements, which is subject to dimensionality-analysis like statically-evaluated expressions for indexing, and therefore must hold for a GALEC program to be valid. The values of an xα_data are considered for interpolation only up to an explicitly given limiting index nxα; values of higher index are not considered and are subject to extrapolation. The ordinate values are in multidimension y_data.

All interpolation built-in functions:

  • Signal INVALID_ARGUMENT if NO_SOLUTION_FOUND is not signaled and any argument has been limited.

  • Signal NO_SOLUTION_FOUND and return qNaN in any of the following cases:

    • ∃α∈{1,2,3}: isNan(xα).

    • ∃α∈{1,2,3}: not(allFinite1D(xα_data)) or the values of xα_data are not strictly monotonically increasing.

    • Any element e of y_data is not finite, i.e., not(isFinite(e)).

Production code generators can — if mutually agreed with further system integration and matching the application requirements — consider a GALEC program to be invalid if any xα_data, nxα, y_data, interpolation or extrapolation argument of any interpolationαD call is not within one of the following variability classes:

  • Constant: The argument must be literal or a constant variable.

  • Tunable: The argument must be literal or a constant variable or parameter.

If a production code generator restricts the variability of interpolation arguments, it must use a single variability class for the whole GALEC program (i.e., the same variability class must hold for every interpolationαD call). Arguments that are literal or a constant variable must be statically-evaluated like any other staticaly-evaluated expression and their values must not be the cause for any error signal by the respective interpolationαD call. Arguments that are parameters must be respectively ranged, like the function parameter they are an argument for. If the production code does not support recalibration (cf. §2:L-1 of Section 3.4), all parameter arguments are treated like constant variables (i.e., variability class tunable is treated like variability class constant).

function interpolation1D
  signals NO_SOLUTION_FOUND,
          INVALID_ARGUMENT;
  input Real x1;
  input Real x1_data[:];
  input Integer nx1(
      min = 2
    , max = size(x1_data, 1));
  input Real y_data[
      size(x1_data, 1)];
  input Integer interpolation(
      min = 1
    , max = 2);
  input Integer extrapolation(
      min = 1
    , max = 2);
  output Real y;

Interpolation in 1D with extrapolation.

function interpolation2D
  signals NO_SOLUTION_FOUND,
          INVALID_ARGUMENT;
  input Real x1;
  input Real x2;
  input Real x1_data[:];
  input Integer nx1(
      min = 2
    , max = size(x1_data, 1));
  input Real x2_data[:];
  input Integer nx2(
      min = 2
    , max = size(x2_data, 1));
  input Real y_data[
      size(x1_data, 1)
    , size(x2_data, 1)];
  input Integer interpolation(
      min = 1
    , max = 2);
  input Integer extrapolation(
      min = 1
    , max = 2);
  output Real y;

Interpolation in 2D with extrapolation.

function interpolation3D
  signals NO_SOLUTION_FOUND,
          INVALID_ARGUMENT;
  input Real x1;
  input Real x2;
  input Real x3;
  input Real x1_data[:];
  input Integer nx1(
      min = 2
    , max = size(x1_data, 1));
  input Real x2_data[:];
  input Integer nx2(
      min = 2
    , max = size(x2_data, 1));
  input Real x3_data[:];
  input Integer nx3(
      min = 2
    , max = size(x3_data, 1));
  input Real y_data[
      size(x1_data, 1)
    , size(x2_data, 1)
    , size(x3_data, 1)];
  input Integer interpolation(
      min = 1
    , max = 2);
  input Integer extrapolation(
      min = 1
    , max = 2);
  output Real y;

Interpolation in 3D with extrapolation.

R-2 (error handling design of built-in functions): The design of built-in functions heavily leverages on the error handling concepts of Section 3.10 and [IEEE 754-2019]. Any possible error is detected and either signaled or denoted by quiet not a number results (qNaN, cf. [IEEE 754-2019]), such that errors cannot slip through undetected. Built-in functions with Real inputs also always account for ±∞ and qNaN arguments, as denoted in their definition. The returned results are always well-defined, even in case of errors.

For example, solveLinearEquations returns a vector where each element is qNaN, not just some, besides signaling the error. This property is of particular importance for delayed error handling, to ensure deterministic control-flows in case of errors. Since returned results can be used in later control-flow conditions, the control-flow taken could vary if errors would be only denoted by error signals but the results are undefined or only partially well-defined.

qNaN arguments are propagated whenever possible, i.e., if results are Real values; otherwise (i.e., if the range has no qNaN representation, like the integer built-in function which maps a Real to Integer), well-defined values are returned and an error signaled. Likewise, if functions are undefined for some arguments; if they return only Real values, the domain error is denoted by returning qNaN, and otherwise by signaling an error and returning well-defined values. Thus, most Real built-in functions do not signal any errors and instead just rely on qNaN propagation. This helps to reduce error signal pollution and pinpoint the source of error signals to the interesting cases, like a singular system of equations subject to solveLinearEquations.

For many built-in functions ⊕ that are undefined for some non-qNaN arguments (for example ln, sqrt or asin), also a built-in function ⊕Safe approximating ⊕ without being undefined for non-qNaN arguments exists (for example lnSafe, sqrtSafe and asinSafe). Of course, such ⊕Safe functions still propagate qNaN arguments. To use the safe built-in functions is recommended whenever the approximation is good enough for the application domain.

The following examples sketch how seamless built-in functions integrate with the error handling concepts of GALEC, enabling delayed error handling and a high-level of abstraction while still taking care of unexpected corner-cases.

E-1: The following block uses the built-in function solveLinearEquations to compute a block output vector based on a single block input. Whenever solving the linear equations fails, the last valid output is returned besides signaling the error to the runtime environment.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
block SafeSolveLinearEquations
    input Real u;
    output Real y[2];
protected
public
    function InitializeConstants
    protected
    algorithm
    end InitializeConstants;

    function InitializeTunableParameters
    protected
    algorithm
    end InitializeTunableParameters;

    function InitializeDependentParameters
    protected
    algorithm
    end InitializeDependentParameters;

    function InitializeInputs
    protected
    algorithm
        block.u := 0.0;
    end InitializeInputs;

    function InitalizeStatesAndOutputs
    protected
    algorithm
        block.y := {0.0, 0.0};
    end InitalizeStatesAndOutputs;

    function DoStep
        signals SOLVE_LINEAR_EQUATIONS_FAILED;
    protected
        Real yOld[2];
    algorithm
        block.yOld := block.y;
        block.y := solveLinearEquations(
              {
                  {1.0, 2.0 * block.u}
                , {4.0 * block.u, 5.0}
              }
            , {-2.0, 4.0 * block.u});
        /*
            Rudimentary error handling. Hold last valid value and
            inform the runtime environment:
        */
        if signal in SOLVE_LINEAR_EQUATIONS_FAILED then
            block.y = block.yOld;
            signal SOLVE_LINEAR_EQUATIONS_FAILED;
        end if;
    end DoStep;
end SafeSolveLinearEquations;

E-2: The following block interpolates in a vector of data points. The interpolation is tunable, including its table, interpolation method etc.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
block SafeInterpolation
    input Real x;
    output Real y;

    /* Tunable default input used for reinitialization and recalibration: */
    parameter Real xDefault
        (nan => 0.0);
    /* X-axis data points as tunable vector: */
    parameter Real x_data[7];
    /* Y-axis data points as tunable vector: */
    parameter Real y_data[7];
    /* Range of elements used for interpolation as tunable scalar: */
    parameter Integer nx
        (min = 2, max = 7);
    /* Interpolation method as tunable scalar: */
    parameter Integer interpolation
        (min = 1, max = 2);

protected
    /* No extrapolation; just hold last value: */
    constant Integer extrapolation;
    /*
        Default interpolation result in case of interpolation errors
        (configuration errors or qNaN as value to interpolate for):
    */
    parameter Real yDefault;

public
    function InitializeConstants
    protected
    algorithm
        block.extrapolation := 1;
    end InitializeConstants;

    function InitializeTunableParameters
    protected
    algorithm
        block.xDefault := 0.0;
        block.x_data := {1.0, 2.0, 3.0, 4.0 , 4.000001, 4.000002, 4.000003};
        block.y_data := {1.9, 4.33e+1, 9.0, 1.6e+1, 1.61e+1, 1.62e+1, 1.63e+1};
        block.nx := 4;
        block.interpolation := 2;
    end InitializeTunableParameters;

    function InitializeDependentParameters
        /*
            Although recalibration always yields well-defined yDefault,
            inform the runtime environment that the interpolation
            configuration has errors, so it can reconfigure:
        */
        signals NO_SOLUTION_FOUND;
    protected
    algorithm
        block.yDefault := interpolation1D(
              block.xDefault
            , block.x_data
            , block.nx
            , block.y_data
            , block.interpolation
            , block.extrapolation);
        if signal s not in INVALID_ARGUMENT then
            block.yDefault := block.xDefault;
            signal s; /* Propagate NO_SOLUTION_FOUND. */
        else if signal then
            /* Just unset INVALID_ARGUMENT. */
        end if;
    end InitializeDependentParameters;

    function InitializeInputs
    protected
    algorithm
        block.x := block.xDefault;
    end InitializeInputs;

    function InitalizeStatesAndOutputs
    protected
    algorithm
        block.y := block.yDefault;
    end InitalizeStatesAndOutputs;

    function DoStep
    protected
    algorithm
        block.y := interpolation1D(
              block.x
            , block.x_data
            , block.nx
            , block.y_data
            , block.interpolation
            , block.extrapolation);
        /*
            Rudimentary error handling. Fallback on default interpolation
            result yDefault of current interpolation configuration:
        */
        if signal then
            block.y := block.yDefault;
        end if;
    end DoStep;
end SafeInterpolation;

At the beginning the interpolation only uses four data points, but nx can be tuned up to seven. Whenever the interpolation configuration is recalibrated, a new default interpolation with the tunable default input xDefault is conducted, which besides yielding a default interpolation result yDefault for the new configuration also causes a check of the interpolation configuration. If it is invalid, for example if x_data is not strictly monotonically increasing or y_data contains qNaN, yDefault is set to xDefault (which never can be qNaN thanks to its range definition). Whenever interpolation throughout later sampling via DoStep() fails, for example if the input x to interpolate for is qNaN, the interpolation result is yDefault (which never will be qNaN).

Hence, the output y is never qNaN, whatever the interpolation configuration and input x to interpolate for is. Also notice the error signaling, which will propagate any interpolation configuration error signal throughout recalibration via InitializeDependentParameters() to the runtime environment, except for out-of-range interpolation and extrapolation method configurations which are already automatically limited according to the ranges of the respective parameters of the interpolation1D built-in function. It is up to the runtime environment to decide how to handle signaled interpolation configuration errors; whether there is time to reconfigure immediately or it is good enough to leverage on the qNaN-free default interpolation result fallback.

§3: Implementation of built-in functions

Production Code generators must provide implementations for all built-in functions and integrate such into the production code generated for a GALEC program as required (i.e., to the extend required for the program to be deploy- and executable in the target environment). Built-in function implementations must preserve the safety and real-time properties of GALEC; to that end, the execution of a built-in function implementation must never abort program execution, always terminate (i.e., have a finite worst-time execution for a given input), be side effect free (i.e., not change or depend on the control-state of the GALEC program), be recusion-free and have a fixed worst-memory consumption for a given input.

L-1 (target environment specific built-in function implementation and optimization): Production Code generators are encouraged to optimize built-in function calls for the target environment. Optimizations include, for example, the implementation of built-in functions in terms of inlined code, assembly code or even the replacement of built-in function calls and sequences thereof by target environment specific — but semantic-wise equivalent — hardware operations.

The roundHalfToEven built-in function for example is the default rounding mode used in the [IEEE 754-2019] standard for floating-point arithmetic and therefore likely hardware supported. Also integer is often provided as single CPU-instruction like CVTTSS2SI or CVTTSD2SI of Streaming SIMD Extensions 2 (SSE2); and roundDown, roundUp, roundTowardZero and roundHalfToEven are provided by ROUNDSS and ROUNDSD of SSE4. Particularly the multidimensional versions of lifted built-in functions likely can be much more efficiently implemented than a naïve iterative solution as shown in Part 4 of Appendix A; SSE4 for example provides for most single data instructions corresponding multiple data instructions (SIMD hardware operations: single instruction, multiple data).

A complete, although likely inefficient, reference implementation of all built-in functions, with only target environment specific characteristics expressed using pseudo-code, is provided in Appendix A. It is given in GALEC and can serve as a basis for a Production Code generator to generate its own implementation, assuming it allows to temporarily disable the check that no user-defined functions are named like built-in functions.

4. Algorithm Code Model Representation

InputOutputBlock

The Algorithm Code model is a portable and tool-independent intermediate representation for coupling physics-modeling tools with embedded Production Code generation. Mathematically, it is described as a sampled input/output block with one (potentially varying) sample period Ti for the whole block where inputs ui and previous (block internal) states xi are provided at sample time ti and outputs yi and new states xi+1 are computed and are latest used at sample time ti+1 = ti + Ti (see figure to the right). All variables of the block have a defined type and all statements of the block are sorted and explicitely solved for a particular variable. Functions are provided to execute the relevant parts of the block, especially to initialize it and to perform one step.

The purpose of the Algorithm Code model representation is to provide a well defined reusable basis for the Production Code generating tools. It can be seen as a target environment independent Production Code on a logical level where the relationship to the original model is clearly visible (for example, the hierarchy of the original model is visible in the variable names). Depending on the embedded device the eFMU should be run on, a single Algorithm Code model representation can be used to generate multiple Production Code model representations and is therefore the last target environment independent model representation of the eFMU.

The Algorithm Code model representation consists

  • of a manifest file in XML format in which all interface variables are defined (see Section 4.1),

  • one code file with extension .alg that represents the executable part of the block consisting of a GALEC block.

In the Algorithm Code specification and its examples the following coding conventions are used:

  • Types — primitives and components — start with capital letters, and each successive word part starts capitalized. Examples: Real, Boolean, Pid, GearBox, CrankShaftPid.

  • Stateless functions — including built-in functions — are defined with keyword function. The function names start with lower-case letters, and each successive word part starts capitalized. Examples: sin, solveLinearEquations, computeCrankShaftPid.

  • Functions for scalars that are generalized to one and two dimensions use the scalar function name with suffix 1D and 2D appended. Examples: roundTowardZero1D, interpolate2D.

4.1. Algorithm Code manifest

InputOutputBlock

The manifest file of the Algorithm Code model representation is an instance of an XML schema definition and defines the variables and functions that represent a sampled input/output block, see figure to the right.


4.1.1. Definition of an eFMU Algorithm Code (efmiAlgorithmCodeManifest.xsd)

This is the root-level schema file of the Algorithm Code model representation and contains the following definition:

ManifestMainLevel

On the top level, the schema consists of the following elements (see figure above):

Element-Name Description

attributes

The attributes of the top-level element are the same for all manifest kinds and are defined in section Section 2.3.1.
Current kind-specific values: kind = "AlgorithmCode", xsdVersion (value is the current xsd version of the schema for the Algorithm Code model manifest).

Files

List of files referenced in this model representation. There must be at least one file that contains the code of the Functions. This element is the same for all manifest kinds and is defined in section Section 2.3.3.

Clock

A reference to the sample period defined by a block variable. For details see Section 4.1.2.

Functions

Properties of block-interface functions. For details see Section 4.1.3.

ErrorSignalStatus

Unique anchor that is used by derived model representations — like production code referring to this manifest — to mark error signal variables. For details see Section 4.1.4.

Units

An optional global list of unit definitions. These definitions are used by the elements of Variables. For details see Section 4.1.5.

Variables

List of block-interface variables. A variable might be a scalar or an array of an elementary type. For details see Section 4.1.6.

Annotations

Additional data that a vendor might want to store and that other vendors might ignore. For details see Section 2.3.4.5.

4.1.2. Definition of Clock

Element Clock provides a reference to the block variable defining the sample period for which the block was designed; only fixed sample periods are permitted, i.e., the referenced variable must be a constant. According to the GALEC block life-cycle (cf. Section 3.4, §3), system integration must execute the block periodically with the defined fixed sample period.

Clock
Element-Name Description

id

The id of the sample period of the block.

variableRefId

Reference to the variable in <Variables> that defines the sample period. This variable must have value constant for its blockCausality attribute. If the variabe has a unit, it must be seconds; otherwise the implicit unit is seconds. The restrictions — constant in seconds — are required to guarantee a well-defined, unique interpretation of Behavioral Model representations for testing (cf. §1.3 and §4 of Section 5.2).

When the production code of this block is integrated in the target environment (for example as AUTOSAR Adaptive Platform component), then it is expected that the block is executed as periodic sampled data system with the sample period defined by the variable variableRefId refers to. It might be that also a slightly changed sample period in the target environment may still result in reasonable performance; in that case, system integration must adapt the sample period respectively in generated production code and take special care to adjust the sampling points of test tooling using Behavioral Model containers referring to this Algorithm Code manifest (cf. §1.3 and §4 of Section 5.2).

4.1.3. Definition of Functions

Element Functions defines properties of the block-interface functions. Each block-interface function must be represented by exactly one Function element.

BlockMethods
BlockMethodSignals
Name Description

name

Name of block-interface function.

Signals

The error signals exposed by the respective block-interface function. The value attribute of each <Signal> defines one possible pre-defined error signal that can be signaled. Cf. Section 3.10, §1.1 and §1.6, for permitted values and their semantic.

4.1.4. Definition of ErrorSignalStatus

This element defines a unique anchor that is used by derived model representations — like production code referring to this manifest — to mark error signal variables. Such hold the error signal status of a block-interface function after its execution and therefore can be used to check if the function’s execution succeeded or encountered any errors (cf. Section 3.10, §1.6 and Section 3.4, §3 regarding GALEC error signals and block-interface functions).

ErrorSignalStatus

The <ErrorSignalStatus> consists only of attribute id that defines the unqiue ID of the anchor.

E-1: Behavioral Model representations for example have to use the <ErrorSignalStatus> to conclude how to access the error signal status of the implementation of a block-interface function of tested production code. This is required, because testing error signals is mandatory for Behavioral Models (cf. §2.3 and §4 of Section 5.2).

4.1.5. Definition of Units

Element Units defines the units that are used by the elements of Variables.

This element is identical to element UnitDefinitions of FMI 3.0 with the only exception that there is an additional attribute id to identify a unit uniquely in the Algorithm Code manifest and that there is no support for display units (element DisplayUnit):

Units
BaseUnit

4.1.6. Definition of Variables

The Variables element consists of an ordered list of all block-interface variables.

Variables are defined as (hereby one variable is defined according to schema group efmiVariable in file efmiVariable.xsd):

Variables

The schema definition contains basically the same information as element ModelVariables in FMI 3.0, but using mathematical instead of target environment types and having the following deviations:

  • There is no String type.

  • A type might have Dimensions where the size of a dimension is an Integer literal (a dimension cannot depend on a structural parameter as in FMI 3.0).

  • The variable attributes causality, variability and initial of FMI 3.0 are replaced with the new attribute blockCausality (see below).

  • The following FMI 3.0 attributes are not present:

    • valueReference

    • canHandleMultipleSetPerTimeInstant

    • clockReference

    • clockElementIndex

    • intermediateUpdate

    • declaredType

    • quantity

    • displayUnit

    • unbounded

    • derivative

    • reinit

Variable Base (attributes + elements)

All variable kinds (so RealVariable, IntegerVariable, BooleanVariable) have the following base attributes/elements:

VariableBase
Name Description

id

The unique identification of the variable with respect to the AlgorithmCode manifest file (can be referenced from other manifest files).

name

The full, unique name of the variable. Every variable is uniquely identified within an eFMI AlgorithmCode instance by this name.

description

An optional description string describing the meaning of the variable.

blockCausality

Enumeration that defines the causality, variability and initialization of the variable. Allowed values of this enumeration:

  • "input": The variable value is set by the environment at the start of a sampling period.

  • "output": The variable value can be used by the environment once it is computed.

  • "tunableParameter": Independent parameter that is constant during a call to DoStep() and can be calibrated.

  • "calculatedParameter": A data value that is constant during a call to DoStep() and is computed during initialization or when tunable parameters change.

  • "constant": The value of the variable defined with the start attribute never changes.

start

Initial value of the variable as defined by default initialization.

The given xs:token value can encode either a scalar value or a multidimensional value where each element value is separated by an XML whitespace character. In the latter case, the array elements are given in row-major order, that is the elements of the last index are given in sequence.

R-1 (default initialization and Algorithm Code manifest start values): The start values of the variables in the manifest of an Algorithm Code container are conceptually determined by default initialization (cf. §4 of Section 3.4) within an arbitrary target environment (and therefore for example undefined floating-point precision for Real variables).

[For example, a table T[4,3,2] (first dimension 4 entries, second dimension 3 entries, third dimension 2 entries) is mapped into the following sequence of values:
T[1,1,1],
T[1,1,2],
T[1,2,1],
T[1,2,2],
T[1,3,1],
T[1,3,2],
T[2,1,1],
T[2,1,2],
T[2,3,1],
…​
]

If the variable is a scalar, the string must encode a scalar value. If the variable is a multidimensional array, the string can either: (1) encode a scalar value, meaning that each element of the multidimensional array has the respective scalar value as start value or (2) encode a multidimensional value, meaning that the start values of the elements of the multidimensional array are the respective encoded multidimensional value.

Encoded values must be of the variable’s type and each must satisfy its min and max value (if min and/or max elements are defined).

Dimensions

If the variable is an array, then the fixed dimensions of the array are defined by this element. For every dimension, the number defines the number of the dimension (must be consecutive numbers 1, 2, …​) and size defines the fixed size of the dimension (must be >= 1).

Annotations

Additional data of the variable, e.g., for the dialog menu or the graphical layout. For details see Section 2.3.4.5.

In FMI 3.0 the attributes causality, variability, initial are defined, which combinations are allowed and why the allowed combinations are needed for an offline simulation program with events. However, for eFMI most of the combinations cannot occur. For simplicity, eFMI uses therefore only the attribute blockCausality. In the following table the mapping of blockCausality to the FMI 3.0 attributes is defined:

eFMI FMI 3.0

blockCausality

causality

variability

initial

input

input

discrete

--- (no initial)

output

output

discrete

exact

tunableParameter

parameter

tunable

exact

dependentParameter

calculatedParameter

tunable

calculated

constant

local

constant

exact

state

local

discrete

exact

RealVariable-specific attributes

The following RealVariable specific attributes are defined:

RealVariableAttributes
Attribute-Name Description

unitRefId

Identifier of the unit of the variable defined in list Units.Unit (Section 4.1.5). The value of the variable is with respect to this unit.

relativeQuantity

Defines if BaseUnit-based unit conversions have to consider the base-unit’s offset (relativeQuantity=false) or not (relativeQuantity=true). [For example, 10 degree Celsius = 10 Kelvin if relativeQuantity = "true" and not 283.15 Kelvin.]

min

Minimum value of variable (variable value ≥ min). If not defined, the minimum is the largest negative number that can be represented in the target environment. If the variable is a multidimensional array, min is a scalar value that holds for all array elements.

max

Maximum value of variable (variable value ≤ max). If not defined, the maximum is the largest positive number that can be represented in the target environment. If the variable is a multidimensional array, max is a scalar value that holds for all array elements.

nominal

Nominal value of variable. If the variable is a multidimensional array, nominal is a scalar value that holds for all array elements.

If not defined and no other information about the nominal value is available, then nominal = 1 is assumed.
[The nominal value of a variable can be, for example, used to define tolerances or scaling values for numerical algorithms in which the variable is used.]

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<Units>
  <Unit id="UnitID_1" name="s"/>
</Units>

<Variables>
  <RealVariable id="ID_1" name="Ti" unitRefId="UnitID_1" blockCausality="tunableParameter" start="0.1"/>
  <RealVariable id="ID_A" name="A" blockCausality="constant" start="1.1 1.2 2.1 2.2">
      <Dimensions>
           <Dimension number="1" size="4"/>
      </Dimensions>
  </RealVariable>
  <RealVariable id="ID_2" name="previous(I.x)"  blockCausality="state" start="0.0" min="0.0" />
</Variables>
IntegerVariable-specific attributes

The following IntegerVariable specific attributes are defined:

IntegerVariableAttributes
Attribute-Name Description

min

Minimum value of variable (variable value ≥ min). If not defined, the minimum is the largest negative number that can be represented in the target environment. If the variable is a multidimensional array, min is a scalar value that holds for all array elements.

max

Maximum value of variable (variable value ≤ max). If not defined, the maximum is the largest positive number that can be represented in the target environment. If the variable is a multidimensional array, max is a scalar value that holds for all array elements.

Examples:

1
2
3
4
5
6
7
8
<Variables>
  <IntegerVariable id="ID_11" name="numberOfCylinders" blockCausality="tunableParameter" start="6" min="0" />
  <IntegerVariable id="ID_12" name="pivots" start="0">
     <Dimensions>
        <Dimension number="1" size="8"/>
     </Dimensions>
  </IntegerVariable>
</Variables>
BooleanVariable-specific attributes

The BooleanVariable element has no additional attributes.

4.2. Example Application Scenarios

4.2.1. Modelica-modeled PID-controller

The following example has its origin in a Modelica model for a speed controller — a PID controller with output limitations — of a DC motor. The block diagram of the Modelica model has two input signals wLoadRef and wMotor. The input signal wLoadRef is the desired value of the speed of the motor load whereas wMotor is the current speed of the motor. The output of the controller is vMotor — the voltage to be applied to the DC motor.

PIDControllerModelica

It follows one possible transformation of this Modelica model into an eFMI GALEC program. The discretization of the dynamic parts of the PID controller is realized by the Explicit Euler method. The respective eFMI GALEC program is:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
block PID_Controller
    input Real wLoadRef(
        min = -1.0e+5, max = 1.0e+5);
    input Real wMotor(
        min = -1.0e+5, max = 1.0e+5);
	
    output Real vMotor(
        min = -1.0e+7, max = 1.0e+7);

    parameter Real 'limiter.uMax'(
        min = 1.0, max = 1.0e+5);
    parameter Real gearRatio(
        min = 1.0e+1, max = 5.0e+2);
    parameter Real Ti(
        min = 1.0e-7, max = 1.0e+2);
    parameter Real Td(
        min = 1.0e-7, max = 1.0e+2);
    parameter Real kd(
        min = 0.0, max = 1.0e+3);
    parameter Real k(
        min = 0.0, max = 1.0e+3);

protected
    constant Real stepSize;
    
    parameter Real 'limiter.uMin'(
        min = -1.0e+5, max = -1.0);

    Real 'PID.I.x';
    Real 'PID.D.x';
    Real 'previous(feedback.y)';
    Boolean firstTick;

public
    function InitializeConstants
    protected
    algorithm
        block.stepSize := 1.0e-3;
    end InitializeConstants;
    
    function InitializeTunableParameters
    protected
    algorithm
        block.'limiter.uMax' := 4.0e+2;
        block.gearRatio := 1.05e+2;
        block.Ti := 1.0e-1;
        block.Td := 1.0e-1;
        block.kd := 1.0e-1;
        block.k := 1.0e+1;
    end InitializeTunableParameters;
    
    function InitializeDependentParameters
	protected
    algorithm
        block.'limiter.uMin' := -block.'limiter.uMax';
    end InitializeDependentParameters;

    function InitializeInputs
    protected
    algorithm
        block.wLoadRef := 0.0;
        block.wMotor := 0.0;
    end InitializeInputs;

    function InitializeStatesAndOutputs
	protected
    algorithm
        block.'PID.I.x' := 0.0;
        block.'PID.D.x' := 0.0;
        block.'previous(feedback.y)' := 0.0;
        block.firstTick := true;
        
        block.vMotor := 0.0;
    end InitializeStatesAndOutputs;

    function DoStep
    protected
        Real 'gain.y';
        Real 'feedback.y';
        Real 'derivative(PID.I.x)';
        Real 'derivative(PID.D.x)';
        Real 'PID.D.y';
        Real 'PID.y';
    algorithm
        if block.firstTick then
            block.firstTick := false;
        else
            'derivative(PID.I.x)' :=
                block.'previous(feedback.y)' / block.Ti;
            'derivative(PID.D.x)' :=
                (block.'previous(feedback.y)' - block.'PID.D.x') / block.Td;

            block.'PID.I.x' := block.'PID.I.x' + (block.stepSize * 'derivative(PID.I.x)');
            block.'PID.D.x' := block.'PID.D.x' + (block.stepSize * 'derivative(PID.D.x)');
        end if;

        'gain.y' := block.gearRatio * block.wLoadRef;
        'feedback.y' := 'gain.y' - block.wMotor;

        'PID.D.y' := block.kd * ('feedback.y' - block.'PID.D.x') / block.Td;
        'PID.y' := block.k * ('PID.D.y' + block.'PID.I.x' + 'feedback.y');

        block.vMotor := (
            if 'PID.y' > block.'limiter.uMax' then
                block.'limiter.uMax'
            elseif 'PID.y' < block.'limiter.uMin' then
                block.'limiter.uMin'
            else
                'PID.y'
        );
        if signal in NAN then
            InitializeStatesAndOutputs();
        else
            block.'previous(feedback.y)' := 'feedback.y';
        end if;
    end DoStep;
end PID_Controller;

The manifest for the controller, just describing its interface, is:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<?xml version="1.0" encoding="UTF-8"?>
<Manifest
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="../schemas/AlgorithmCode/efmiAlgorithmCodeManifest.xsd"
    xsdVersion="0.14.0"
    kind="AlgorithmCode"
    efmiVersion="1.0.0"   
    id="{1e111db5-90e6-4e17-b2e5-4e215dbbdd49}" 
    name="PID controller discretized by Explicit Euler method"  
    version="0.1"
    generationDateAndTime="2020-11-10T12:33:22Z"
    generationTool="Manual"
    license="MIT">

    <Files>
        <File
            name="Controller.alg"
            id="FileID_1"
            path="./"
            needsChecksum="false"
            role="Code"/>
    </Files>

    <Clock id="ID_Clock" variableRefId="ID_7"/>
    
    <Functions fileRefId="FileID_1">
        <Function id="ID_Startup" kind="Startup"/>
        <Function id="ID_Recalibrate" kind="Recalibrate"/>
        <Function id="ID_DoStep" kind="DoStep"/>
    </Functions>
    
    <ErrorSignalStatus id="ID_ErrorSignalStatus"/>
    
    <Variables> 
        <RealVariable
            name="'limiter.uMin'"
            id="ID_1"
            blockCausality="dependentParameter"
            start="-4.0e+2"
            min="-1.0e+5"
            max="-1.0"/>
        <RealVariable
            name="'limiter.uMax'"
            id="ID_2"
            blockCausality="tunableParameter"
            start="4.0e+2"
            min="1.0"
            max="1.0e+5"/>
        <RealVariable
            name="Ti"
            id="ID_3"
            blockCausality="tunableParameter"
            start="1.0e-1"
            min="1.0e-7"
            max="1.0e+2"/>
        <RealVariable
            name="Td"
            id="ID_4"
            blockCausality="tunableParameter"
            start="1.0e-1"
            min="1.0e-7"
            max="1.0e+2"/>
        <RealVariable
            name="kd"
            id="ID_5"
            blockCausality="tunableParameter"
            start="1.0e-1"
            min="0.0"
            max="1.0e+3"/>
        <RealVariable
            name="k"
            id="ID_6"
            blockCausality="tunableParameter"
            start="1.0e+1"
            min="0.0"
            max="1.0e+3"/>
        <RealVariable
            name="stepSize"
            id="ID_7"
            blockCausality="tunableParameter"
            start="1.0e-3"
            min="1.0e-10"
            max="1.0e-2"/>
        <RealVariable
            name="gearRatio"
            id="ID_8"
            blockCausality="tunableParameter"
            start="1.05e+2"
            min="1.0e+1"
            max="5.0e+2"/>
        <RealVariable
            name="wLoadRef"
            id="ID_9"
            blockCausality="input"
            start="0.0"
            min="-1.0e+5"
            max="1.0e+5">
        </RealVariable>
        <RealVariable
            name="wMotor"
            id="ID_10"
            blockCausality="input"
            start="0.0"
            min="-1.0e+5"
            max="1.0e+5">
        </RealVariable>
        <RealVariable
            name="vMotor"
            id="ID_11"
            blockCausality="output"
            start="0.0"
            min="-1.0e+7"
            max="1.0e+7">
        </RealVariable>
    </Variables>
</Manifest>

4.2.2. Mathematical Example using built-in Functions

The following example implements a linearly implicit second order differential equation system of the form M(x)*x'' = F(x,u), y = g(x) with an invertible matrix M(x) for a state vector x, inputs u and outputs y. The vector functions F and g describe the right hand sides of the dynamical system and the output equation respectively.

The following implementation in eFMI GALEC code is based on a discretization by the Explicit Euler method. Further, there are several expressions in M and F that use built-in functions like sin, cos and exp. Additionally, the built-in function solveLinearEquations is used to solve the linear system of equations. The respective eFMI GALEC program is:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
block LinearEquationSystem
    input Real u[ 4 ](
        min = -1.0e+7, max = 1.0e+7);
	
    output Real y[ 4 ];

protected
    constant Real stepSize;

    Real x[ 4 ];
    Real v[ 4 ];
    Real 'derivative(x)'[ 4 ];
    Real 'derivative(v)'[ 4 ];
    
public
    function InitializeConstants
    protected
    algorithm
        block.stepSize := 1.0e-2;
    end InitializeConstants;
    
    function InitializeTunableParameters
    protected
    algorithm
    end InitializeTunableParameters;
    
    function InitializeDependentParameters
	protected
    algorithm
    end InitializeDependentParameters;

    function InitializeInputs
    protected
    algorithm
        block.u := { 0.0, 0.0, 0.0, 0.0 };
    end InitializeInputs;

    function InitializeStatesAndOutputs
	protected
    algorithm
        block.x := { -3.0, 7.0, 1.9e+1, 1.0 };
        block.v := { 0.0, 0.0, 0.0, 0.0 };

        block.'derivative(x)' := { 0.0, 0.0, 0.0, 0.0 };
        block.'derivative(v)' := { 0.0, 0.0, 0.0, 0.0 };

        block.y := { 0.0, 0.0, 0.0, 0.0 };
    end InitializeStatesAndOutputs;

    function DoStep   
    protected
        Real M[ 4, 4 ];
        Real F[ 4 ];  
    algorithm
        block.x := block.x + (block.stepSize *. block.'derivative(x)');
        block.v := block.v + (block.stepSize *. block.'derivative(v)');

        block.y := {
            sin(block.x[ 1 ]) + block.x[ 3 ],
            -block.x[ 2 ],
            pi() * 2.0 * cos(block.x[ 4 ] - block.x[ 2 ]),
            block.x[ 3 ] + (block.x[ 1 ] / block.x[ 4 ])
        };

        M := {
            {
                -sin(block.x[ 3 ] + block.x[ 4 ]),
                (block.x[ 4 ]^2) - (block.x[ 2 ]^3),
                -4.0 * exp(block.x[ 3 ] * block.x[ 1 ]),
                cos(-block.x[ 2 ]) * block.x[ 3 ]
            },
            {
                (block.x[ 2 ] + (2.0 * block.x[ 4 ])) / block.x[ 1 ],
                -block.x[ 1 ],
                block.x[ 1 ] * block.x[ 2 ],
                sin(block.x[ 1 ] * block.x[ 2 ] * block.x[ 3 ])
            },
            {
                -block.x[ 4 ] + (block.x[ 2 ] * block.x[ 1 ]),
                6.0 * pi() * cos(block.x[ 2 ]),
                -block.x[ 2 ],
                2.0 * (block.x[ 1 ] + sin(block.x[ 3 ] * pi()))
            },
            {
                block.x[ 1 ] + cos(block.x[ 3 ]),    
                -2.0 * block.x[ 3 ] * block.x[ 4 ],
                -4.0 * block.x[ 3 ] * cos(block.x[ 2 ]),
                block.x[ 4 ] - (block.x[ 1 ] * block.x[ 2 ])
            }
        };
        F := {
            block.u[ 1 ] - (block.x[ 3 ]^2),
            -block.u[ 4 ] + (block.x[ 2 ] * cos(block.x[ 1 ])),
            -block.u[ 4 ] + (block.u[ 2 ] * block.x[ 4 ]),
            block.u[ 2 ] + block.u[ 3 ]
        };

        block.'derivative(v)' := solveLinearEquations(M, F);
        block.'derivative(x)' := block.v;
        
        if signal in SOLVE_LINEAR_EQUATIONS_FAILED or hasNan1D(block.y) then
            InitializeStatesAndOutputs();
        end if;
    end DoStep;
end LinearEquationSystem;

The manifest summarising the controller’s interface is:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?xml version="1.0" encoding="UTF-8"?>
<Manifest
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="../schemas/AlgorithmCode/efmiAlgorithmCodeManifest.xsd"
    efmiVersion="1.0.0"
    xsdVersion="0.14.0"
    id="{351131cd-1e50-46d0-913a-240451d247c7}"
    kind="AlgorithmCode"
    name="Dynamic system discretized by Explicit Euler method"
    generationDateAndTime="2020-10-15T16:49:20Z"
    version="0.4.0"
    generationTool="Manual"
    license="MIT">

    <Files>
        <File
            name="Controller.alg"
            id="FileID_1"
            path="./"
            needsChecksum="false"
            role="Code"/>
    </Files>

    <Clock id="ID_Clock" variableRefId="ID_2"/>

    <Functions fileRefId="FileID_1">
        <Function id="ID_Startup" kind="Startup"/>
        <Function id="ID_Recalibrate" kind="Recalibrate"/>
        <Function id="ID_DoStep" kind="DoStep"/>
    </Functions>

    <ErrorSignalStatus id="ID_ErrorSignal"/>

    <Variables>
        <RealVariable
            name="stepSize"
            id="ID_2"
            blockCausality="constant"
            start="1e-2"/>
        <RealVariable 
            name="u"
            id="ID_3"
            blockCausality="input"
            start="0.0 0.0 0.0 0.0"
            min="-1.0e+7"
            max="1.0e+7">
            <Dimensions>
                <Dimension number="1" size="4"/>
            </Dimensions>
        </RealVariable>
        <RealVariable
            name="y"
            id="ID_4"
            blockCausality="output"
            start="0.0 0.0 0.0 0.0">
            <Dimensions>
                <Dimension number="1" size="4"/>
            </Dimensions>
        </RealVariable>
    </Variables>
</Manifest>

4.2.3. Vehicle model with implicit integration method

The following example presents a discretized vehicle model. The model equations and parameters are according to Section 6.8 Rollover Avoidance of the book J. Ackermann et al.: Robust Control, Springer 2002 with some further assumptions. The vehicle model is a single track model with roll augmentation. The discretization is realized by a linear implicit Runge-Kutta method of order 1 (Rosenbrock method, linear implicit Euler method) suited for stiff systems. For such methods the input signals have to be differentiated, therefore the derivatives of the original input variables are added as inputs of the discretized model.

The example demonstrates the use of for-loops, vectors and matrices as well as several built-in functions, particularly for solving linear equation systems. The eFMI GALEC program is:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
block VehicleModel
    input Real u[ 2 ](
        min = -1.0e+7, max = 1.0e+7);
    input Real 'derivative(u)'[ 2 ](
        min = -1.0e+7, max = 1.0e+7);
	
    output Real x[ 8 ];

    parameter Real FdF;
    parameter Real m;
    parameter Real m2;
    parameter Real h;
    parameter Real lF;
    parameter Real lR;
    parameter Real g;
    parameter Real Jx2;
    parameter Real mu;
    parameter Real cF;
    parameter Real cR;
    parameter Real Jz1;
    parameter Real Jz2;
    parameter Real Jy2;
    parameter Real cphi;
    parameter Real dphidot;
    parameter Real b1;
    parameter Real b2;

protected
    constant Real stepSize;

    parameter Real FlV;
    parameter Real FzR;
    parameter Real FzF;

    Real q[ 4 ];
    Real dx[ 8 ];

public
    function InitializeConstants
    protected
    algorithm
        block.stepSize := 1.0e-2;
    end InitializeConstants;
    
    function InitializeTunableParameters
    protected
    algorithm
        block.FdF := 1.5e+1;
        block.m := 1.43e+4;
        block.m2 := 1.2487e+4;
        block.h := 1.15;
        block.lF := 1.95;
        block.lR := 1.54;
        block.g := 9.81;
        block.Jx2 := 2.4201e+4;
        block.mu := 1.0;
        block.cF := 5.82e+5;
        block.cR := 7.83e+5;
        block.Jz1 := 3.654e+3;
        block.Jz2 := 3.4917e+4;
        block.Jy2 := 3.4917e+3;
        block.cphi := 4.57e+5;
        block.dphidot := 1.00e+5;
        block.b1 := 2.0e-1;
        block.b2 := 1.0e-1;
    end InitializeTunableParameters;
    
    function InitializeDependentParameters
	protected
    algorithm
        block.FlV := block.FdF;
        block.FzR := block.m * block.g * block.lF / (block.lR + block.lF);
        block.FzF := (block.m * block.g) - block.FzR;
    end InitializeDependentParameters;

    function InitializeInputs
    protected
    algorithm
        block.u = { 0.0, 0.0 };
        block.'derivative(u)' = { 0.0, 0.0 };
    end InitializeInputs;

    function InitializeStatesAndOutputs
	protected
    algorithm
        block.q := { 0.0, 0.0, 0.0, 0.0 };
        block.dx := { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
        block.x := { 0.0, 0.0, 0.0, 0.0, 1.0e+1, 0.0, 0.0, 0.0 };
    end InitializeStatesAndOutputs;

    function DoStep
    protected
        Real sx;
        Real sy;
        Real psi;
        Real phi;
        Real vx;
        Real vy;
        Real r;
        Real phidot;
        Real delta;
        Real FyD;
        Real q1;
        Real q2;
        Real q3;
        Real q4;
        Real deltadot;
        Real FyDdot;

        Real FdF;
        Real FlV;
        Real m;
        Real m2;
        Real h;
        Real lF;
        Real lR;
        Real g;
        Real Jx2;
        Real mu;
        Real cF;
        Real cR;
        Real Jz1;
        Real Jz2;
        Real Jy2;
        Real FzR;
        Real FzF;
        Real cphi;
        Real dphidot;
        Real b1;
        Real b2;

        Real G[ 4, 4 ];

        Real rs2[ 4 ];
        Real dx1[ 4 ];

        Real help1;
        Real help2;
        Real help3;
    algorithm
        for i in 1 : 8 loop
            block.x[ i ] := block.x[ i ] + block.dx[ i ];
        end for;

        for i in 1 : 4 loop
            block.q[ i ] := block.dx[ 4 + i ] / block.stepSize;
        end for;

        sx := block.x[ 1 ];
        sy := block.x[ 2 ];
        psi := block.x[ 3 ];
        phi := block.x[ 4 ];
        vx := block.x[ 5 ];
        vy := block.x[ 6 ];
        r := block.x[ 7 ];
        phidot := block.x[ 8 ];

        delta := block.u[ 1 ];
        FyD := block.u[ 2 ];

        q1 := block.q[ 1 ];
        q2 := block.q[ 2 ];
        q3 := block.q[ 3 ];
        q4 := block.q[ 4 ];

        deltadot := block.'derivative(u)'[ 1 ];
        FyDdot := block.'derivative(u)'[ 2 ];

        FdF := block.FdF;
        FlV := block.FlV;

        m := block.m;
        m2 := block.m2;
        h := block.h;
        lF := block.lF;
        lR := block.lR;
        g := block.g;
        Jx2 := block.Jx2;

        mu := block.mu;
        cF := block.cF;
        cR := block.cR;

        Jz1 := block.Jz1;
        Jz2 := block.Jz2;
        Jy2 := block.Jy2;
        FzR := block.FzR;
        FzF := block.FzF;
        cphi := block.cphi;
        dphidot := block.dphidot;

        b1 := block.b1;
        b2 := block.b2;

        help1 := sqrt((vx^2) + (vy^2));
        help2 := ((vx^2) + (vy^2))^1.5;
        help3 := ((h^2) * m2) + Jy2 - Jz2;

        G[ 1, 1 ] :=
            (
                  (mu * ((lF * r * vx) + (help1 * vy)) * block.stepSize * cF * sin(delta))
                + (help2 * m)
            )
            / (help2 * block.stepSize);
        G[ 1, 2 ] :=
            -1.0 * (
                  (mu * ((-lF * r * vy) + (help1 * vx)) * cF * sin(delta))
                + (help2 * r * m)
            )
            / help2;
        G[ 1, 3 ] :=
            (
                  (2.0 * h * m2 * phidot * cos(phi) * block.stepSize * help1)
                - (mu * cF * lF * sin(delta) * block.stepSize)
                + (h * m2 * sin(phi) * help1)
                - (m * vy * block.stepSize * help1)
            )
            / (block.stepSize * help1);
        G[ 1, 4 ] :=
            h * m2 * (
                  (-2.0 * sin(phi) * phidot * r * block.stepSize)
                + (cos(phi) * q3 * block.stepSize)
                + (2.0 * r * cos(phi))
            );
        G[ 2, 1 ] :=
            (
                  ((
                        (-cos(delta) * cF * mu * vy)
                      - (cR * mu * vy)
                      + (m * r * ((vx^2) + (vy^2)))
                  ) * help1)
                - (r * mu * vx * ((cos(delta) * cF * lF) - (cR * lR)))
            )
            / help2;
        G[ 2, 2 ] :=
            (
                  ((
                        (cos(delta) * cF * mu * vx * block.stepSize)
                      + (cR * mu * vx * block.stepSize)
                      + (m * ((vx^2) + (vy^2)))
                  ) * help1)
                - (block.stepSize * r * mu * vy * ((cos(delta) * cF * lF) - (cR * lR)))
            )
            / (help2 * block.stepSize);
        G[ 2, 3 ] :=
            (
                  (2.0 * h * m2 * r * sin(phi) * help1)
                + (mu * cF * lF * cos(delta))
                + (m * vx * help1)
                - (mu * cR * lR)
            )
            / help1;
        G[ 2, 4 ] :=
            m2 * (
                  ((-1.0 + (((phidot^2) + (r^2)) * (block.stepSize^2))) * cos(phi))
                + (block.stepSize * sin(phi) * ((q4 * block.stepSize) + (2.0 * phidot)))
            )
            * (h / block.stepSize);
        G[ 3, 1 ] :=
            (
                  ((
                      (-cos(delta) * cF * lF * mu * vy * block.stepSize)
                    + (h * m2 * ((vx^2) + (vy^2)) * sin(phi))
                    + (cR * lR * mu * vy * block.stepSize)
                  ) * help1)
                - (block.stepSize * r * mu * vx * (((lF^2) * cF * cos(delta)) + ((lR^2) * cR)))
            )
            / (help2 * block.stepSize);
        G[ 3, 2 ] :=
            -1.0 * (
                  ((
                        (-cos(delta) * cF * lF * mu * vx)
                      + (h * r * m2 * ((vx^2) + (vy^2)) * sin(phi))
                      + (cR * lR * mu * vx)
                  ) * help1)
                + (vy * r * mu * (((lF^2) * cF * cos(delta)) + (lR^2) * cR))
            )
            / help2;
        G[ 3, 3 ] :=
            2.0 * (
                  ((
                      ((
                            (-5.0e-1 * (h^2) * m2)
                          - (5.0e-1 * Jy2)
                          + (5.0e-1 * Jz2)
                      ) * (cos(phi)^2))
                    + (phidot * block.stepSize * sin(phi) * help3 * cos(phi))
                    - (5.0e-1 * sin(phi) * h * m2 * vy * block.stepSize)
                    + (5.0e-1 * (h^2) * m2)
                    + (5.0e-1 * Jy2)
                    + (5.0e-1 * Jz1)
                  ) * help1)
                + (5.0e-1 * mu * block.stepSize * (((lF^2) * cF * cos(delta)) + ((lR^2) * cR)))
            )
            / (help1 * block.stepSize);
        G[ 3, 4 ] :=
              (4.0 * phidot * block.stepSize * r * help3 * (cos(phi)^2))
            + ((
                  (2.0 * help3 * ((q3 * block.stepSize) + r) * sin(phi))
                - (h * block.stepSize * m2 * ((r * vy) - q1)) * cos(phi)))
            - (2.0 * phidot * block.stepSize * r * help3);
        G[ 4, 1 ] := -h * m2 * r * cos(phi);
        G[ 4, 2 ] := -h * m2 * cos(phi) / block.stepSize;
        G[ 4, 3 ] := -2.0 * ((help3 * r * sin(phi)) + (5.0e-1 * h * m2 * vx)) * cos(phi);
        G[ 4, 4 ] :=
            (
                  (-2.0 * (block.stepSize^2) * (r^2) * help3 * (cos(phi)^2))
                - (cos(phi) * g * h * m2 * (block.stepSize^2))
                + ((block.stepSize^2) * h * m2 * ((r * vx) + q2) * sin(phi))
                + (((help3 * (r^2)) + cphi) * (block.stepSize^2))
                + (dphidot * block.stepSize)
                + ((h^2) * m2)
                + Jx2
            )
            / block.stepSize;

        rs2[ 1 ] :=
            2.0 * (
                  ((
                      (-5.0e-1 * block.stepSize * deltadot * (
                            (cF * mu * (delta - atan2(vy, vx)) * cos(delta))
                          + (sin(delta) * ((cF * mu) + FlV))))
                    + (5.0e-1 * atan2(vy, vx) * sin(delta) * cF * mu)
                    - (5.0e-1 * sin(delta) * cF * delta * mu)
                    - (
                          5.0e-1 * h * m2 * phidot
                        * ((q3 * block.stepSize) + (2.0 * r))
                        * cos(phi))
                    + (5.0e-1 * FlV * cos(delta))
                    + (
                          (r * (sin(phi) * h * m2 * (phidot^2) * block.stepSize)
                        + (5.0e-1 * m * vy)))
                  ) * help1)
                + (
                      5.0e-1 * cF * lF * mu * r
                    * ((deltadot * cos(delta) * block.stepSize) + sin(delta)))
            )
            / help1;
        rs2[ 2 ] :=
            -1.0 * (
                  ((
                      ((
                          (mu * cF * (delta - atan2(vy, vx)) * sin(delta))
                        - (cos(delta) * ((cF * mu) + FlV))
                      ) * (block.stepSize * deltadot))
                    - (FyDdot * block.stepSize)
                    + (mu * ((cos(delta) * cF) + cR) * atan2(vy, vx))
                    - (cos(delta) * cF * delta * mu)
                    + (
                          h * m2
                        * ((phidot * q4 * block.stepSize) + (phidot^2) + (r^2))
                        * sin(phi))
                    + (h * phidot * block.stepSize * m2 * ((phidot^2) + (r^2)) * cos(phi))
                    + (m * r * vx)
                    - (FlV * sin(delta))
                    - FyD
                  ) * help1)
                - (mu * r * (
                      (block.stepSize * sin(delta) * deltadot * cF * lF)
                    - (cos(delta) * cF * lF)
                    + (cR * lR)))
            )
            / help1;
        rs2[ 3 ] :=
            -2.0 * (
                  ((
                      (5.0e-1 * lF * block.stepSize * deltadot * (
                          (mu * cF * (delta - atan2(vy, vx)) * sin(delta))
                        - (cos(delta) * ((cF * mu) + FlV))))
                    - (5.0e-1 * FyDdot * b1 * block.stepSize)
                    + (5.0e-1 * mu * ((cos(delta) * cF * lF) - (cR * lR)) * atan2(vy, vx))
                    + (2.0 * r * (phidot^2) * block.stepSize * help3 * (cos(phi)^2))
                    + (phidot * cos(phi) * (
                          (help3 * ((q3 * block.stepSize) + r) * sin(phi))
                        + (5.0e-1 * h * block.stepSize * m2 * ((-r * vy) + q1))))
                    - (5.0e-1 * sin(phi) * h * m2 * r * vy)
                    - (5.0e-1 * cos(delta) * cF * delta * lF * mu)
                    - (5.0e-1 * FlV * sin(delta) * lF)
                    - (r * (phidot^2) * block.stepSize * help3)
                    - (5.0e-1 * b1 * FyD)
                  ) * help1)
                - (5.0e-1 * r * mu * (
                      (deltadot * sin(delta) * cF * (lF^2) * block.stepSize)
                    - ((lF^2) * cF * cos(delta))
                    - ((lR^2) * cR)))
            )
            / help1;
        rs2[ 4 ] :=
              (block.stepSize * b2 * FyDdot)
            + (2.0 * phidot * block.stepSize * (r^2) * help3 * (cos(phi)^2))
            + (cos(phi) * (
                  ((r^2) * help3 * sin(phi))
                + (h * m2 * ((g * phidot * block.stepSize) + (r * vx)))))
            + (((-phidot * ((r * vx) + q2) * block.stepSize) + g) * h * m2 * sin(phi))
            - (phidot * ((help3 * (r^2)) + cphi) * block.stepSize)
            - (cphi * phi)
            - (dphidot * phidot)
            + (b2 * FyD);

        dx1 := solveLinearEquations(G, rs2);
        for i in 1 : 4 loop
            block.dx[ 4 + i ] := dx1[ i ];
            block.dx[ i ] := block.stepSize * (block.x[ 4 + i ] + dx1[ i ]);
        end for;

        if signal in SOLVE_LINEAR_EQUATIONS_FAILED or hasNan1D(block.x) then
           InitializeStatesAndOutputs();
        end if;
    end DoStep;
end VehicleModel;

The resulting manifest is:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
<?xml version="1.0" encoding="UTF-8"?>
<Manifest efmiVersion="1.0.0"
          generationDateAndTime="2020-10-15T16:52:13Z"
          generationTool="Manual"
          id="{e3eae104-6417-4783-8c05-7c14e6fab8a6}"
          kind="AlgorithmCode"
          license="MIT"
          name="Vehicle model discretized by Linearly implicit Euler method"
          version="0.2"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsdVersion="0.14.0"
          xsi:noNamespaceSchemaLocation="../schemas/AlgorithmCode/efmiAlgorithmCodeManifest.xsd">
  <Files>
    <File
          id="FileID_1"
          name="Controller.alg"
          needsChecksum="false"
          path="./"
          role="Code" />
  </Files>
  <Clock id="ID_Clock" variableRefId="ID_1" />
  <Functions fileRefId="FileID_1">
    <Function id="ID_Startup" kind="Startup" />
    <Function id="ID_DoStep" kind="DoStep" />
    <Function id="ID_Recalibrate" kind="Recalibrate" />
  </Functions>
  <ErrorSignalStatus id="ID_ErrorSignal"/>
  <Variables>
    <RealVariable blockCausality="tunableParameter"
          id="ID_1"
          name="stepSize"
          start="1.0e-2" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_2"
          name="FdF"
          start="1.5e+1" />
    <RealVariable blockCausality="dependentParameter"
          id="ID_3"
          name="FlV"
          start="1.5e+1" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_4"
          name="m"
          start="1.43e+4" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_5"
          name="m2"
          start="1.2487e+4" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_6"
          name="h"
          start="1.15" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_7"
          name="lF"
          start="1.95" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_8"
          name="lR"
          start="1.54" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_9"
          name="g"
          start="9.81" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_10"
          name="Jx2"
          start="2.4201e+4" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_11"
          name="mu"
          start="1.0" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_12"
          name="cF"
          start="5.82e+5" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_13"
          name="cR"
          start="7.83e+5" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_14"
          name="Jz1"
          start="3.654e+3" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_15"
          name="Jz2"
          start="3.4917e+4" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_16"
          name="Jy2"
          start="3.4917e+3" />
    <RealVariable blockCausality="dependentParameter"
          id="ID_17"
          name="FzR"
          start="0.0" />
    <RealVariable blockCausality="dependentParameter"
          id="ID_18"
          name="FzF"
          start="0.0" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_19"
          name="cphi"
          start="4.57e+5" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_20"
          name="dphidot"
          start="1.0e+5" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_21"
          name="b1"
          start="2.0e-1" />
    <RealVariable blockCausality="tunableParameter"
          id="ID_22"
          name="b2"
          start="1.0e-1" />
    <RealVariable blockCausality="input"
          id="ID_23"
          name="u"
          start="0.0 0.0"
          min="-1.0e+7"
          max="1.0e+7">
      <Dimensions>
        <Dimension number="1"
                   size="2" />
      </Dimensions>
    </RealVariable>
    <RealVariable blockCausality="input"
          id="ID_24"
          name="&#39;derivative(u)&#39;"
          start="0.0 0.0"
          min="-1.0e+7"
          max="1.0e+7">
      <Dimensions>
        <Dimension number="1"
                   size="2" />
      </Dimensions>
    </RealVariable>
    <RealVariable blockCausality="output"
          id="ID_25"
          name="x"
          start="0.0 0.0 0.0 0.0 1.0e+1 0.0 0.0 0.0">
      <Dimensions>
        <Dimension number="1"
                   size="8" />
      </Dimensions>
    </RealVariable>
  </Variables>
</Manifest>

5. Behavioral Model Representation

The optional Behavioral Model representation defines test scenarios with reference trajectories to allow automatic verification of other model representations like Algorithm, Production or Binary Code representations. Reference trajectories are stored within a Behavioral Model container in comma-separated values (CSV) files — so called reference trajectories files. A single Behavioral Model container can have several reference trajectories files, used for varying test scenarios described in its manifest. Besides the test scenarios backed by the container’s reference trajectories files, the manifest defines acceptable tolerances (absolute and relative), type and dimensionality (any GALEC type of any dimensionality, i.e., boolean, integer or real that is a scalar, vector, matrix, or has an even higher number of dimensions), causality (any GALEC block-interface causality, i.e., input, output, tunable parameter or dependent parameter) and unit of each reference trajectory. Each test scenario thereby defines an open loop test for the GALEC block — and any model representations derived from it — of an Algorithm Code container of the eFMU.

To that end, reference trajectories in Behavioral Model manifests are linked to the GALEC block variables of an Algorithm Code manifest for which they define reference values. Other containers derived from the same algorithmic solution — like Production or Binary Code containers — can in turn be tested by matching their own tracelinks to GALEC block variables with the ones of the Behavioral Model manifest. This indirect linking of reference tests with tested components via an Algorithm Code manifest provides an universal test framework where different, independently designed Behavioral Models can be used to test independently developed executable model representations.

Two types of test scenarios are distinguished, such with variable and such with equidistant time grid. Variable time grid scenarios do not restrict by any means the time trajectory of reference trajectories; the time distance between two values of a reference trajectory (two reference points) is variable. As a consequence, application of such scenarios for testing sampled data systems (like production code) requires interpolation if reference points are not exactly at sampling points. Equidistant time grid scenarios on the other hand define reference points in equidistant intervals; interpolation is not required. Variable time grids are more common in the continuous physics simulation world, and offer higher flexibility at the potential cost of precision due to interpolation, whereas equidistant time grids are the norm for hardware-in-the-loop (HiL) tests in the embedded domain. Although free of any interpolation issues, equidistant time grid scenarios are not as flexible when it comes to actual sampling trajectories used throughout testing; late stage sampling period changes, causing the actual sampling trajectory to misalign with the equidistant time trajectory of the reference results, are not supported.

Note that, reference trajectories themselves are not causalized. The actual sampling and causalization (i.e., are reference trajectories block inputs, outputs, tunable parameters, or dependent parameters) used for testing a GALEC block are from the linked Algorithm Code manifest, whereas the reference trajectories of a reference trajectories file can stem from varying modeling and simulation scenarios. Trajectories could be derived from whole system models where the tested block is coupled to plant models or simple open loop or table-driven test scenarios, either based on a continuous, a-causal simulation or a fixed step-size simulation with well-defined input/output causalities or any combination thereof. The eFMI Standard does not anticipate any specific tooling or simulation technique used for producing reference trajectories files. In case of variable time grid, tooling used to generate Behavioral Model containers and their reference trajectories files should take care however, that the simulated behavior and respectively derived reference trajectories are of appropriate detail regarding tolerances and reference point density to replay the designed test scenario using a fixed step-size sampled algorithm (i.e., GALEC program and derived production and binary codes). To that end, it is recommended that originating models are numerical stable, including stability of used integration methods, the discontinuities of discrete or piecewise continuous trajectories are properly reflected and sufficient reference points for reasonable interpolation of continuous trajectories are provided.

Tolerances defined in the Behavioral Model manifest can help to overcome acceptable imprecisions. Supported are relative and absolute error tolerances for individual reference trajectories. Well-defined interpolation semantics for variable time grid scenarios ensure unique interpretation regarding applied values and whether actual results are within tolerance or not. Also the acceptable time tolerance between the sampling period of the Algorithm Code manifest and equidistant time grid scenarios is well-defined, as is the acceptable time tolerance between sampling trajectory and the time trajectory given in reference trajectories files.

The structure and content of the manifest describing an eFMI Behavioral Model container and its test scenarios are defined in Section 5.1. The final interpretation semantic of a test scenario defined in a Behavioral Model manifest — i.e., the semantic of reference trajectories files for testing other model representations — is defined in Section 5.2.

5.1. Behavioral Model manifest

Every eFMI Behavioral Model container is described by its manifest, an Extensible Markup Language (XML) document satisfying the XML Schema Definition (XSD) and rules given in the following.

§1: Encoding of manifests

Behavioral Model manifests must satisfy the [XML 1.0] standard; and be Unicode® Standard conforming documents encoded in UTF-8 without byte-order mark according to [ISO/IEC 10646:2020]. To denote these encoding restrictions, Behavioral Model manifests must start with <?xml version="1.0" encoding="UTF-8"?>.

The XML Schema Definition (XSD) of eFMI Behavioral Model manifests, described in the following, is according to the [XSD 1.1] standard.

§2: General structure and content of manifests

The following figure summarizes the general structure of Behavioral Model manifests; the individual XML elements will be described in detail in the subsequent sections:

efmiBehavioralModelManifest.xsd.1

The focal point of the root <Manifest> element is the <Scenarios> list defining arbitrary many test scenarios, each an individual <Scenario> element. Each scenario compiles the assets defining it by referencing to them (cf. Section 2.3.4.1 about local manifest references); actual asset definitions are in separate lists such that different scenarios can share parts of their configuration. The assets a scenario refers to are:

  • its reference trajectories file (<File> in <Files> list)

  • its mapping configuration (<CsvMapping> in <CsvMappings> list), defining the mapping of the reference time grid and the element-index-wise reference trajectories of inputs, tunable parameters, dependent parameters and output variables to column names of the reference trajectories file

  • its tolerances setup (<TolerancesSetup> in <TolerancesSetups> list), with error tolerances configurations (<TolerancesConfiguration>) for the different floating-point precisions the scenario supports

Each tolerance configuration defines the error tolerances to be used if tests are conducted with its floating-point precision. It defines error tolerances for all tested dependent parameters and outputs, each in an individual tolerances definition (<TolerancesDefinition>). The resulting XML containment structure clearly defines which configuration a tolerance is defined for (parent <TolerancesConfiguration> of <TolerancesDefinition>) and which setup the configuration is part of (parent <TolerancesSetup> of <TolerancesConfiguration>). A tolerances setup therefore can be understood as the definition of acceptable error tolerances for a set of floating-point precisions, which define the precisions supported by scenarios referencing it; if it misses a configuration for some floating-point precision, scenarios referencing it cannot be used for testing eFMU containers based on that very precision.

Besides listing scenarios, reference trajectories files, mapping configurations and tolerance setups, Behavioral Model manifests also link variables back to their respective definition in the Algorithm Code manifest. To that end, all used variables are compiled in the <Variables> list, with each <Variable> element using a <ForeignVariableReference> to define the link (cf. Section 2.3.4.3 about foreign manifest references). The causality (input, tunable parameter, dependent parameter or output) of listed variables can be resolved from the Algorithm Code manifest via these backlinks. Behavioral Model manifests also compile the units (<Units> list) referenced from variables, tolerances for such, reference time grids and clocks of equidistant time grid scenarios. Since the mapping configuration of scenarios map variables to the columns of their reference trajectories file, the causalities and units of reference trajectories are well-defined (cf. §1.1 and §1.3 of Section 5.2). Likewise, Behavioral Model manifests compile the clocks referenced from equidistant time grid scenarios (<Clocks> list) to define their presupposed sampling period. All local units and presupposed sampling periods of a Behavioral Model manifest must be consistent with the Algorithm Code manifest MA the Behavioral Model manifest refers to; only if so, model representations derived from MA, like Production Code containers, can be tested (cf. Section 5.2 for the respective consistency rules).

R-1 (system integration of Behavioral Models and tested model representations in test environments; decoupled development of algorithmic implementation and validation scenarios): The indirect linkage from a Behavioral Model manifest MB via an Algorithm Code manifest MA to other model representation manifests transitively referencing MA — e.g., a Production or Binary Code manifest MPB — defines what can be tested (everything indirectly, transitively and reflexively linked). The consistency rules of Section 5.2 between MB and MA ensure that MPB (which is derived from MA) can be tested with MB. And the GALEC block-interface and life-cycle of Section 3.4 defines how the test must be instantiated and conducted (cf. §4 of Section 5.2 for details). The latter is particularly important, since only the GALEC block-interface of MA is fixed, whereas the interface of derived production or binary code in MPB is not; but a testing tool can resolve the actual production or binary code interface of MPB and system integrate it into a test environment for testing MPB with MB by collecting the required information from the interlinked manifests.

This design decouples algorithmic implementation from validation, enabling concurrent development of either by different stakeholders. To define Behavioral Models, only an Algorithm Code manifest defining the block-interface must exist; an actual GALEC implementation — and derived Production and Binary Code containers subject to testing — can be complemented later. To that end, the tooling of a requirements and validation engineer could be the origin of an eFMU, defining the interface and application scenarios of an embedded functionality to develop.

§3: Root of manifest

The root element of a Behavioral Model manifest is the <Manifest> element, defined in BehavioralModel/efmiBehavioralModelManifest.xsd. It shares the optional <Annotations> list defined in Section 2.3.4.5 and the attributes defined in Section 2.3.1, which are common for the manifests of any eFMI model representation; its manifest kind specific attributes are kind="BehavioralModel".

The XSD of <Manifest> is:

efmiBehavioralModelManifest.xsd.2

The Behavioral Model specific elements of <Manifest> are:

Name Description

<ManifestReferences>

Foreign manifest references as defined in Section 2.3.4.3. In case of Behavioral Model manifests, a single reference to the manifest of the Algorithm Code for which this Behavioral Model defines test scenarios. The causalities of the block-interface variables, exposed error signals of block-interface functions and sampling period (called actual sampling period in the context of Behavioral Models) of the referenced Algorithm Code manifest are used to instantiate actual tests — with the test scenarios defined by this Behavioral Model — for the referenced Algorithm Code container itself or any Production or Binary Code container whose manifest transitively (i.e., directly or indirectly via a chain of references) refers to the very same Algorithm Code manifest.

<Files>

List of referenced files of the model representation as defined in Section 2.3.3. In case of Behavioral Model manifests, only container local files can be referenced and no <ForeignFile>. The files referenced (contained <File> elements) must have role="ReferenceData" and are the individual reference trajectories files of the Behavioral Model container; each must be in turn referenced by at least one test scenario.

<Units>

List of units as defined in Section 4.1.5. The defined units are referenced by the individual mappings of mapping configurations to define the unit of reference time grids and variable trajectories stored in reference trajectories files (cf. §5), tolerances definitions to define the unit of absolute tolerances (cf. §6), and the clock of equidistant time grid scenarios to define the unit of the presupposed sampling period. The units in between Behavioral Model entities and with their respective Algorithm Code entities must align according to §1.3 of Section 5.2.

<Clocks>

List of clocks referenced by equidistant time grid scenarios to define their presupposed sampling period and its time unit (samplingPeriod and unitRefId attributes of contained <Clock> elements). The presupposed sampling periods of clocks must be GALEC Real values and must align with the actual sampling period of the Algorithm Code manifest the Behavioral Model manifest refers to according to §2.2 of Section 5.2. The XSD of <Clocks> and <Clock> is defined in BehavioralModel/efmiClocks.xsd.

<Variables>

List of variables, each variable (contained <Variable> element) linked to an Algorithm Code manifest variable via a <ForeignVariableReference> (cf. Section 2.3.4.3 about foreign manifest references) to denote the GALEC variable it represents. The defined variables are referenced by tolerance definitions to denote which variable they define a tolerance for (cf. §6) and the individual mappings of mapping configurations to denote which variable they define a column mapping for (cf. §5). Variables must be linked to inputs, tunable parameters, dependent parameters or output variables of the Algorithm Code manifest; and each Algorithm Code manifest variable must be linked at most once. The XSD of <Variables> and <Variable> is defined in BehavioralModel/efmiVariables.xsd.

<Scenarios>

List of test scenarios defined by the Behavioral Model container (cf. §4).

<CsvMappings>

List of mapping configurations used by test scenarios to map the individual element-indexes of variables to column names of reference trajectories files (cf. §5).

<TolerancesSetups>

List of tolerance setups used by test scenarios to define error tolerances for dependent parameter and output variables for different floating-point precisions (cf. §6).

§4: Test scenarios of manifest

The test scenarios of a Behavioral Model manifest are defined by its <Scenarios> list; each test scenario as an individual <Scenario> element.

The XSD of <Scenarios> (complex type efmiScenarios) and <Scenario> — defined in BehavioralModel/efmiScenarios.xsd — is:

efmiScenarios.xsd

The attributes of <Scenario> are:

Name Description

name

Optional scenario name.

description

Optional scenario description.

timeGrid

Scenario type; either "variable" or "equidistant" denoting that the scenario is a variable or equidistant time grid scenario respectively.

clockRefId

Optional reference to the clock defining the scenario’s presupposed sampling period and its time unit. Must be given, if, and only if, the scenario is an equidistant time grid scenario.

fileRefId

Reference to the <File> element defining the scenario’s reference trajectories file.

csvMappingRefId

Reference to the scenario’s mapping configuration (cf. §5).

tolerancesSetupRefId

Reference to the scenario’s tolerances setup (cf. §6).

R-2 (design rationale for the separate definition of reference trajectories files, variables, clocks, mapping configurations and tolerances setups): Test scenarios only refer to their assets; the actual assets like a scenario’s reference trajectories file, mapping configuration, tolerances setup, clock (in case it is an equidistant time grid scenario) and the variables used by such are each defined in separate lists. This enables to reuse assets in different scenarios, i.e., they can be shared. A typical use-case is, for example, to share a single mapping configuration among all test scenarios; to use equivalent column names to represent the same reference trajectories among different scenarios that are created using the same tooling is not unlikely. Another use-case for shared assets is to have two test scenarios referencing the very same reference trajectories file: one scenario with variable time grid and one with equidistant. Such setup provides high flexibility: if the actual sampling period of the model to test fits the presupposed one of the scenario, the precise equidistant time grid scenario can be used, otherwise one can fallback to the variable time grid scenario. In such setup, the variable time grid scenario might use a less strict tolerances setup than the equidistant one to account for interpolation imprecisions.

The drawback of separately defined assets is, that if such are shared and an update is supposed to only change a certain of the shared test scenarios, one cannot just update the existing asset but instead must create a copy that now can be respectively changed. Just updating the existing asset would change all test scenarios referencing it. Handling correct update behavior and optimize sharing is a tool support issue however, whereas providing the means to define comprehensible test scenario narratives — like which scenarios share the same tolerances setup, finding all tolerances definitions for a variable, representing test scenarios as a collection of their assets and not vice-versa — is a standardization challenge.

Every alternative design approach has its own issues. Embedding every asset as element, such that each test scenario contains its whole definition, likely implies many copies of the very same definitions — like a common mapping configuration — if there are many test scenarios. And using another dominant composition, like letting variables define tolerances and mapping configurations and compile the actual test scenarios indirectly via links from each variable to the test scenario it is part of, destroys the convenient narrative of test scenarios being the vocal point and introduces many complicated semantic restrictions to ensure consistency and completeness (e.g., because supporting test scenarios varying in tolerances and mapping configurations would require several definitions for the very same variable, each linking to its "own" test scenario).

§5: Mapping configurations of manifests

The mapping configurations of a Behavioral Model manifest are defined by its <CsvMappings> list; each configuration as an individual <CsvMapping> element. Besides the id used to reference a mapping configuration, configurations define in which columns the trajectories for the reference time grid and individual variables are stored (<TimeData> and <ReferenceData> elements) if a reference trajectories file is structured according to the configuration. The trajectory values for a variable can require several columns if the variable is a multidimensional; in that case, the individual trajectories of the element-indexes are scalarized into separate columns defined by respective <ColumnMapping> elements. Completeness rules ensure that every mapping configuration defines a mapping for all trajectories of all variables that are required for testing; and consistency rules ensure that there are no contradictions that might cause misinterpretations (for example due to different variables mapping to the same column).

The XSD of <CsvMappings> (complex type efmiCsvMappings), <CsvMapping>, <TimeData>, <ReferenceData> and <ColumnMapping> — defined in BehavioralModel/efmiCsvMappings.xsd — is:

efmiCsvMappings.xsd

The attributes of <TimeData> are:

Name Description

columnName

Name of the reference time grid column. The column names of a mapping configuration must be distinguished according to §1.1 of Section 5.2.

unitRefId

Reference to the unit of the reference time grid. All time-related units of a test scenario (like the units of actual sampling period, presupposed sampling period and reference time grid) must align according to §1.3 of Section 5.2.

The attributes and elements of <ReferenceData> are:

Name Description

variableRefId

Reference to the variable v for which a mapping to the column(s) of reference trajectories files is defined. The referenced variables of a mapping configuration must be distinguished according to §1.1 of Section 5.2.

unitRefId

Optional reference to the default unit of all trajectories of the variable. Must not be given if the referenced variable v is scalar. Otherwise (i.e., v is multidimensional), the default unit holds for the individual trajectories of each element-index whose unit is not refined by <ColumnMapping> elements. All units a test scenario compiles for the same variable and element-index (like the units defined for it in the Algorithm Code manifest, mapping configuration and tolerance definition) must align according to §1.3 of Section 5.2.

<ColumnMapping>

List of at least one <ColumnMapping> defining the column(s) of reference trajectories files onto which the referenced variable v is mapped. If v is scalar, exactly one <ColumnMapping> element without any elementIndex must be given; otherwise, all contained <ColumnMapping> elements must have an distinguished elementIndex.

The attributes of <ColumnMapping> are:

Name Description

elementIndex

Optional index of the element for which the <ColumnMapping> defines a column. Must be given, if, and only if, the variable v the containing <ReferenceData> refers to is multidimensional. Let (s1, s2, …, sn), n∈ℕ1 be the sizes of the dimensions of v. The value i of elementIndex must be a GALEC Integer and be in range 1 ≤ i ≤ s1 × s2 × … × sn; it refers to the i'th element of v in row-major order.

unitRefId

Optional reference to the unit of the trajectory. A given value overrides any default unit of the containing <ReferenceData> element for the given element-index. All units a test scenario compiles for the same variable and element-index (like the units defined for it in the Algorithm Code manifest, mapping configuration and tolerance definition) must align according to §1.3 of Section 5.2.

columnName

Name of the column storing the trajectory for the (element-index of the) variable the containing <ReferenceData> refers to. The column names of a mapping configuration must be distinguished according to §1.1 of Section 5.2.

According to §1.1 of Section 5.2, mapping configurations must be complete, i.e., define column links for (each element-index of) all input variables according to the Algorithm Code manifest the Behavioral Model manifest refers to; and according to §1.3 of Section 5.2, must always define a unit for (the element-index of) a variable if the Algorithm Code manifest defines a unit for the respective (element-index of the) variable (thus, units are only optional if, and only if, the Algorithm Code manifest defines none; but mapping configurations can introduce units if the respective (element-index of the) variable has none in the Algorithm Code manifest).

§6: Tolerances setups of manifests

The tolerances setups of a Behavioral Model manifest are defined by its <TolerancesSetups> list; each setup as an individual <TolerancesSetup> element. Besides the id used to reference a tolerances setup, setups define a tolerances configuration (contained <TolerancesConfiguration> elements) for each floating-point precision they support; and each tolerances configuration in turn can define absolute and relative tolerances in tolerance definitions (contained <TolerancesDefinition> elements) for the dependent parameters and outputs relevant for testing. Tolerances can be defined for each individual trajectory — i.e., element-index — of a multidimensional variable, either via a default tolerance for all trajectories or by refined tolerances overriding the default for a certain element-index; the latter can be defined via individual <ElementTolerances> within a tolerances definition. Completeness rules ensure that every tolerances configuration defines tolerances for all trajectories of all variables that are of interest for testing; and consistency rules ensure that there are no contradictions that might cause misinterpretations (for example due to several, contradicting tolerances definitions for the very same variable or contradicting units between trajectory values and their absolute tolerance).

The XSD of <TolerancesSetups> (complex type efmiTolerancesSetups), <TolerancesSetup>, <TolerancesConfiguration>, <TolerancesDefinition> and <ElementTolerances> — defined in BehavioralModel/efmiTolerances.xsd — is:

efmiTolerancesSetups.xsd.1
efmiTolerancesSetups.xsd.2

The attributes and elements of <TolerancesConfiguration> are:

Name Description

floatingPointPrecision

[IEEE 754-2019] floating-point precision for which this tolerances configuration defines acceptable tolerances. One of 16-bit, 32-bit, 64-bit, 128-bit, 256-bit or any. If any, the configuration is the default configuration to be used for testing Algorithm Code containers or whenever no other specialized configuration is given for an actual test setup (i.e., when the tested Production or Binary Code container uses a floating-point precision for which the used tolerances setup misses a tolerances configuration). The floating-point precisions between the different tolerances configurations of a tolerances setup must be distinguished.

<TolerancesDefinition>

List of tolerances definitions to be used when comparing actual vs. reference values, each defining the error tolerances applicable for (a certain element-index of) a certain variable in test scenarios conducted with the floating-point precision of this tolerances configuration. The referenced variables of the tolerances definitions of a tolerances configuration must be distinguished.

In case a tolerances configuration does not contain any tolerances definition defining the absolute tolerance for (the element-index of) a variable suited as variableRefId value, the respective absolute tolerance is 0; and likewise for relative tolerances.

E-3 (minimal, generic tolerances setup): By using default tolerances in case absolute and relative tolerances are not defined, and the possibility to denote that a tolerances configuration can be used in any floating-point precision test environment (floatingPointPrecision="any") in case there is no more specific configuration available, it is possible to define a minimal generic tolerances setup working for any test scenario, block-interface and test environment:

1
2
3
4
5
<TolerancesSetups>
  <TolerancesSetup id="MinimalGenericSetup">
    <TolerancesConfiguration floatingPointPrecision="any"/>
  </TolerancesSetup>
</TolerancesSetups>

The drawback of such definition is, that, according to §3-4 of Section 5.2, an absolute and relative tolerance of 0 for (the element-index of) a variable v means, that no deviations between actual and reference values are tolerated for (the respective element-index of) v. This means, that above minimal, generic tolerances setup enforces tested code to match perfectly the expected reference trajectories. Such strict conditions are unlikely to be intentional and are very hard to satisfy considering that reference trajectories are typically not generated from the GALEC code of an eFMU’s Algorithm Code container, but instead from independent offline simulations of the model subject to eFMU generation. Hence, the simulation and tested eFMU code are likely using completely different numerical approaches and floating-point arithmetics are prone to minor deviations for even the simplest change in just the order of floating-point operations.

The attributes and elements of <TolerancesDefinition> are:

Name Description

variableRefId

Reference to the variable for which this tolerances definition defines tolerances. The referenced variable must be a dependent parameter or output of type Integer or Real.

unitRefId

Optional reference to the default unit of all absolute tolerances defined for the trajectories of the variable. Must not be given if no absolute default tolerance is defined. If the referenced variable v is multidimensional, the default unit holds for the individual absolute tolerances of each element-index whose unit is not refined by <ElementTolerances> elements. All units a test scenario compiles for the same variable and element-index (like the units defined for it in the Algorithm Code manifest, mapping configuration and tolerance definition) must align according to §1.3 of Section 5.2.

absoluteTolerance

Optional absolute default tolerance for all trajectories of the variable. If given, the value t must be a GALEC Integer if the referenced variable v is of type Integer; otherwise it must be a GALEC Real; in any case, it must hold that t ≥ 0. If v is multidimensional, the absolute default tolerance holds for the individual trajectories of each element-index whose absolute tolerance is not refined by <ElementTolerances> elements.

relativeTolerance

Optional relative default tolerance for all trajectories of the variable. If given, the value t must be a GALEC Real with t ≥ 0. If the referenced variable v is multidimensional, t holds for the individual trajectories of each element-index whose relative tolerance is not refined by <ElementTolerances> elements.

<ElementTolerances>

List of refined error tolerances for the individual element-indexes of the variable v this tolerances definition refers to. Must be empty if v is not a multidimensional (i.e., is a scalar); otherwise, all contained <ElementTolerances> elements must have an distinguished elementIndex.

A tolerances definition for a scalar variable must define at least one tolerance (i.e., either absoluteTolerance or relativeTolerance or both are given).

The attributes of <ElementTolerances> are:

Name Description

elementIndex

Index of the element for which the <ElementTolerances> defines error tolerances. Let (s1, s2, …, sn), n∈ℕ1 be the sizes of the dimensions of the variable v the containing tolerances definition refers to. The value i of elementIndex must be a GALEC Integer and be in range 1 ≤ i ≤ s1 × s2 × … × sn; it refers to the i'th element of v in row-major order.

unitRefId

Optional reference to the unit of the absolute tolerance. Must not be given if no absolute tolerance is defined. A given value overrides any default unit of the containing <TolerancesDefinition> element for the given element-index. All units a test scenario compiles for the same variable and element-index (like the units defined for it in the Algorithm Code manifest, mapping configuration and tolerance definition) must align according to §1.3 of Section 5.2.

absoluteTolerance

Optional absolute tolerance for the trajectory. If given, the value t must be a GALEC Integer if the referenced variable v of the containing tolerances definition is of type Integer; otherwise it must be a GALEC Real; in any case, it must hold that t ≥ 0. t overrides any absolute default tolerance of the containing <TolerancesDefinition> element for the given element-index.

relativeTolerance

Optional relative tolerance for the trajectory. If given, the value t must be a GALEC Real with t ≥ 0. t overrides any relative default tolerance of the containing <TolerancesDefinition> element for the given element-index.

An <ElementTolerances> element must define at least one tolerance (i.e., either absoluteTolerance or relativeTolerance or both are given).

5.2. Behavioral Model semantic

Assuming a valid Behavioral Model manifest according to Section 5.1 is given, this section defines the semantics for testing another Algorithm, Production or Binary Code container of the eFMU according to one of the test scenarios of the manifest. To that end, we define restrictions on the reference trajectories file of the scenario (i.e., under which conditions it defines reference trajectories suited for testing) and how to apply its reference trajectories for testing a GALEC block-interface and life-cycle (cf. Section 3.4) based program.

§1: Structure and content of reference trajectories files

Reference trajectories files contained in a Behavioral Model representation must satisfy [RFC 4180] and the additional constraints defined in the following.

Double quoted fields are only permitted in the header line, whose fields must not contain linefeed or carriage return characters (hexadecimal 0A and 0D in [INCITS 4-1986[R2022]]).

L-1 (implications of [RFC 4180] and restriction to printable [INCITS 4-1986[R2022]] values for CSV fields): [RFC 4180] strictly restricts the structure of valid CSV files, some are not well known or commonly violated by "CSV" tooling extending the range of valid files. eFMI reference trajectories files must comply to [RFC 4180] however, including its errata, without exceptions. Examples of typically missed restrictions are:

  • By default, [RFC 4180] only permits the subset of printable characters (hexadecimals 20 to 7E) and double quoted comma, carriage return, linefeed and quote (hexadecimals 2C, 0D, 0A and 22) of [INCITS 4-1986[R2022]] (US-ASCII) as field values. The whole CSV file is just an US-ASCII encoded file, and does not support the full Unicode® Standard or UTF-8 encoding according to [ISO/IEC 10646:2020]. This restriction is not in conflict with GALEC names, multidimensional queries of such and the values of Integer and Real (literals); such are all composed of printable characters (i.e., within the restricted subset of US-ASCII) and therefore can be used as CSV field values.

  • Only comma is supported as CSV field separator (and nothing else like semicolon).

  • The only valid line break is carriage return followed by linefeed (US-ASCII hexadecimal 0D followed by 0A). Other common combinations like just linefeed are not permitted.

  • The last record of a CSV file must have an ending line break. Hence, a CSV file must always end with carriage return followed by linefeed. This is important to disambiguate the empty record (without any field values) as last record of a single column CSV file from just the end of file.

[RFC 4180] permits to use user-defined encodings, like UTF-8, instead of [INCITS 4-1986[R2022]]. The eFMI Standard deliberately does not change the default of [INCITS 4-1986[R2022]] however. It is the most common denominator, including in particular being valid UTF-8. Target environments might not support any more advanced encoding standards; to enable code generation for hardware-in-the-loop (HiL) tests from reference trajectories files, [INCITS 4-1986[R2022]] is a good choice.

Finally note, that reference trajectories files are intended to just store trajectories, i.e., sequences of Integer and Real values. More advanced meta information requiring special characters, like column and test scenario documentation, should be denoted in the XML based manifests of Behavioral Model containers, not their reference trajectories files.

A reference trajectories file must have at least two lines (which, according to §1.1 and §1.2, are a header line defining columns followed by another line with reference values for the first sampling).

§1.1: CSV header line and column linking

The first line of a reference trajectories file is a CSV header line; it defines the columns and their names. Each column name must be unique; its value is the respective CSV field’s value without enclosing double quotes if any, and each escaped double quote (2DQUOTE in [RFC 4180]) replaced by a single double quote character (").

The first column must be the reference time grid as defined in the Behavioral Model manifest by name via the columnName attribute of the <TimeData> element of the scenario’s mapping configuration (cf. §5 of Section 5.1). Optional InitializeDependentParameters() and DoStep() columns define reference values for the error signals returned by the InitializeDependentParameters() and DoStep() block-interface functions respectively (hence, InitializeDependentParameters() and DoStep() are reserved column names with special meaning). All other column names (i.e., except the reference time grid and error signal columns) can be used by the scenario’s mapping configuration — as defined in the Behavioral Model manifest — to bidirectional link columns to individual element-indexes of block variables of the Algorithm Code manifest.

Each column can be linked to at most one block variable element-index (with scalar block variables treated as 1-dimensional with size 1), and each block variable

  • in case it is scalar, can be linked to at most one column

  • in case it is multidimensional, each of its element-indexes can be linked to at most one column

within a single reference trajectories file. Not all columns have to be linked; but whenever the manifest links a column by name and element-index via the columnName and elementIndex attributes of a <ColumnMapping> element of a <ReferenceData> element of the scenario’s mapping configuration (cf. §5 of Section 5.1), the respective column must exist in the reference trajectories file.

The reference time grid and error signal columns must not be linked. All block inputs must, for each element-index, be linked to a column. Columns for the element-indexes of tunable parameters, dependent parameters and block outputs are optional; if any element-index of such is not linked to a column, it simply is not tested. Linking block constants or states to columns is forbidden.

R-2 (restriction of reference time grid as first column): In general, mapping configurations could define any column besides the first to be the reference time grid. In practice, CSV processing — like plotting curves from a CSV file — is often much more convenient in third party tooling lacking dedicated eFMI support if the reference time grid is stored in the first column.

Likewise, the whole reference time grid column could be skipped for equidistant time grid scenarios. The sampling period of the clock of an equidistant time grid scenario, together with the knowledge about how many reference points (i.e., lines) the scenario’s reference trajectories file has, would be sufficient to define the presupposed time grid. Further third party processing of references trajectories files would become complicated however, since a reference time grid is typically required and now would have to be constructed on the fly. An explicit reference time grid also has the advantage that recording errors when constructing the reference trajectories can be detected by the consistency rules between reference time grid, actual time grid and presupposed time grid (cf. §2.2). If, for example, a references trajectories file stems from real-time recordings of hardware-in-the-loop (HiL), any real-time violations are captured when the actual recording times are stored as reference time grid.

§1.2: CSV non-header lines and reference points

Each line following the CSV header line defines the value of each column at a certain time point; the respective time point is the value given in the reference time grid column. The tuple (t, v) of the field value v of a column c for a certain time point t is called a reference point of c.

All column values must be according to the GALEC syntax for Integer and Real literals (cf. §2 of Section 3.2). Values of columns linked to GALEC Integer variables must be integers; values of columns linked to GALEC Real variables must be reals. Values of columns linked to GALEC Boolean variables have to be represented by the Integer values 0 for false and 1 for true. Values of error signal columns must be GALEC integers representing any valid combination of the error signals exposed by their respective block-interface function according to the Algorithm Code manifest (cf. §1 of Section 3.10 for details regarding pre-defined and exposed error signals). The values of the reference time grid column must be GALEC reals.

L-3 (whitespace-free trajectory values): In general, [RFC 4180] fields can contain whitespace, but above definition prohibits whitespace characters — except within header lines — since field values are GALEC Integer or Real values (i.e., without any whitespace preceding, following or inbetween).

§1.3: Unit of column values and tolerances

All values of a column, except error signal columns and the values of the CSV header line, have the same unit, defined by the scenario’s mapping configuration (cf. §5 of Section 5.1); the unit of a column is

  • in case of the reference time grid column, the unit defined by the <TimeData> element linking to the column

  • otherwise, the unit defined by the <ColumnMapping> (preferred) or <ReferenceData> element linking to the column if either defines a unit

  • ⊤ otherwise (no unit defined, therefore all units are valid w.r.t. any constraints)

Error signal columns have no unit.

The unit of an absolute tolerance ∆absolute for a linked column c is:

  • the unit defined by the <ElementTolerances> (preferred) or <TolerancesDefinition> element defining ∆absolute if either defines a unit

  • otherwise (including the case that the used tolerances configuration does not explicitly define the value of ∆absolute, but instead a default value is used according to §6 of Section 5.1), the unit of c

The unit of the reference time grid column must be equivalent to the unit of the <Clock> variable of the Algorithm Code manifest the Behavioral Model manifest links to. For equidistant time grid scenarios, the units of their <Clock> and reference time grid column must be equivalent. The unit of an absolute tolerance for a linked column c must be equivalent to the unit of c. Let uB be the unit of a linked column and uA be the unit

  • for the element-index of the variable v (in case v is multidimensional)

  • for the variable v (in case v is scalar)

in the Algorithm Code manifest the column links to; one of the following must hold:

  • uB = uA (including the special case that both are ⊤) or

  • uA = ⊤ (and uB can be anything, i.e., introduce a unit for the trajectory)

L-4 (unit equivalence between Algorithm Code and Behavioral Model containers): Since the unit of a linked column of the reference trajectories file, the block variable it is linked to, and potential tolerances must be equivalent, there is no need for unit conversions. This restriction eases implementation effort for tools, but likely will be dropped in a future version of the standard, which then supports, constraints and requires respective automatic value conversions.

Units are nevertheless explicitly defined in Behavioral Model manifests to enable the detection of misalignments, when, for example, the reference points of a scenario have been recorded using different units than a Production Code to test or absolute tolerances have different units than the trajectory they are defined for. Such errors would be nasty pitfalls if there would be no explicit units in Behavioral Model manifests, for example, when regenerating GALEC and production codes with changed units without updating Behavioral Model containers accordingly.

§2: Time grids and reference values at actual sampling points

§2.1: Reference and actual time grids

Values of the reference time grid column must be strictly monotonically increasing from line to line; their ascending ordered sequence is the reference time grid ST. It must hold that ∀t∈ST: t ≥ 0. We denote the i'th value of a sequence s via value(i, s); the first and last value of the reference time grid are therefore value(1, ST) and value(|ST|, ST) respectively.

Let sA∈ℝ be the actual sampling period according to the clock of the Algorithm Code manifest the Behavioral Model manifest links to; it must hold that sA > 0. The time tolerance ∆t± for time related deviations is

  • in case of equidistant time grid scenarios, ∆t± = 0.05 × sA (i.e., 5% of the actual sampling period sA)

  • otherwise, ∆t± = 0

The first actual sampling point tstart∈ℝ is tstart = value(1, ST) (i.e., at the smallest reference time grid value). The last actual sampling point tend∈ℝ is tend = tstart + iend × sA where iend∈ℤ is the largest number such that tend ≤ value(|ST|, ST) + ∆t± holds. All other actual sampling points are at time points t∈ℝ, tstart < t < tend for which holds: ∃i∈ℤ: t = tstart + i × sA. The ascending ordered sequence of all actual sampling points is the actual time grid SA.

R-5 (difference between reference and actual time grids): Above definition of actual sampling points has no strict implications or restrictions on the reference time grid as defined in the reference trajectories file, which — in particular for variable time grid scenarios — is independently defined from the actual time grid. For variable time grid scenarios, the values of the reference time grid can be actual sampling points, between actual sampling points or even after the last actual sampling point (e.g., a reference time grid for a test scenario with 1s sampling period could have time points at 3.1s, 5.7s and 7.9s, yielding an actual time grid with 5 points at 3.1s, 4.1s, 5.1s, 6.1s and 7.1s). For equidistant time grid scenarios, this freedom is restricted in §2.2 to ensure that the reference time grid aligns with the actual time grid within the time tolerance ∆t±.

R-6 (well-defined time span of tests): Above definitions ensure that there are no inept implicit assumptions about the starting point and time span of simulations used to generate reference trajectories files, while still ensuring unique interpretation of such:

  • Sampling starts with the first reference time grid value, whatever it is.

  • There is no need for extrapolation (because for variable time grid scenarios, ∆t± = 0 and therefore tend ≤ value(|ST|, ST); and for equidistant time grid scenarios, the last actual sampling point is at most ∆t± after value(|ST|, ST), i.e., within the time tolerance up to which to conduct tests and for which reference values are defined according to §2.3).

Thus, it is possible to do snap-shot recordings of long running simulations — where start and end time are not necessarily of any specific value — for generating reference trajectories files.

§2.2: Presupposed time grid and acceptable time deviation of equidistant time grid scenarios

Let sB∈ℝ be the presupposed sampling period according to the clock the Behavioral Model manifest defines for an equidistant time grid scenario; it must hold that sB > 0. The first presupposed sampling point tstart∈ℝ is tstart = value(1, ST) (i.e., at the smallest reference time grid value). The last presupposed sampling point tend∈ℝ is tend = tstart + iend × sB where iend∈ℤ is the largest number such that tend ≤ value(|ST|, ST) + ∆t± holds. All other presupposed sampling points are at time points t∈ℝ, tstart < t < tend for which holds: ∃i∈ℤ: t = tstart + i × sB. The ascending ordered sequence of all presupposed sampling points is the presupposed time grid SB.

For equidistant time grid scenarios it must hold that

  • |SA| = |SB| = |ST| (all time grids align on the number of samplings conducted for the scenario)

  • ∀i∈ℤ, 1 ≤ i ≤ |SA|, b[ = value(i, SA) - ∆t±, b] = value(i, SA) + ∆t±: b[ ≤ value(i, SB) ≤ b] ∧ b[ ≤ value(i, ST) ≤ b] (actual and presupposed time grids align for the scenario within the permitted time tolerance, i.e., for this scenario, the presupposed sampling period of the Behavioral Model manifest is close enough to the actual sampling period of the Algorithm Code manifest it links to; likewise, each reference time point of the reference time grid aligns with a unique actual sampling point within the permitted time tolerance; thanks to the previous constraints, and ∆t± being significantly smaller than 0.5 × sA by definition, the permitted time tolerance around actual sampling points do never overlap for which reason the alignments are bidirectional).

R-7 (difference between actual and presupposed time grids): The actual time grid defines the sampling assumed by the tested code (Algorithm, Production or Binary Code container); this is the sampling required by that very code to work properly (for example, the code might use this sampling period internally to compute derivatives). The actual time grid defines the sampling to use for testing the behavior of that very code, and therefore used to execute any test scenario. The presupposed time grid on the other hand defines the sampling under which the reference values of the reference trajectories file of an equidistant time grid scenario have been recorded.

Both must be close enough to each other (i.e., align) for the equidistant time grid scenario to be applicable for testing the given code. Otherwise, the tested code might use a wrong sampling period internally. Note, that alignment is not defined by some tolerance for the sampling period as such, for which we could always find a scenario where it is to permissive — given the scenario just runs long enough — due to sampling differences adding up over time. Instead alignment is defined for the actual scenario by applying the acceptable time tolerance ∆t± on each individual given actual sampling point.

§2.3: Reference values at actual sampling points

The reference value v of a column c at an actual sampling point ts = value(i, SA), i∈ℤ, 1 ≤ i ≤ |SA| (i.e., the i'th sampling) is

  • in case of equidistant time grid scenarios, the value of the reference point (t, v) of c for which ts - ∆t± ≤ t ≤ ts + ∆t± (i.e., for which t = value(i, ST), and therefore v is the field value of c given on the i'th line of the reference trajectories file, excluding the CSV header line from counting)

  • otherwise (i.e., in case of variable time grid scenarios)

    • in case ∃t∈ST: t = ts, the value of the reference point of c for t

    • otherwise, the interpolation result between the two reference points of c nearest to ts; the two nearest reference points r0 = (t0, v0) and r1 = (t1, v1) are the reference points of c for which holds: t0 < ts < t1 ∧ ∄t0,t1∈ST: t0 < t0 < ts ∨ ts < t1 < t1 (i.e., the reference points of c uniquely defined by the smallest index i for which t0 = value(i, ST), t1 = value(i + 1, ST), t0 < ts < t1)

Two interpolation methods are supported for the last case, constant-segment and linear interpolation. In case of constant-segment interpolation the reference value v is v0. In case of linear interpolation, let vlinear = v0 + ( ( ts - t0 ) / ( t1 - t0 ) ) × (v1 - v0); then v is

  • in case c is linked to a GALEC Boolean or Integer variable, the round half to even of vlinear (cf. GALEC built-in function roundHalfToEven)

  • otherwise, vlinear

Which interpolation method is used, depends on c

  • in case c is an error signal column or linked to a tunable or dependent parameter, constant-segment interpolation

  • otherwise, linear interpolation

If no error signal column for a block-interface function is defined, the reference value for the respective function’s error signal is 0 (i.e., a reference value for error signals of block-interface functions is always defined and tested even if no column for such exists).

R-8 (characteristics of time grids and reference trajectories): All time grids are discrete-time; their plots are points of unique value and not a curve with a continuous time axis. The other trajectories (linked block variables and error signals) are continuous-time in case of variable time grid scenarios and discrete-time in case of equidistant time grid scenarios.

These characteristics are not only of interest for correct plotting (continuous curves vs. points), but for any further processing by third party tooling. For example, interpolating the values of reference trajectories files of equidistant time grid scenarios as if they are continuous — i.e., using the CSV data like continuous curves — is highly questionable.

R-9 (reference time grids for variable time grid scenarios should follow significant trajectory changes): Variable time grid scenarios use linear interpolation; although well-defined compared to the plethora of spline interpolation schemes, linear interpolation is a rather coarse grained interpolation scheme. Whenever trajectories have significant derivative changes or discontinuities, it is highly recommended that the reference time grid of reference trajectories files contains entries close to these points of interest. Otherwise, test results might not be meaningful; they might miss to test points of interest (undersample) and/or fail because linear interpolation does not find good reference values for actual sampling points that are far off from reference time grid points. Oversampling — i.e., to have many more time points — is not problematic for variable time grid scenarios.

R-10 (life-time of reference values w.r.t. the GALEC block life-cycle): The reference values for tunable parameters are right before calling InitializeDependentParameters() and are valid at least until DoStep() finished. The reference values for dependent parameters are right after calling InitializeDependentParameters() and are valid at least until the next InitializeDependentParameters() call. The reference values for block inputs are right before calling DoStep() and are valid at least until DoStep() finished. The reference values for block outputs are right after calling DoStep() and are valid at least until the next DoStep() call. The reference values for error signals of block-interface functions are right after calling their respective function and are valid at least until the next call of the function.

§3: Tolerances and acceptable deviation at actual sampling points

Let c be a linked column for (some element-index of) a dependent parameter or output variable V. According to §6 of Section 5.1, an absolute and relative tolerance ∆absolute and ∆relative will be defined for c if V is of type Integer or Real, either explicitly in the Behavioral Model manifest by some tolerances definition or implicitly if such is missing. Let vr be the reference value of c at some actual sampling point. A value v is within tolerance of vr, if, and only if,

  • in case V is of type Integer or Real, |vr - v| ≤ ∆± where ∆± is the maximum of ∆absolute and ∆relative × |vr|

  • otherwise (i.e., V is of type Boolean), v = vr

In case V is of type Integer, above equation is evaluated in real arithmetics by first promoting vr and ∆absolute to Real according to the GALEC built-in function real() (ignoring any error signals of it); this implies in particular that ∆± can be a proper real value in case the fractional part of ∆relative is not 0, and ≤ is a real comparison.

§4: Interpretation of test scenarios

§4.1: Test configuration

Given a test configuration C = (Cscenario, Ctested, Cenvironment), where Cscenario is a test scenario, Ctested a container of the same eFMU, and Cenvironment the test environment comprising of all hard- and software components involved to conduct the test. C is a valid test configuration — and Cscenario can be used to test Ctested in Cenvironment according to §4.2 — if, and only if:

  • Ctested is a testable container of the eFMU

  • the tolerances setup of Cscenario provides a suited tolerances configuration for Ctested

  • Cenvironment supports the floating-point precision selected for testing

The testable containers of an eFMU are its Algorithm Code container, if it is not a pure-interface (i.e., provides a GALEC block implementation), or any container — except Behavioral Model containers — transitively derived from it (i.e., whose manifest refers directly or indirectly, via other manifests, to the Algorithm Code container of the eFMU).

The target environment precision of a testable container is:

  • in case of Algorithm Code containers, any

  • in case of Binary Code containers, the target environment precision of the Production Code container they refer to

  • in case of Production Code containers, the value of the floatingPointPrecision attribute of the <CodeContainer> element of their manifest

A tolerances configuration is suited for a testable container, if the value of its floatingPointPrecision attribute is either, the target environment precision of the testable container or any. In case several tolerances configurations are suited (i.e., there exists one with floatingPointPrecision="any" and one with the target environment precision), the most specific one (i.e., the one with the target environment precision) is selected for testing.

Let Ctolerances be the tolerances configuration selected to test Ctested with Cscenario in Cenvironment. The floating-point precision Cfpp selected for testing is

  • in case floatingPointPrecision="any" of Ctolerances, the highest possible [IEEE 754-2019] floating-point precision supported by Cenvironment; if such does not exist, Cfpp = ⊥ (i.e., Cfpp is undefined)

  • otherwise, the value of the floatingPointPrecision attribute of Ctolerances

Cenvironment supports the floating-point precision selected for testing, if, and only if, Cfpp ≠ ⊥ (i.e., Cfpp is defined) and Cenvironment conducts any real arithmetics of §1-3 according to [IEEE 754-2019] in Cfpp; this comprises:

  • the reading of the values of reference points from reference trajectories files, and tolerances, default start values and sampling periods from manifests (values of Real variables must be stored in Cfpp); any values read of a higher precision than Cfpp must be rounded toward the nearest value representable in Cfpp; the rounding is toward 0

  • reading of reference time grid values, construction of actual and presupposed time grids, and checking that the respective trajectories are aligned according to §2.1 and §2.2 (respective Real values, including any intermediate values, must be stored and processed by computations in Cfpp)

  • computation of interpolations according to §2.3 (respective computations must be conducted in Cfpp)

  • decision if values are within tolerance according to §3 (respective computations must be conducted in Cfpp)

R-11 (invalid Behavioral Model containers vs. nonapplicable scenarios vs. failed tests): In case of any violations of the manifest schema as defined in Section 5.1, the Behavioral Model container, and all its test scenarios, are invalid. Invalid containers and scenarios cannot be used for testing according to §4.

Otherwise (i.e., if the manifest satisfies all rules of Section 5.1), but in case of any violations of rules §1-2.1 (i.e., w.r.t. a certain scenario and its reference trajectories file but excluding alignment rules related to reference time grids of equidistant time grid scenarios), the respective scenario is invalid. Invalid scenarios cannot be used for testing but other scenarios of the container might still be valid and usable for testing.

Scenarios violating only rules of §2.2 are nonapplicable (due to a too large reference time grid deviation compared to the actual sampling period); they too cannot be used for testing, but are easy to fix by regenerating the reference points of the equidistant time grid scenario with appropriate resolution (by using a sampling period aligned with the sampling period of the Algorithm Code container).

Scenarios missing a tolerances configuration for a certain floating-point precision and without a tolerances configuration with floatingPointPrecision="any" are nonapplicable for testing other eFMU containers requiring that very precision.

If a scenario is neither invalid nor nonapplicable and a valid test configuration is given, it can be used for testing as described in §4.2, in which case the test either passes or fails.

L-1 (optional, production and binary code dependent support for recalibration): A test tool must reject — i.e., consider to be nonapplicable — scenarios requiring recalibration for testing Production or Binary Code containers which dropped recalibration support (i.e., assume all tunable parameters are constants fixed to their default initialization value and therefor do not provide an implementation of the block’s InitializeDependentParameters() function). A scenario requires recalibration, if a column of a used reference trajectories file is linked to a tunable or dependent parameter and contains any value different to the parameter’s default initialization value (considering tolerances).

L-2 (undecidable applicability of variable time grid scenarios): For equidistant time grid scenarios applicability for a given Algorithm, Production or Binary Code container is decidable. The alignment rules of §2.2 between time grids ensure that the sampled system can be tested with the given reference trajectories without the risk of undersampling. In fact, for each sampling exact reference points are defined. This is not the case for variable time grid scenarios; that is why rationale R-9, that the reference time grids of variable time grid scenarios should follow significant trajectory changes, is important. A user of a variable time grid scenario cannot decide if its reference time grid is suited for the actual sampling period; he must trust that the producer recorded good enough reference trajectories.

§4.2: Test execution

The execution of a valid test configuration within its test environment (i.e., the interpretation of a test scenario for testing a certain testable eFMU container) follows the GALEC block-interface and life-cycle (cf. Section 3.4), with the sampling — and therefore interactions with block-interface variables and functions — following the actual time grid SA. Let B be the tested block:

  • B is default initialized (cf. §3 of Section 3.4) before any other block-interface interaction. If the error signal returned by any of its initialization functions (InitializeConstants(), InitializeTunableParameters(), InitializeDependentParameters(), InitializeInputs(), and InitalizeStatesAndOutputs()) is not 0, the test fails.

  • At each actual sampling point, the linked tunable parameters and block inputs of B are set to their reference values before calling any block-interface function.

  • The InitializeDependentParameters() function of B is executed once at the very first actual sampling point if the default start value, according to the Algorithm Code manifest, of any linked tunable parameter is either, undefined, or not equivalent to its reference value. The InitializeDependentParameters() function of B is also executed once at any further actual sampling point where the reference value of any linked tunable parameter is not equivalent to its reference value at the previous sampling point.

  • The DoStep() function of B is executed once at each actual sampling point, after any InitializeDependentParameters() execution. Afterwards, the values of linked dependent parameters and linked block outputs of B (the actual values) are checked if they are within tolerance of their respective reference values; if any is not, the test fails.

  • Whenever a block-interface function of B is executed after default initialization, its returned error signal is compared to its respective reference value (according to §2.3, such is always defined); if the returned error signal and reference value are not equivalent, the test fails.

  • There are no further interactions with B than the ones defined above.

A test passes, if, and only if, it does not fail.

6. Production Code Model Representation

A Production Code Model Representation of an eFMU container contains the actual sources that implement the algorithm expressed in Algorithm Code Model Representation of the same eFMU container.

As mentioned before an eFMU container can contain any number of Production Code Model Representations.

ProdCode Container

The following code parts may be present inside each Production Code Model Representation:

  • Production Code: This section contains the actual Production Code running on the embedded device. In later development steps it shall be compiled and linked to be integrated in the target environment.

  • [optional] Simulation Code: This code is used to simulate the target environment of the Production Code. It may provide stub functions for communication with other software functions.

  • [optional] Tool Specific Code: Tool Specific Code may help tools to integrate the Production Code in their (execution) environment.

  • [optional] FMU container: This FMU container may be extracted and copied to the surrounding FMU Data to be consumed by FMI compatible tools directly.

The structure of the Model Representation is organized in a folder structure, but not standardized. Instead, the actual structure of the Model Representations’s content, e.g. code at least as far as interfaces and externally accessible parts are concerned, is formally described in the manifest file of the Model Representation. The Model Representation is "registered" in the "__content.xml" registry of the eFMU container.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
                  +---------------------+
                  |     __content.xml   |
                  +---------------------+
                    ^                 ^
                    | registers       |
                    |                 |
    +---------------+-+             +-+------------------------------------+
    | Algorithm       |             | Production Code Model Representation |
    | Code            | references  |                                      |
    | Container       |       +-----| manifest.xml                         |
    |                 |       :     |  folder                              |
    |   manifest.xml  |<------+     |     model.h                          |
    +-----------------+             |     model.c                          |
                                    +--------------------------------------+

The manifest itself references to a manifest of a Algorithm Code Model Representation for more detailed information.

For each different target environment there exist a dedicated Production Code section inside an eFMU container. A special target environment is the generic one, where the included C code doesn’t contain target environment specific parts, e.g. assembler code sections or code assuming a certain target environment. Such a generic C code is therefore portable, i.e. compilable on an ARM architecture as well as on a i86 architecture. This flexibility allows for including an FMU into the Production Code Model Representation, that uses the generated Production Code and a FMI compatible interface.

Note An example use case for the FMU container is an early back-to-back test while already using the target environment datatypes: After modelling an controller, developers can easily check the resulting Production Code using FMI compatible tools.

A generic target environment allows for testing and simulating the Production Code in an environment other than the embedded target environment, which may require additional software parts to interface with. These software parts can simulate parts of an operating system of the microcontroller, create stubs to represent other software functions that interact with the software-under-test or handle inputs, outputs and the execution.

Note Testing a Production Code Model Representation in a Processor-in-the-Loop scenario, tools using their own execution frame on the targed board. To support these use-cases this kind of code can be stored as Tool Specific Code inside the Production Code Model Representation. The name of the tool and its version have to be specified in the manifest file referencing the code.

6.1. Production Code Manifest

The Production Code manifest follows the general guidelines as pertaining to all manifests, including the listing of relevant manifests and files. In addition it describes the content of the "Code Files":

ProductionCodeManifest

On the top level, the schema consists of the following elements:

Name Description

attributes

The attributes of the top-level element are the same for all manifest kinds and are defined in section Section 2.3.1.
Current kind-specific values: kind = "ProductionCode", xsdVersion (value is the current xsd version of the schema for the Algorithm Code model manifest).

ManifestReferences

Reference to the manifest of the Algorithm Code on which this Production Code manifest is based on. This element is the same for all manifest kinds and is defined in section Section 2.3.4.3.

Files

List of files referenced in this model representation. This element is the same for all manifest kinds and is defined in section Section 2.3.3.

CodeContainer

Defines the details of the production code. For details see Section 6.1.2.

Annotations

Additional data that a vendor might want to store and that other vendors might ignore. For details see Section 2.3.4.5.

The Production Code manifest describes the structure of the contained "Production Code". Languages for the producion code include the "C" language and the "C++" language. The manifest will give more detailed information on the exact requirements on the Production Code language to integrate the code into an actual ECU software content.

Note The Production Code manifest focusses on aspect directly tied to the Production Code itself in particular the technical aspects. Relevant aspect relating to the algorithm or the "logical" concepts are referred to from the Algorithm Code manifest (e.g. whether an object is a state or calibration parameter, input or output etc.).

The Production Code manifest is an xml file with structured information about the Production Code. It contains two sections:

  • Production code description section: This section contains all information directly pertaining to the code itself, i.e. the "technical realisation".

  • Mapping section: this section contains all information relating to mapping the elements of the technical realistion (aka. the C-code) to the logical elements of the Algorithm Code.

This distinction into logical (as e.g. described in the Algorithm Code) and technical parts is crucial and is shown in one example here.

Example: Suppose a (logical) function f that computes outputs y1 and y2 from inputs x1 and x2 and a state s1 using parameters p1 and p2. This logical function could be implemented in several ways, e.g.:

  • f1 working on global variables only. In this case the (technical) function signature is that of a void void function and the expressions directly access the elements.

void f1() {
    ...
    s1 = ...  /* update of state s1 */
    y1 = ...  /* y1 expression */
    y2 = ...  /* y2 expression */
}
  • f2 that takes the inputs as arguments and returns output y1 as return value and y2 via a pointer. Access to state and parameters is through global variables

float f2(float x1, float x2, float *y2) {
    ...
    s1 = ...  /* update of state s1 */
    *y2 = ...  /* y2 expression */
    return ...;  /* y1 expression */
}
  • f3 that that works like f2 but takes the states as a struct with two elements

…​ typedef struct { float s; float t; } states;

…​

float f3(float x1, float x2, states myStates, float y2) { …​ myStates.s = …​ / update of state s1 / *y2 = …​ / y2 expression / return …​; / y1 expression */ }

  • f4: In this example the parameter and the state are coupled in a data structure (e.g. a spring with parameter being the rigidity of the spring and the state being the deflection). As both are not in the same memory (one is in ROM the other in RAM), the one value is referenced per pointer. The C function itselfs takes as input an array with the two pairs.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
...
typedef struct {
   float *deflection;
   float rigidity;
} spring;

....

float f4(float x1, float x2, spring[] springs, float *y2) {
    ...
    springs[0].deflection = ....  /* update of state s1 */
    *y2 = ...  /* y2 expression */
    return ...;  /* y1 expression */
}

As can be easily seen by these example, there is a big difference between the logical variables on which a function operates, and the representation of these in code. As the last two examples show, this can even go so far that the code structure contains elements that do not directly appear in the Algorithm Code.

Wheras the technical description part of the manifest relates solely to the technical (realisation) aspects of the C Code, the mapping section is dedicated to bridge the gap between the two levels of abstraction: the Algorithm Code and the Production Code.

6.1.1. Technical description of Production Code

The technical description part of the Production Code manifest specifies the following aspects of the code:

  • the underlying language including detailed information on the version of the language

    • any restrictions / specification on the target environment (e.g. HW) for which the code is intended for

    • any restrictions / specification on the compilers to be used included specifics on compiler versions and configuration

  • Definition of the type (numeric) type system on the target environment. This section maps the standardized (eFMI-) types onto the target environment types. These may depend on the compiler (e.g. some compilers use "int" for 32 bit and "long" for 64 bit, others use "long" for 32 bit and "long long" for 64 bit).

  • Definition of the code itself. The code is thereby grouped in "Modules" which contain source files (for the language "C" normally a module contains a ".c" and a ".h" file).

For each file the content (as far as relevant and accessible) is described. This includes:

  • references ("includes") to other files (defined in the Production Code manifest).

  • defined types in that file (referring to the defined and standardized target environment types). Usually these are specifically defined names for the type like e.g. "uint8" that are used in the actual Production Code. These defined types also contain definitions for structured types

  • defined macros (if any)

  • defined variables in the file

  • defined functions in the file.

For Production Code Model Representations that contain e.g. AUTOSAR Classic or Adaptive code, there exist additional so-called description files, describing the technical aspects of the code. Those description files must be listed in the Code Container and are the alternative to the above mentioned details in the manifest and must be use instead.

6.1.2. Code Container

The code container groups the actual Production Code Model Representaion content, and gives specification for the following details:

CodeContainer
Name Description

language

Language to be used. Currently, the following values are possible: "C" or "C++".

standard

Relevant language standard to be used.

platform

The target environment. Currently, the following values are possible:
"Legacy" (= xxx)
"Classic" (= xxx)
"AUTOSAR" (= xxx)
"Adaptive AUTOSAR" (= xxx)

floatPrecision

Floating point precision of the target environment. Currently, the following values are possible: "32-bit" or "64-bit".

description

Optional description

Target

Unique identifier, if the production code uses target environment specific code parts, for example assembler op codes; otherwise the identifier is the default Generic.

CompilerOptions

List of Compiler Options for Production or Binary Code. For more details, see section Section 6.1.2.1.

LinkerOptions

List of Linker Options for Production or Binary Code. For more details, see section Section 6.1.2.4.

TargetTypes

Defines which kind of data type (kind) in the eFMI specification is mapped to a certain target environment type. Usually all kinds are listed although they are not used in the production code container. E.g. a kind "Bool" may be mapped to unsigned char in case of [ISO/IEC 9899:1990]; and using [ISO/IEC 9899:2024], the kind shall be mapped to bool. For each coded type, there exists a unique TargetType in order to abstract from the target environment types. For more details, see section Section 6.1.2.7.

CodeFiles

List of files in model representation, i.e. source file and/or header file including any information needed to integrate the code in an environment. For more details, see section Section 6.1.3.

TechnicalInformationLookUps

Facilitates a quick access to information in the manifest and the associated C files. For more details, see section Section 6.1.4.

LogicalData

Defines how the logical elements (variables, functions etc.) are mapped to the actual data structures and elements of functions and defined variables. For more details, see section Section 6.1.5.

Compiler Options
CompilerOptions
Name Description

compileRoot

Directory where compilation should be performed.

CompilerSwitch

Compiler switch, see Section 6.1.2.2.

PreprocessorDefinition

Preprocessor definition, see Section 6.1.2.2.

AdditionalIncludeDirectory

Additional include directory, see Section 6.1.2.2.

CompilerOptionReference

Reference to option in another manifest file, see Section 6.1.2.3.

Compiler Option Type
CompilerOptionType
Name Description

id

Id of option.

name

Name of option.

value

Value of option.

description

Optional description of option.

optional

Definition of option is optional. Possible values: "false" (default) or "true".

Compiler Option Reference
CompilerOptionReference
Name Description

index

Index of the option reference in the list of option references.

id

Id of option reference.

manifestReferenceRefId

If of foreign manifest file.

foreignRefId

Id of option in foreign manifest file.

Linker Options
LinkerOptions
Name Description

LinkerSwitch

The linker switches of type [LinkerOptionType].

Library

Library of type [LinkerOptionType].

AdditionalLibraryDirectory

Additional library directory of type [LinkerOptionType].

LinkerOptionReference

A list of option references, see Section 6.1.2.6.

Linker Option Type
LinkerOptionType
Name Description

id

Id of option.

name

Name of option.

value

Value of option.

description

Optional description of option.

optional

Definition of option is optional. Possible values: "false" (default) or "true".

Linker Option Reference
LinkerOptionReference
Name Description

index

Index of the option reference in the list of option references.

id

Id of option reference.

manifestReferenceRefId

Id of foreign manifest file.

foreignRefId

Id of option in foreign manifest file.

Target Types

Target types define which kind of data type (kind) in the eFMI specification is mapped to a certain target environment type. Usually all kinds are listed although they are not used in the production code container. E.g. a kind "Bool" may be mapped to unsigned char in case of [ISO/IEC 9899:1990]; and using [ISO/IEC 9899:2024], the kind shall be mapped to bool. For each coded type, there exists a unique TargetType in order to abstract from the target environment types.

TargetTypes
Name Description

id

The unique id of the target environment type.

kind

The kind of the target environment type. The value must be one of the predefined kinds from the following list: "efmiInteger8", "efmiUnsignedInteger8", …​ , "efmiUnsignedInteger64", "efmiFloat32", "efmiFloat64", "efmiFloat128, "efmiBoolean", "efmiVoid".

codedType

The actual Production Code type to be used, e.g. "unsigned char".

Example:

1
<TargetType id="TT_float64" kind="efmiFloat64" codedType="double"/>

6.1.3. Code Files

The code file section describes the actual content of a (production) code file. It refers to one of the files listed in the "Files" section, so it is clear which file’s content it actually species

CodeFiles
Name Description

id

Unique id.

fileType

Type of the file. Allowed values: "ProductionCode", "SimulationCode", "ToolSpecificCode".

codeType

Type of the code. Allowed values: "SourceFile", "HeaderFile".

FileReferece

Reference to a file element in this manifest file, see Section 2.3.4.2.

Includes

Definition of include files, see Section 6.1.3.1.

Typedefs

Definition of typedefs, see Section 6.1.3.2.

Macros

Definition of macros, see Section 6.1.3.2.3.

Variables

Definition of variables, see Section 6.1.3.2.4.

Functions

Definition of functions, see Section 6.1.3.2.5.

Example:

1
2
3
4
<CodeFile id="C_1" fileType="ProductionCode" codeType="SourceFile">
   <FileReference fileRefId="F_22" kind="code"/>
   .....
</CodeFile>
Includes

Includes represent include preprocessor statements. Linker dependencies to certain libraries are part of the linker sections of the BuildInformation.

Includes
Name Description

codeFileRefId

id of the included file. This attribute might be empty if the include is of a library.

Example:

1
 <Include codeFileRefId="F_1"/>
Typedefs

Typdefs are used to either define structured types, array types or alias types (of predefined types).

TypeDefs
Name Description

id

Unique id of typedef.

name

name of the type

Alias

Alias means renaming of types, e.g. "typedef unsigned char MyUint8_t;". Therefore the targetTypeRefId is always set and references the certain TargetType in the target environment type list and in cases of cascaded Typedefs, also the typeDefRefId is set. Usually, a TargetType is referenced by a most one Typedef statement. If a basetype is renamed (e.g. Int16 → MyInt16) or a user type based on an existing type is defined, two or more Typedef statements may point to a single TargetType.

Pointer

Declares a type that is a pointer to another type. This type can be any other defined type.

Components

Definition of a struct. Structs in structs are allowed but Dimensions have to be specified at variable definitions only. For details see Section 6.1.3.2.1.

EnumerationItems

Definition of an enum. For details see Section 6.1.3.2.2.

The following is an example of a simple alias declaration

Example:

1
2
3
  <Typedef name="Float32" id="TD_F32">
      <Alias targetTypeRefId="TT_float32" />
  </Typedef>

The more complex data structure of function spring of the fourth example would be described by the following snipppet:

1
2
3
4
5
6
7
  <Typedef name="spring" id="TD_spring">
      <Components>
        <Component id="C_1" name="deflection" typeRefId="TD_F32" pointer="true">
        <Component id="C_2" name="rigidity" typeRefId="TD_F32">
      <Components>
      <Alias targetTypeRefId="TT_float64" />
  </Typedef>
Components (struct)

Components declare a structure and are a list of Component:

TypeDefsComponents
Name Description

id

Unique id.

Name

Name of the field. Must be unique within one <Components> tag.

typeDefRefId

Reference of the type of the field.

pointer

Boolean flag on whether the field is a reference or not (optional field).

Each field can be an array. This is indicated with the subelement <Dimensions> that contains a list of <Dimension> elements, each with the following attributes:

Name Description

number

The index of the dimension.

size

The size (number of elements) of that dimension.

valueMacroRefId

Instead of the size a reference to the value macro defining the size.

Enumeration Items (enum)
TypeDefsEnumerationItems

<EnumerationItems> declares an enumeration type with the list of enumeration items. Each <EnumerationItem> has the following fields

Name Description

id

Unique id.

name

Name of the enumeration literal. This name must be unique within an enumeration definition (`<EnumerationItems>)

value

Encoded value (this field is optional).

Macros

Here all macro definitions in the source and header file of the module are listed that are relevant to integrate the code. For example system constants used to define integration relevant vector variables must be part of the list, whereas macros in the code used as guards must not be part of the list.

There are two kind of macros "ValueMacro" and "ParameterizedMacro". Both are contained as children in the "Macros" tag.

Macros

A value macros defines a symbol and assigns a value to it. The value must be a number

Name Description

id

Unique id.

name

Name of the macro variable.

value

Concrete value of the macro variable.

Annotations

Additional data that a vendor might want to store and that other vendors might ignore. For details see Section 2.3.4.5.

A parameterized macro defines however only the signature of a macro with parameters. Thereby each parameter is given as a "Parameter" element with attrubtes for its name and its position (since xml is not guaranteed to be order-preserving). The positions must be the values 0 …​ n-1 where n is the number of parameters.

Name Description

name

Name of the macro argument.

Number

Position of the macro argument.

The following example shows the declaration of a value and a parametrized macro

1
2
3
4
5
6
7
  <Macros>
      <ValueMacro id="VM_1" name="num_Cyl" value="4"/>
      <ParameterizedMacro id="PM_1" name="myMax">
      		<Parameter name="a" number="0">
      		<Parameter name="b" number="1">
      </ParameterizedMacro>
  </Macros>
Variables

<Variable> elements are grouped in the <Variables> element.

Variables
VariableAttributes
VariablesAccessFcnRef

Each variable has the following attributes:

Name Description

id

Unique id of the variable.

name

Name of the variable.

typedefRefId

id of the defined type of the variable.

address

Optional address.

value

Optional initial value of that variable that must be consistent which the initial value in Algorithm Code. Value might be different because of a decision to implement the Algorithm Code variable in a different datatype, for example Algorithm Code variable is Float64 and Production Code variable is Float32.

min

Optional minimum value (see value).

max

Optional maximum value (see value).

const

Optional Boolean value on whether the variable is constant.

volatile

Optional Boolean value on whether the variable is volatile.

pointer

Optional Boolean value whether the variable is a pointer of the type or a variable of that type.

constPointer

Optional Boolean value whether the variable is a const pointer.

static

Optional Boolean value on whether the variable is static.

Similar like a field in a <Component> a <Variable> can also be multidimensional by adding the <Dimensions> element. The following example defines a 2x2 array of variables with name "T".

1
2
3
4
5
6
7

  <Variable id="V_33" name="T" typeDefRefId="TD_F64" pointer="false" value="0.1" const="false" volatile="true" static="false">
     <Dimensions>
        <Dimension number="0" size="2">
        <Dimension number="1" size="2">
     </Dimensions>
   </Functions>
Functions

The described functions of (production) code files are grouped in the "Functions" tag. Each function has an "id" and a "name". In addition it has a subelement for the return parameter (if the function is void, the subelement is not present) and a list of "formal parameter". The return parameter (if present) and the formal parameters list.

Functions
FunctionReturnParameter
FunctionFormalParameters

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<Functions>
	<Function id="Func_1" name="doStep">
  		<FormalParameters>
			<FormalParameter id="V_33" name="T" number="0" typeDefRefId="TD_F64">
		</FormalParameters>
  	<Function/>
  	<Function id="Func_2" name="doStep2">
  		<ReturnParameter id="Func_2_ret" typeDefRefId="TD_F64" pointer="false">
 	<Function/>
<Functions/>

6.1.4. Technical Information Lookups

Facilitates a quick access to information in the manifest and the associated C files.

TechnicalInformationLookup
Name Description

DeclaredTypeDefs

List of all typedef statements in C code

GlobalAccessableDataElements

List of all global variables and global available access functions

Both lists consist of elements, DeclaredTypedef and GlobalAccessableDataElement respectively, that only have a reference attribute to a certain kind of element.

Attribute of DeclaredTypedef:

Name Description

typeDefRefId

Reference to a TypeDef element in the manifest.

Attribute of GlobalAccessableDataElement:

Name Description

variableRefId

Reference to a Variable element in the manifest.

6.1.5. Logical Data

Defines how the logical elements (variables, functions etc.) are mapped to the actual data structures and elements of functions and defined variables.

The description in the code files basically describes only Production Code parts. As shown in the beginning of this section the mapping to the Algorithm Code is sometimes not obvious, for example because variables in the Algorithm Code do only appear as arguments or are may be part of structures or arrays. Therefore we describe this mapping explicitely.

The mapping is given in the element LogicalData which contains the DataReferences and the FunctionReferences.

LogicalData

A DataReference itself contains the following attributes and elements to identify the variable in the Production Code and the mapped variable in the Algorithm Code

DataReference
Name Description

ForeignVariableReference

Subelement of type ForeignReference to the element in the Algorithm Code.

GlobalVariable

Reference to a declared global accessible variable in the current manifest. If the referenced variable is of a complex type, the componentIdentifier gives the "path" within that complex variable. The "." is used as component separator, brackets are used for array index, e.g. "a.b[3].c" means that the refered variable has a field "a" that itself contains a field "b" which is an array of a complex type that contains a field "c".

FormalParameter

Reference to a formal parameter of a global accessible function by the formalParameterRefId attribute in the current manifest. If the referenced parameter is of a complex type, the componentIdentifier gives the "path" within that complex parameter. The "." is used as component separator, brackets are used for array index, e.g. "a.b[3].c" means that the referred parameter has a field "a" that itself contains a field "b" which is an array of a complex type that contains a field "c".

A FunctionReference is similar to the DataReferences mapping Algorithm Code functions, mainly the block interface functions, to functions in the Production Code.

FunctionReference
Name Description

ForeignFunctionReference

Subelement of type ForeignReference to the element in the Algorithm Code.

GlobalFunction

Reference to a declared global accessible function in the current manifest by functionRefId attribute.

6.2. Production code characteristics

The source code files of a Production Code container are for a well-defined programming language, potentially compliant with further guidelines and standards. These production code characteristics are defined by respective attributes of the <CodeContainer> element of the manifest of a Production Code container; and since the <CodeContainer> element is unique, hold for all source code files (i.e, all source code files share the same configuration).

The mandatory language and optional languageStandard attributes define the programming language of source code and the actual language revision the code is compliant with respectively. The following table summarizes the permitted configurations:

Attribute language="C"

Value of optional languageStandard attribute

Normative reference

1990

[ISO/IEC 9899:1990]

1999

[ISO/IEC 9899:1999]

2011

[ISO/IEC 9899:2011]

2018

[ISO/IEC 9899:2018]

2024

[ISO/IEC 9899:2024]

Attribute language="C++"

Value of optional languageStandard attribute

Normative reference

1998

[ISO/IEC 14882:1998]

2003

[ISO/IEC 14882:2003]

2011

[ISO/IEC 14882:2011]

2014

[ISO/IEC 14882:2014]

2017

[ISO/IEC 14882:2017]

2020

[ISO/IEC 14882:2020]

2024

[ISO/IEC 14882:2024]

If the languageStandard attribute is given, source code must be compliant with the respective standard.

The additional guidelines (e.g., coding conventions, development standards, weaknesses and vulnerabilities recommendations, etc) the source code of a Production Code container is compliant with are defined by the optional guidelines attribute. Permitted values are not standardized, except that the list of guidelines is semicolon separated and the following names are reserved to denote well-established standards:

Attribute language="C"

Listed within value of guidelines attribute

Normative reference

MISRA C:1998

[MISRA C:1998]

MISRA C:2004

[MISRA C:2004]

MISRA C:2012

[MISRA C:2012]

MISRA C:2023

[MISRA C:2023]

MISRA C:2025

[MISRA C:2025]

SEI CERT C 2016

[SEI CERT C 2016]

Attribute language="C++"

Listed within value of guidelines attribute

Normative reference

MISRA C++:2008

[MISRA C++:2008]

MISRA C++:2023

[MISRA C++:2023]

SEI CERT C++ 2016

[SEI CERT C++ 2016]

If guidelines lists a reserved name, the language attribute must have the value indicated in above table. Source code must be compliant to the listed guidelines.

R-1 (standards and production code quality; restricted set of supported source code languages): The C programming language is defined in the ISO/IEC 9899 standards series, starting with [ISO/IEC 9899:1990] and the latest version [ISO/IEC 9899:2024]. Likewise, the C++ programming language is defined in the ISO/IEC 14882 standards series, starting with [ISO/IEC 14882:1998] and the latest version [ISO/IEC 14882:2024].

For both programming languages, well established guidelines to facilitate code safety, security, portability and reliability in the context of embedded software systems exist. Examples are the [MISRA C:2025] and [MISRA C++:2023] standards published by the Motor Industry Software Reliability Association (MISRA), or the [SEI CERT C 2016] and [SEI CERT C++ 2016] standards published by the Computer Emergency Response Team (CERT) Coordination Center of the Software Engineering Institute (SEI) of Carnegie Mellon University.

Although optional, compliance with language and guideline standards is highly recommended to achieve a high level of implementation portability, quality, and credibility; at least a language standard should be typically enforced. To omit the languageStandard and guidelines attributes is only prohibited to ease adaptation of the eFMI Standard; and because as a newly released standard, eFMI naturally only supports a constrained set of third party standards to start with. In future revisions of the eFMI Standard both attributes might become mandatory.

An important reason for the limited support of source code languages — i.e., why not just permit arbitrary files to be the sources of some implementation — is to enable universal system integration of production code as required for example for testing such as described in §4 of Section 5.2. Universal system integration requires that sources can be well-defined compiled, deployed and utilized, which in turn requires that users and tooling know what to do with it. The manifests of eFMI Production Code containers achieve this by describing the sources in terms of their mapping to the standardized GALEC block-interface (cf. Section 3.4). The required manifest elements are source code language specific and rather involved; supporting further languages besides C and C++ requires respective extensions and tool support. Likely candidates for future support are the Rust programming language and Structured Text according to [IEC 61131-3].

7. Binary Code Model Representation

The Binary Code Model Representation is intended to be a container to exchange software artifacts in binary form. Such binaries can be directly integrated with other embedded software running on an ECU. The main purpose of this format is the protection of intellectual property. Shareholders can exchange a software solution without revealing crucial implementation or algorithm details to the user of a particular solution. Beside the protection of intellectual property, the Binary Code Model Representation also provides protection of integrity of the solution. The software solution cannot be altered except for the intended interface such as calibration parameters. Furthermore the binary representation unitizes separate functionalities into dedicated binary files. These binary files can be used independently in different contexts.

An eFMU container might consist of multiple Binary Model Representations which may originate from the same Production Code Model Represention.

BinCode Container
Figure 1. Structure of Binary Model Represention

A Binary Code Model Representation consists at least of the following items:

  • Object files or static libraries in Executable and Linking Format (ELF) for the use for embedded devices or dynamic linked libraries for co-simulation purposes in Windows environments

  • Container manifest

Furthermore, it might include a file containing information necessary for calibration, measurement and diagnosis purposes and a linker script that contains the necessary information in order to link the software for a particular target environment.

7.1. Manifest

Since a binary container is subject to an integration on a particular target ECU, its manifest has to provide any necessary information about

  • the components interface,

  • the compiler and its configuration,

  • the linker and its configuration,

  • the target

Optionally, there might exists

  • information about the run time behavior

  • meta information regarding the source code (e.g. [MISRA C:2025] compliance, code quality reports, etc.)

  • Calibration

The Binary Code manifest is an XML file with structured information about the Binary Model Representation.

Note Some of the above points are already available in the Production Code Model Representation. Such information (interface, [MISRA C:2025] compliance) will be referenced by the Binary Code manifest from the Production Code manifest.

7.1.1. Structure of the Manifest

The Binary Code manifest:

ManifestMainLevel

consists of the following elements:

On the top level, the schema consists of the following elements:

Name Description

attributes

The attributes of the top-level element are the same for all manifest kinds and are defined in section Section 2.3.1.
Current kind-specific values: kind = "BinaryCode", xsdVersion (value is the current xsd version of the schema for the Binary Code model manifest).

ManifestReferences

Reference to the manifest of the Production Code on which this Binary Code manifest is based on. This element is the same for all manifest kinds and is defined in section Section 2.3.4.3.

Files

List of files referenced in this model representation. This element is the same for all manifest kinds and is defined in section Section 2.3.3.

BinaryContainer

Defines the essential content of the actual container. For details see Section 7.1.2.

Annotations

Additional data that a vendor might want to store and that other vendors might ignore. For details see Section 2.3.4.5.

The following subsections focus on the BinaryContainer element which represents the actual Binary Model Representation.

7.1.2. Binary Container

Element BinaryContainer

BinaryContainer

consists of the following elements:

Name Description

BuildConfiguration

The BuildConfiguration describes the actual build environment used to create the binary objects in the container. For more details see Section 7.1.2.1.

Modules

The Modules section describes all relevant binaries and source code references required or available for the binary model representation container. For more details see Section 7.1.3.

BinaryContainerInfo

The BinaryContainerInfo element contains additional and optional information relevant to the end user. For more details see Section 7.1.4.

Each of the above listed elements has to exist exactly once in a BinaryContainer. Additionally, the the BinaryContainer has the following Attributes:

Name Description

toolVersion

This attribute is used by the the generating tool to store its Name and Version.

BuildConfiguration

Element BuildConfiguration consists of all information related to the compilation and linking of the model representation:

BuildConfiguration

This element contains exactly one of each of the following elements:

Name Description

Compiler

This element unambigously describes the compiler that has been used to create the binary artifacts. For details see Section 7.1.2.2.

Linker

This element unambigously describes the linker that has been used to create the binary artifacts. For details see Section 7.1.2.3.

CompilerOptionSets

This element stores all possible compiler settings used to create any binary element in the container. For details see Section 7.1.2.4.

DefaultCompilerOptions

This element refers to a CompilerOptionSet that has to be used to create the binary. For details see Section 7.1.2.5.

LinkerOptionSet

This element describes the relevant linker option for the above linker that has been used to create the binary object. For details see Section 7.1.2.6.

CompileTarget

This element describes the target environment, the binary has been compiled for. For details see Section 7.1.2.7.

Note It is possible that a Binary Code Model Representation needs to be combined with some source from the Simulation Code, Tool-specific code of the Production Code model or even from external generators in order to analyze, integrate or test the model. In such cases additional sources need to be compiled and linked together. To support such a use case, the BuildConfiguration of a Binary Model Representation needs to provide all required information to be able to compile and link additional sources with the binary artifacts.
Compiler

In order to integrate the object code, it is required to have all relevant information about the compile process of a binary specified. Hence, the compiler is to be specified in the manifest as follows:

Compiler

All attributes are mandatory and are defined as follows:

Name Description

id

A unique id that has to be referenced by any corresponding CompilerOptionSet.

vendor

The name of the Company/Vendor that has created or issued the compiler.

name

A unique, unambiguous name of the compiler or compiler suite.

version

The specific version of the above compiler that has been used to create the binary.

executableName

The name of the actual executable of the compiler (suite).

The attributes vendor, name and version must clearly identify a particular compiler. Furthermore, it should be possible to use the value executableName together with a matching CompilerOptionSet to automatically compile a source file.

Note The following example depicts a compiler configuration for a target compiler for the TriCore processor archtecture.
1
2
<Compiler id="ID_1000001" vendor="Altium"
          name="TASKING VX-toolset for TriCore: C compiler"  version="v4.2r2" executableName="ctc"/>
Linker

Similar to the definition of the compiler infrastructure and options, the linker and link options have to be declared to be known to the integration engineer.

Linker

All attributes are mandatory and defined as follows:

Name Description

vendor

The name of the Company/Vendor that have created or issued the linker.

name

Unique, unambiguous name of the linker .

version

The specific version of the above linker that have been used to create the binary.

executableName

The name of the actual executable of the linker (suite).

The attributes vendor, name and version must clearly identify a particular linker. Furthermore, it should be possible to use the value executableName together with the below defined LinkerOptionSet to automatically link object files together.

Note The following example depicts an linker configuration for the TriCore processor architecture.
1
<Linker id="ID_1000002" vendor="Altium" name="TASKING VX-toolset for TriCore: object linker" version="v4.2r2" executableName="ltc"/>
CompilerOptionSets

The CompilerOptionSets contains one or more CompilerOptionSet which defines settings and switches used to create at least one of the contained binary artifacts.

CompilerOptionSets
Name Description

id

The unique identifier of the the CompilerOptionSet within the manifest.

compilerRefId

A reference to a configured compiler for the Compilers Section.

CompilerOptions

List of compiler options for Production or Binary Code, see [CompilerOptions]

The CompilerOptions list is defined as:

CompilerOptions
Name Description

compileRoot

Directory where compilation should be performed.

CompilerSwitch

The compiler switches of type [CompilerOptionType].

PreprocessorDefinition

Preprocessor definitions of type [CompilerOptionType].

AdditionalIncludeDirectory

Additional include directory of type [CompilerOptionType].

CompilerOptionReference

A list of option references, see [CompilerOptionReference].

The CompilerOptionType attributes are defined as:

CompilerOptionType
Name Description

index

Index of the compiler option in the list of options (first compiler option = 1, second compiler option = 2, etc). The indices of the choice elements of each 'CompilerOptions' must be consecutive, unique and one element must have index 1.

id

Unique id of compiler option.

name

Name of option.

value

Optional value of option.

description

Optional description of option.

optional

Optional Boolean with default false, defining whether the option is optional.

The CompilerOptionReference list is defined as:

CompilerOptionReference
Name Description

index

Index of the compiler option in the list of options (first compiler option = 1, second compiler option = 2, etc). The indices of the choice elements of each 'CompilerOptions' must be consecutive, unique and one element must have index 1.

id

Unique id of option reference.

ForeignOptionReference

Reference to another manifest file of type ForeignReference. For details see Section 2.3.4.3.

Note The following example depicts some of the options that have to be provided in order to compile code for the Infineon Tricore TC27x family. Most options are special to this compiler family.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<CompilerOptionSets>
  <CompilerOptionSet id="ID_1001" compilerRefId="ID_1000001">
    <CompilerOptions>
      <CompilerSwitch>
        <id>ID_100010</id>
        <name>--iso</name>
        <value>90</value>
      </CompilerSwitch>
      <CompilerSwitch>
        <id>ID_100011</id>
        <name>--align</name>
        <value>4</value>
      </CompilerSwitch>
      <CompilerSwitch>
        <id>ID_100012</id>
        <name>--optimize</name>
        <value>3</value>
      </CompilerSwitch>
      <CompilerSwitch>
        <id>ID_100013</id>
        <name>--tradeoff</name>
        <value>4</value>
      </CompilerSwitch>
      <CompilerSwitch>
        <id>ID_100014</id>
        <name>--source</name>
      </CompilerSwitch>
      <CompilerSwitch>
        <id>ID_100015</id>
        <name>--error-file</name>
      </CompilerSwitch>
      <CompilerSwitch>
        <id>ID_100016</id>
        <name>--rename-sections=sect</name>
      </CompilerSwitch>
      <CompilerSwitch>
        <id>ID_100017</id>
        <name>--core</name>
        <value>tc1.6.x>
      </CompilerSwitch>
      <CompilerSwitch>
        <id>ID_100018</id>
        <name>-Hsfr/regtc27x.sfr</name>
      </CompilerSwitch>
      <CompilerSwitch>
        <id>ID_100019</id>
        <name>--default-near-size</name>
        <value>0</value>
      </CompilerSwitch>
<CompilerOptionSets>
Default Compiler Options

While each module might have its own compiler options referenced from the CompilerOptionsSets of the BinaryContainer, a default option set for the container can be defined. The default compiler options are used in any case where no other CompilerOptionsSet is provided.

The DefaultCompilerOptions are specified as follows:

DefaultCompilerOptions
Name Description

compilerOptionsRefId

Reference to a previously defined CompilerOptionSet to be used as default.

Note The following example depicts an default option set that refers to the CompilerOptionSet defined in the parent BinaryContainer element.
1
<DefaultCompilerOptions compilerOptionsRefId="ID_1001" />
LinkerOptionSet

The LinkerOptionSet contains one LinkerOptions which defines linker settings and switches.

LinkerOptionSet
Name Description

LinkerOptions

List of linker options for Production or Binary Code, see [LinkerOptions]

FileReference

The linker script is referenced with a FileReference element.

The LinkerOptions list is defined as:

LinkerOptions
Name Description

LinkerSwitch

The linker switches of type [LinkerOptionType].

Library

Library of type [LinkerOptionType].

AdditionalLibraryDirectory

Additional library directory of type [LinkerOptionType].

LinkerOptionReference

A list of option references, see [LinkerOptionReference].

The LinkerOptionType attributes are defined as:

LinkerOptionType
Name Description

index

Index of the option in the linker command line.

id

Unique id of linker option.

name

Name of option.

value

Optional value of option.

description

Optional description of option.

optional

Optional Boolean with default false, defining whether the option is optional.

The LinkerOptionReference list is defined as:

LinkerOptionReference
Name Description

index

Index of the option in the linker command line.

id

Unique id of option reference.

ForeignOptionReference

Reference to another manifest file of type ForeignReference. For details see Section 2.3.4.3.

Note The following example depicts some of the options that have to be provided in order to compile code for the Infineon Tricore TC27x family. Most options are special to this linker family.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<LinkerOptionSet>
  <LinkerOptions>
    <LinkerSwitch>
      <id>ID_100010</id>
      <name>output</name>
      <value>dummy.elf:ELF</value>
    </LinkerSwitch>
    <LinkerSwitch>
      <id>ID_100011</id>
      <name>no-warnings</name>
    </LinkerSwitch>
    <LinkerSwitch>
      <id>ID_100012</id>
      <name>incremental</name>
    </LinkerSwitch>
    <LinkerSwitch>
      <id>ID_100013</id>
      <name>lsl-file</name>
      <value>TC277.lsl</value>
    </LinkerSwitch>
    <LinkerSwitch>
      <id>ID_100014</id>
      <name>map-file</name>
      <value>mapfile.map</value>
    </LinkerSwitch>
  <LinkerOptions>
  <FileReference fileRefId="ID_999915" kind="LinkerScript" />
</LinkerOptionSet>
Target

In order to decide whether a target ECU is (technically) suitable for a particular binary with respect to target optimization and assumptions done during Production Code generation regarding hardware, the manifest has to specify the following items:

CompileTarget

To define the target ECU the binary representation is compiled for, this section defines the following attributes:

Name Description

vendor

The manufacturer of the the target environment processor.

targetName

The name of the architecture.

chipVersion

The exact version of processor used in the architecture.

instructionSetArchitecture

A unique identifier for the instruction set used by the chip.

endianess

Describes whether the target uses Little-Endian (little) or Big-Endian (big) byte order.

registerWidth

Declares the bit width of the registers of the chip.

addressWidth

Declares the bit width of a memory address in the target.

Note The following example depicts the target information needed for a TC277 Processor within a TriCore embedded target.
1
<CompileTarget vendor="Infineon" targetName="TriCore" chipVersion="TC277 C-Step" instructionSetArchitecture="TC1.6E" endianess="little" registerWidth="32" addressWidth="32"/>

7.1.3. Modules

The Modules section lists and describes all relevant binaries contained in the Binary Model Representation. Furthermore, it lists all source code references to the Production Code container that are provided with the binary files.

The Modules section consist of a list of one or more BinaryModule items.

Modules
ModulesFileReference
ModulesSourceFileReference

A BinaryModule describes a binary object in the Binary Code Model Representation. It has the following attributes:

Name Description

id

A unique identifier for further referencing.

creator

The creating tool or person.

creationDate

The date, the particular binary moduel has been created.

compilerOptionSetRefId

A reference to the CompilerOptionSet used for generation of the object file.

A BinaryModule contains one ObjectFile element and zero or more SourceFileReference:

Name Description

ObjectFile

The actual binary object in the container. There can be only one object file per Binary module.

SourceFileReference

Each element refers to a code file in production Code manifest.

Note SourceFileReference elements refer to possibly required CodeFile elements from the Production Code Model. Those files are not part of the object file but might be necessary for further processing steps, e.g., a PiL simulation of th object file.

The SourceFileReference element has the following attributes:

Name Description

id

A unique identifier for further referencing.

fileRefId

Reference to the code Files in the Production Code manifest via a ForeignFile reference in the manifest Files section.

CompilerOptionSetId

If a CompilerOptionSetId is specified, it must be used for compiling this code artifact. Otherwise, the DefaultCompilerOptions must be used.

Each ObjectFile has the following attributes:

Name Description

id

A unique identifier for further referencing.

Additionally, it consists of the following elements:

Name Description

FileReference

Reference to the actual binary object file. The kind of the FileReference is either "RelocatableObjectFile" or "ExecutableObjectFile". This element is mandatory.

ForeignSourceFileReference

The ForeignSourceFileReference elements refer to CodeFile elements of the Production Code Model Representation which have been used to generate the binary object file. The presence of the actual source files in the Production code container is not required. The manifest information, however, needs to be available.

Note The following example shows a snippet for a very simple model. It consists of one non-executable object file that have been generated from two ("Production Code") source files.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<ForeignFile id="ID_999920">
  <ForeignReference foreignRefId="ID_9" manifestReferenceRefId="ID_0000001" />
</ForeignFile>
<ForeignFile id="ID_999921">
  <ForeignReference foreignRefId="ID_10" manifestReferenceRefId="ID_0000001" />
</ForeignFile>
<ForeignFile id="ID_999922">
  <ForeignReference foreignRefId="ID_5" manifestReferenceRefId="ID_0000001"/>
</ForeignFile>
<ForeignFile id="ID_999923">
  <ForeignReference foreignRefId="ID_1" manifestReferenceRefId="ID_0000001"  />
</ForeignFile>
<ForeignFile id="ID_999924">
  <ForeignReference foreignRefId="ID_3" manifestReferenceRefId="ID_0000001"  />
</ForeignFile>
[...]
<Modules>
  <BinaryModule id="ID_4" creator="JDoe" creationDate="2018-08-09">
	<ObjectFile id="ID_10">
	  <FileReference fileRefId="ID_01" kind="RelocatableObjectFile" />
	  <SourceFileReference id="ID_02" fileRefId="ID_999920" />
	  <SourceFileReference id="ID_03" fileRefId="ID_999921" />
	</ObjectFile>
	<SourceFileReference id="ID_5"fileRefId="ID_999922" />
	<SourceFileReference id="ID_1" compilerOptionSetRefId="ID_46" fileRefId="ID_999923" />
	<SourceFileReference id="ID_3" compilerOptionSetRefId="ID_46" fileRefId="ID_999924" />
  </BinaryModule>
</Modules>

7.1.4. Binary Container Info (optional)

The previously described elements of the manifest for the Binary Code Model Representation are mandatory. However, there is also information that might not be necessary to describe a binary but very helpful in the actual use cases for the Binary Code Model Representation such as integration or validation.

To store and provide this information, the manifest contains the BinaryContainerInfo section. A BinaryContainerInfo element might contain a description for each of the following topics

  • mapping information (memory, registers, etc.)

  • run time behavior

  • calibration information

  • measurement information

  • information about the diagnosis interface

The BinaryContainerInfo element is defined as follows:

BinaryContainerInfo

It contains the following elements:

Name Description

RunTimeComplianceInformation

Information regarding run time behavior of the different functions provided by the Binary Code model representation.

FileReference

In addition to the run time information, it is also possible to provide reference to files that give further information regarding the above mentioned topics. The kind of the FileReference indicates which topic is tackled.

Possible kinds are: MapFile, CalibrationInformationFile, MeasurementInformationFile, DiagnosisInformationFile, ValidationAndVerificationFile, ComplianceInformationFile, LicenseFile, ConfigurationFile.

Mapping Information

In order to provide the integration engineer with additional information about a binary file that has already has been linked, a map file can be specified in the MapFileReference element.

Note The following example shows, how a map file can be provided using the combination of the File element declared for the Manifest and the actual FileReference with the kind="MapFile".
1
2
3
4
5
6
<File id="ID_999913" path="/objects/" name="SpeedController.map" role="other" needsChecksum="true"
       checksum="A43C0994FAD1247988C2AA8A90CCA2E241CF5687" />
[...]
<BinaryContainerInfo>
  <FileReference fileRefId="ID_999913" kind="MapFile" />
</BinaryContainerInfo>
Note The map file can be used to easily inspect information about the memory mapping and, memory usage. Furthermore general information about estimated stack size and the overall link process can be provided here.
Run Time Behavior

In order to integrate a function defined in an eFMI into a binary for the target ECU, it is required to have information about the run time behavior to decide whether there are enough resources available in order to coexist with additional functions or tasks running on the same ECU.

Note This information might help the integration engineer to identify possible bottlenecks before he starts the actual integration.

Hence, the manifest can specify RunTimeComplianceInformation as additional, optional information.

If RunTimeComplianceInformation is provided, it can specify the run time behavior for one or more functions as follows:

RunTimeCompliance

It consists of one ForeignFunctionReference that refers to the function in the manifest of the Production Code model representation. The information about the run time behavior is described by the following attributes:

Name Description

id

A unique identifier for further referencing.

wcExecTime

The maximum time consumed by the function in the worst case.

wcStackSize

The maximum stack size required by the function in the worst cas.

wcMemSize

The maximum memory consumed by the function in the worst case.

Note that valid units have to be used for each attribute by the author.

Note The following example shows how the RunTimeComplianceInformation can be defined for some function.
1
2
3
4
5
6
7
<BinaryContainerInfo>
  <RunTimeComplianceInformation>
	<RunTimeCompliance id="ID_100301" wcExecTime="8.4ms" wcStackSize="70kb" wcMemSize="840kb">
	  <ForeignFunctionReference foreignRefId="ID_41" manifestReferenceRefId="ID_0000001" />
	</RunTimeCompliance>
  </RunTimeComplianceInformation>
</BinaryContainerInfo>
Calibration

In order to be able to calibrate the binary object provided by the Binary Code Model Representation with common, widely used calibration tools, the manifest might specify one or more files containing calibration information. Calibration information is given using FileReference elements with the kind="CalibrationInformationFile".

Note The following code snippet shows how a calibration file can be provided.
1
2
3
4
5
<File id="ID_999912" path="/" name="myFunction.a2l" role="other" checksum="0DC09613F414FFCE10865AF3AD3EC31D3ED61EA8" needsChecksum="true" />
[...]
<BinaryContainerInfo>
  <FileReference fileRefId="ID_999912" kind="CalibrationInformationFile" />
</BinaryContainerInfo>
Note An incomplete and optional A2L file provides the symbols used for calibration purposes. When the integrator performs the final linking, the memory addresses of all A2L files of the used software functions are updated. The resulting A2L files can be used by calibration tools to dynamically change parameters for example.
Measurement

In order to measure internal values of the controller software during the testing and validation phase, the manifest might specify one or more file containing measurement information. Measurement information is given using FileReference elements with the kind="MeasurmentInformationFile".

Note The following code snippet shows how a measurement information file can be provided. Note that in this example, in case of an A2L-File, the same file might be used for calibration and measurement.
1
2
3
4
5
<File id="ID_999912" path="/" name="myFunction.a2l" role="other" checksum="0DC09613F414FFCE10865AF3AD3EC31D3ED61EA8" needsChecksum="true" />
[...]
<BinaryContainerInfo>
  <FileReference fileRefId="ID_999912" kind="MeasurmentInformationFile" />
</BinaryContainerInfo>
Diagnosis

ECU software often provides some subroutines for diagnosis that is used for testing and maintenance. Hence, the manifest of a Binary Model representation can contain one or more files that provide information for diagnosis tools. Diagnosis information is given using FileReference elements with the kind="DiagnosisInformationFile".

Note The following code snippet shows how a diagnosis information file can be provided.
1
2
3
4
5
<File id="ID_999914" path="/" name="myFunction.cdd" role="other" checksum="E7A58CD816076EE26DE1D6BF2F13630000675FB2" needsChecksum="true" />
[...]
<BinaryContainerInfo>
  <FileReference fileRefId="ID_999914" kind="DiagnosisInformationFile" />
</BinaryContainerInfo>
Compliance

Since the main intention of the Binary Code container is the protection of intellectual property, the source code usually cannot be checked according to compliance to relevant standards. However, since this information might be of interest for the integrating company, an eFMI binary container shall have an optional section to define one or more files describing the components compliance. Diagnosis information is provided using FileReference elements with the kind="ComplianceInformationFile".

Note The following code snippet shows how a compliance information file can be provided.
1
2
3
4
5
<File id="ID_999910" path="/doc/" name="MISRA.doc" role="other" checksum="27D8D7BB69E1D7E98C7A278C5A48199CE7B65399" needsChecksum="true" />
[...]
<BinaryContainerInfo>
  <FileReference fileRefId="ID_999910" kind="ComplianceInformationFile" />
</BinaryContainerInfo>
Note A FileReference can also point to a ForeignFile element and, hence, to an arbitrary file in the eFMU container. This means it can also point to a compliance information file from Production Code container.
Note Note that the eFMI standard does not define how the integrity of the compliance information can be ensured. It is up to the software provider and the integrating company to ensure the validity and integrity of this compliance information.
License Information

In case that any third party licenses have to be shipped with the binary or to provide license information is provided using FileReference elements with the kind="LicenseFile".

Note The following code snippet shows how a licenese file can be provided.
1
2
3
4
5
<File id="ID_999911" path="/license/" name="BSD.TXT" role="other" checksum="A7549D084CFD2F9C6DEFA940B9BD5DA402B8341D" needsChecksum="true" />
[...]
<BinaryContainerInfo>
  <FileReference fileRefId="ID_999910" kind="LicenseFile" />
</BinaryContainerInfo>
Validation & Verification

For Verification and Validation, additional files can be provide using one or more FileReference elements with the kind="ValidationAndVerificationFile".

Note The following code snippet shows how some simulation results (e.g., ASAM MDF format) from a use case for back to back testing as well as some description of equivalence classes (e.g., properitary XML format) can be specified for th container.
1
2
3
4
5
6
<File id="ID_999920" path="/v_n_v/" name="scenario1.mdf" role="other" checksum="DB1A8489D88604A5C896BAB2B35631314B257036" needsChecksum="true" />
<File id="ID_999921" path="/v_n_v/" name="equivalenceclasses.xml" role="other" checksum="F61E2D36002DD140653334E4871DEBE6EE3B721A" needsChecksum="true" />
[...]
<BinaryContainerInfo>
  <FileReference fileRefId="ID_999910" kind="ValidationAndVerificationFile" />
</BinaryContainerInfo>
Configuration of Runtime

Certain binary files require additional information on runtime. The Binary Code container provides the possibility to link such information via FileReference elements with the kind="ConfigurationFile".

Note The following code snippet shows how a SOME/IP stack configuration for Adaptive AUTOSAR application is referenced.
1
2
3
4
5
<File id="ID_999910" path="/adaptive/" name="someip.json" role="other" checksum="DB1A8489D88604A5C896BAB2B35631314B257036" needsChecksum="true" />
[...]
<BinaryContainerInfo>
  <FileReference fileRefId="ID_999910" kind="ConfigurationFile" />
</BinaryContainerInfo>

7.2. Binary Format

The Binary Code Model Representation contains object files and libraries in binary format.

For deployment in a target environment the object file or library must be provided as a binary file according to [TIS ELF 1.2].

Note Hence, an ELF file should be target environment specific (e.g., for a specific ECU) and, optionally, may be executable. Executable ELF files will be used in PiL Simulation and can contain dedicated frame code. PiL-simulation tools may also create their own harness for PiL simulation. Non-executable ELF files (relocatable ELF) can be used for the integration in embedded target environments.

For Windows-based co-simulation a Binary Code Model Representation might also contain Windows-compatible object files or dynamic link libraries.

Note For the (co-)simulation use case the binary artifacts support multiple use cases. On the one hand, it may be a DLL, shared library or object file for general purpose code for a general purpose target environment (e.g., Windows or Linux) that can be used in a Software-in-the-Loop simulation.

Additionally, the Binary Code Model Representation can refer to the following Production Code Model Represention items:

  • Simulation Code that might be necessary/used for a standalone SiL or PiL simulation of the eFMU.

  • Tool specific code that might be required to use simulation features of a particular tool.

Note An example for the tool specific code might be a TargetLink S-Function frame used for a SiL Simulation or an TargetLink TSM-Frame used for PiL simulation. Another example migth be a minimal stub for debugging purposes on the target architecture.

Beside the actual binary format the Binary Code Model Representation might contain also files including information for calibration, measurement and diagnosis purposes.

Note An example format for the description of calibration, measurement and diagnosis is the ASAM A2L format. This might be an incomplete A2L since the absolute memory addresses will be updated after the final link process is completed.

An eFMI Binary Model Represention might make use of service functions which do not necessarily have to be contained in the binary files. Especially for the use case of ECU integration these service functions might be provided by the ECU environment.

Appendix A: Implementation of GALEC built-in functions

This appendix provides reference implementations for all GALEC built-in functions as defined in Section 3.11. Most can be realized in GALEC; only for the actual implementation of GALEC types in hardware, target environment specific characteristics are required like the ranges of Integer and Real. Such target environment dependent characteristics are expressed in natural language; respective pseudocode is wrapped between [[ and ]] and highlighted red. The provided implementations also leverage on the requirement of GALEC, that target environments must implement floating-point arithmetics according to [IEEE 754-2019] (cf. Chapter 3); places of particular interest where [IEEE 754-2019] is utilized to produce special values like not a number or check for such are marked with respective comments.

To use GALEC itself to define its built-in functions is "only" to clarify built-in function semantics as simple as possible, although completely and sound. To that end, we can leverage on GALEC error signaling, automatic limitation of ranged in- and outputs and the special error handling of relational operators like < and ==. The GALEC-based implementation very likely is inefficient however when used as such by a Production Code generator (assuming it allows to implement GALEC built-in functions as user-defined functions); a lower-than-GALEC-level language like [ISO/IEC 9899:2024] usually can provide much more efficient, although target environment specific, built-in function implementations.

The following reference implementation is split into four parts:

  • Part 1: Built-in functions that are target environment specific and therefore require pseudocode.

  • Part 2: Target environment independent built-in functions, except functions for integer division and remainder, and the multidimensional lifted versions of scalar argument functions defined in Part 4.

  • Part 3: Template based integer division and remainder built-in functions.

  • Part 4: Template based lifting of scalar arguments built-in functions to multidimensional versions.

The implementation source code distinguishes between integer and Integer. Integer with uppercase first letter is the type Integer — a target environment specific data-type — whereas integer with lowercase first letter is the mathematical term for numbers without fractional component. This distinction is for example of importance for the pseudocode regarding target environment specific type characteristics and conversions. Likewise, real and Real are distinguished.

Part 1: Target environment specific built-in functions

§1: Properties of Integer

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function minInteger
    output Integer i;
protected
algorithm
    i := [[ target environment specific smallest Integer ]];
end minInteger;

function maxInteger
    output Integer i;
protected
algorithm
    i := [[ target environment specific largest Integer ]];
end maxInteger;

§2: Properties of Real

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function minReal
    output Real r;
protected
algorithm
    r := [[ target environment specific smallest, not -∞ representing, Real ]];
end minReal;

function maxReal
    output Real r;
protected
algorithm
    r := [[ target environment specific largest, not +∞ representing, Real ]];
end maxReal;

function posMinReal
    output Real r;
protected
algorithm
    r := [[ target environment specific smallest Real > 0.0 ]];
end posMinReal;

function epsReal
    output Real r;
protected
algorithm
    r := [[ target environment specific smallest Real r > 0.0 such that 1.0 + r ≠ 1.0 ]];
end epsReal;

§3: Numeric type conversions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
function real
    signals OVERFLOW;
    input  Integer i;
    output Real r;
protected
algorithm
    r := (
        if [[ i < roundTowardZero(minReal()) ]] then
            minusInfinite() /* Triggers OVERFLOW signal in following test. */
        elseif [[ i > roundTowardZero(maxReal()) ]] then
            plusInfinite() /* Triggers OVERFLOW signal in following test. */
        else
            [[ target environment specific, according to IEEE 754-2019,
               nearest Real representation of i ]]);
    if [[ r is not an exact representation of i according to IEEE 754-2019 ]] then
        signal OVERFLOW;
    end if;
end real;

function integer
    signals NAN, OVERFLOW;
    input Real r;
    output Integer i;
protected
    Real r_rounded;
    Real i_min;
    Real i_max;
algorithm
    /*
        Check if Integer bounds are outside the range of Real (e.g., 16-bit floating-point
        precision Real and 32-bit Integer). If so, every finite truncated Real can be exactly,
        according to IEEE 754-2019, represented as Integer => use Real bounds in later range
        check and not Integer (the range check is still needed to capture ±∞ inputs):
    */
    i_min := (
        if isInfinite(real(minInteger())) then
            roundTowardZero(minReal())
        else
            real(minInteger()));
    i_max := (
        if isInfinite(real(maxInteger())) then
            roundTowardZero(maxReal())
        else
            real(maxInteger()));
    if signal in OVERFLOW /* by real() */ then
        /* It is of no importance if Integer bounds can be exactly represented as Real. */
    end if;

    i := 0;
    r_rounded := roundTowardZero(r); /* Returns qNaN if r is qNaN. */
    if /* Range check: */ (r_rounded < i_min) or (r_rounded > i_max) then
        signal OVERFLOW;
    elseif signal in NAN then
        signal NAN; /* r_rounded was qNaN. */
    else
        i := [[ target environment specific Integer representation of r_rounded ]];
    end if;
end integer;

§4: Direct Real rounding

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function roundDown
    input Real r;
    output Real r_rounded;
protected
algorithm
    r_rounded := (
        if isNan(r) then
            nan()
        else
            [[ target environment specific greatest integer ≤ r ]]);
end roundDown;

function roundUp
    input Real r;
    output Real r_rounded;
protected
algorithm
    r_rounded := (
        if isNan(r) then
            nan()
        else
            [[ target environment specific least integer ≥ r ]]);
end roundUp;

§5: Mathematical Real constants and functions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function euler
    output Real y;
protected
algorithm
    y := [[
        Target environment specific, most-precise representation of
        Euler's number ℯ. In IEEE 754-2019 quadruple-precision
        (256-bit), the decimal value is
            2.7182818284 5904523536 0287471352 6623143584
              2186719354 8862669230 8603276671 6801933881
              6975505324 0805864334 1064453125
        ]];
end euler;

§6: Trigonometric Real constants and functions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function pi
    output Real y;
protected
algorithm
    y := [[
        Target environment specific, most-precise representation of π.
        In IEEE 754-2019 quadruple-precision (256-bit), the
        decimal value is
            3.1415926535 8979323846 2643383279 5027974790
              6809813729 5573004504 3318742967 1866297553
              6062731407 5827598571 77734375
        ]];
end pi;

Part 2: Target environment independent built-in functions

§1: Properties of Real

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
function nan
    output Real r;
protected
algorithm
    /*
        r := [[ target environment specific quiet not a number representation ]];
        According to IEEE 754-2019:
    */
    r := 0.0 / 0.0;
end nan;

function isNan
    input  Real r;
    output Boolean b;
protected
algorithm
    /*
        b := [[ true if r is a target environment specific not a number representation, otherwise false ]];
        According to IEEE 754-2019:
    */
    b := r <> r;
    if signal in NAN then
    end if;
end isNan;

function minusInfinite
    output Real r;
protected
algorithm
    /*
        r := [[ target environment specific -∞ representation ]];
        According to IEEE 754-2019:
    */
    r := -1.0 / 0.0;
end minusInfinite;

function plusInfinite
    output Real r;
protected
algorithm
    /*
        r := [[ target environment specific +∞ representation ]];
        According to IEEE 754-2019:
    */
    r := -minusInfinite();
end plusInfinite;

function isInfinite
    input  Real r;
    output Boolean b;
protected
algorithm
    b := (r == minusInfinite()) or (r == plusInfinite());
    if signal in NAN then
        /* IEEE 754-2019: b is already false. */
    end if;
end isInfinite;

function isFinite
    input  Real r;
    output Boolean b;
protected
algorithm
    b := not(isNan(r)) and not(isInfinite(r));
end isFinite;

§2: Multidimensional properties of Real

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
function hasNan1D
    input  Real r[:];
    output Boolean b;
protected
algorithm
    b := false;
    for i in 1:size(r, 1) loop
        if isNan(r[i]) then
            b := true;
        end if;
    end for;
end hasNan1D;

function hasNan2D
    input  Real r[:, :];
    output Boolean b;
protected
algorithm
    b := false;
    for i in 1:size(r, 1) loop
        for j in 1:size(r, 2) loop
            if isNan(r[i, j]) then
                b := true;
            end if;
        end for;
    end for;
end hasNan2D;

function hasInfinite1D
    input  Real r[:];
    output Boolean b;
protected
algorithm
    b := false;
    for i in 1:size(r, 1) loop
        if isInfinite(r[i]) then
            b := true;
        end if;
    end for;
end hasInfinite1D;

function hasInfinite2D
    input  Real r[:, :];
    output Boolean b;
protected
algorithm
    b := false;
    for i in 1:size(r, 1) loop
        for j in 1:size(r, 2) loop
            if isInfinite(r[i, j]) then
                b := true;
            end if;
        end for;
    end for;
end hasInfinite2D;

function allFinite1D
    input  Real r[:];
    output Boolean b;
protected
algorithm
    b := true;
    for i in 1:size(r, 1) loop
        if isFinite(r[i]) then
            b := false;
        end if;
    end for;
end allFinite1D;

function allFinite2D
    input  Real r[:, :];
    output Boolean b;
protected
algorithm
    b := true;
    for i in 1:size(r, 1) loop
        for j in 1:size(r, 2) loop
            if isFinite(r[i, j]) then
                b := false;
            end if;
        end for;
    end for;
end allFinite2D;

§3: Direct Real rounding

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
function roundTowardZero
    input  Real r;
    output Real r_rounded;
protected
algorithm
    r_rounded := (if r >= 0.0 then roundDown(r) else roundUp(r));
    if signal in NAN then
        /* Already handled: roundUp(r) ===> qNaN */
    end if;
end roundTowardZero;

function roundAwayZero
    input  Real r;
    output Real r_rounded;
protected
algorithm
    r_rounded := (if r <= 0.0 then roundDown(r) else roundUp(r));
    if signal in NAN then
        /* Already handled: roundUp(r) ===> qNaN */
    end if;
end roundAwayZero;

§4: Nearest Real rounding (using a tie-breaking rule)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
function roundHalfDown
    input  Real r;
    output Real r_rounded;
protected
algorithm
    r_rounded := roundUp(r - 5.0e-1);
end roundHalfDown;

function roundHalfUp
    input  Real r;
    output Real r_rounded;
protected
algorithm
    r_rounded := roundDown(r + 5.0e-1);
end roundHalfUp;

function roundHalfTowardZero
    input  Real r;
    output Real r_rounded;
protected
algorithm
    r_rounded := roundAwayZero(r - sign(r) * 5.0e-1);
end roundHalfTowardZero;

function roundHalfAwayZero
    input  Real r;
    output Real r_rounded;
protected
algorithm
    r_rounded := roundTowardZero(r + sign(r) * 5.0e-1);
end roundHalfAwayZero;

function roundHalfToEven
    input Real r;
    output Real r_rounded;
protected
    Real half_down;
    Real half_up;
algorithm
    half_down = roundHalfDown(r);
    half_up = roundHalfUp(r);
    r_rounded := (
        if half_down <> half_up then
            (if roundTowardZero(r - 2.0 * roundDown(r / 2.0)) == 0.0
                then half_down
                else half_up)
        else half_down);
    if signal in NAN then
        /* Already handled: roundHalfDown(r) ===> qNaN */
    end if;
end roundHalfToEven;

function roundHalfToOdd
    input  Real r;
    output Real r_rounded;
protected
    Real half_down;
    Real half_up;
algorithm
    half_down = roundHalfDown(r);
    half_up = roundHalfUp(r);
    r_rounded := (
        if half_down <> half_up then
            (if roundTowardZero(r - 2.0 * roundDown(r / 2.0)) == 0.0
                then half_up
                else half_down)
        else half_down);
    if signal in NAN then
        /* Already handled: roundHalfDown(r) ===> qNaN */
    end if;
end roundHalfToOdd;

§5: Multidimensional Boolean functions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
function anyTrue1D
  input Boolean v[:];
  output Boolean b;
protected
algorithm
  b := false;
  for i in 1 : size(v, 1) loop
    b := b or v[i];
  end for;
end anyTrue2D;

function anyTrue2D
  input Boolean m[:, :];
  output Boolean b;
protected
algorithm
  b := false;
  for i in 1 : size(m, 1) loop
    for j in 1 : size(m, 2) loop
      b := b or m[i, j];
    end for;
  end for;
end anyTrue2D;

function allTrue1D
  input Boolean v[:];
  output Boolean b;
protected
algorithm
  b := true;
  for i in 1 : size(v, 1) loop
    b := b and v[i];
  end for;
end allTrue1D;

function allTrue2D
  input Boolean m[:, :];
  output Boolean b;
protected
algorithm
  b := true;
  for i in 1 : size(m, 1) loop
    for j in 1 : size(m, 2) loop
      b := b and m[i, j];
    end for;
  end for;
end allTrue2D;

§6: Relational Integer functions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function imin
    input  Integer x1;
    input  Integer x2;
    output Integer y;
protected
algorithm
    y := (if x1 < x2 then x1 else x2);
end imin;

function imax
    input  Integer x1;
    input  Integer x2;
    output Integer y;
protected
algorithm
    y := (if x1 > x2 then x1 else x2);
end imax;

§7: Relational Real functions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function rmin
    input  Real x1;
    input  Real x2;
    output Real y;
protected
algorithm
    y := (if x1 < x2 then x1 else x2);
    if signal in NAN then
        y := nan();
    end if;
end min;

function rmax
    input  Real x1;
    input  Real x2;
    output Real y;
protected
algorithm
    y := (if x1 > x2 then x1 else x2);
    if signal in NAN then
        y := nan();
    end if;
end max;

§8: Mathematical Real constants and functions

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
function fractionalPart
    input  Real x;
    output Real y;
protected
algorithm
    y := (if isInfinite(x) then 0.0 else x - roundTowardZero(x));
end fractionalPart;

function sign
    input  Real x;
    output Real y;
protected
algorithm
    y := (if r > 0.0 then 1.0 elseif r < 0.0 then -1.0 else 0.0);
    if signal in NAN then
        y := nan();
    end if;
end sign;

function absolute
    input  Real x;
    output Real y;
protected
algorithm
    y := sign(x) * x;
end absolute;

function sqrt
    input  Real x;
    output Real y;
protected
algorithm
	/* ^ operator already handles x < 0, +∞ and qNaN: */
    y := x^5.0e-1;
end sqrt;

function exp
    input  Real x;
    output Real y;
protected
algorithm
    /* ^ operator already handles ±∞ and qNaN: */
    y := euler()^x;
end exp;

function ln
    input  Real x;
    output Real y;
protected
algorithm
    y := (
        if isNan(x) or x < 0.0 then
            nan()
        elseif x == 0.0 then
            minusInfinite()
        elseif x == 1.0 then
            0.0
        elseif x == plusInfinite() then
            plusInfinite()
        else
            [[ logarithm of x to base euler() ]]);
    if signal in NAN then
        /* Not possible because of explicit isNan() check. */
    end if;
end ln;

function lg
    input  Real x;
    output Real y;
protected
algorithm
    y := (
        if isNan(x) or x < 0.0 then
            nan()
        elseif x == 0.0 then
            minusInfinite()
        elseif x == 1.0 then
            0.0
        elseif x == plusInfinite() then
            plusInfinite()
        else
            [[ logarithm of x to base 1.0e+1 ]]);
    if signal in NAN then
        /* Not possible because of explicit isNan() check. */
    end if;
end lg;

function divisionSafe
    signals INVALID_ARGUMENT;
    input Real dividend;
    input Real divisor;
    input Real epsilon
        (min = posMinReal());
    output Real quotient;
protected
algorithm
    quotient := dividend / (if divisor < epsilon then epsilon else divisor);
    if divisor < -epsilon then
        signal INVALID_ARGUMENT;
    end if;
    if signal in NAN then
        quotient := nan();
    end if;
end divisionSafe;

function sqrtSafe
    input Real x
        (min = 0.0);
    output Real y;
protected
algorithm
    y := sqrt(x);
end sqrtSafe;

function lnSafe
    input Real x
        (min = 0.0);
    output Real y;
protected
algorithm
    y := ln(x);
end lnSafe;

function lgSafe
    input Real x
        (min = 0.0);
    output Real y;
protected
algorithm
    y := lg(x);
end lgSafe;

§9: Trigonometric Real constants and functions

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
function sin
    input Real x;
    output Real y;
protected
algorithm
    y := (if isFinite(x) then [[ sine of x ]] else nan());
end sin;

function cos
    input Real x;
    output Real y;
protected
algorithm
    y := (if isFinite(x) then [[ cosine of x ]] else nan());
end cos;

function tan
    input Real x;
    output Real y;
protected
algorithm
    y := sin(x) / cos(x);
    if isInfinite(y) then
        y := nan();
    end if;
end tan;

function asin
    input  Real x;
    output Real y;
protected
algorithm
    y := (
        if (-1.0 <= x) and (x <= 1.0) then
            [[ inverse of sin(x) in the range -π/2 ≤ y ≤ π/2 ]]
        else
            nan());
    if signal in NAN then
        /* Already handled by else branch. */
    end if;
end asin;

function acos
    input  Real x;
    output Real y;
protected
algorithm
    y := (
        if (-1.0 <= x) and (x <= 1.0) then
            [[ inverse of cos(x) in the range 0 ≤ y ≤ π ]]
        else
            nan());
    if signal in NAN then
        /* Already handled by else branch. */
    end if;
end asin;

function atan
    input Real x;
    output Real y;
protected
algorithm
    y := (
        if isNan(x) then
            nan()
        elseif isInfinite(x) then
            sign(x) * (pi() / 2.0)
        else
            [[ inverse of tan(x) in the range -π/2 < y < π/2 ]]);
end atan;

function atan2
    input  Real y;
    input  Real x;
    output Real z;
protected
algorithm
    z := (
        /*
            Error cases. In opposite to IEEE 754-2019, we do
            not support y = ±0 when x ≤ ±0, since we cannot
            distinguish -0.0 from +0.0 in GALEC to do a
            limit analysis:
        */
        if isNan(x) or isNan(y) or (y == 0.0 and x <= 0.0) then
            nan()
        /*
            IEEE 754-2019 extreme cases (y = 0 and ±∞ arguments):
        */
        elseif y == 0.0 /* and x > 0.0 */ then
            0.0
        elseif isInfinite(y) then
            sign(y) * (
                if x == minusInfinite() then
                    (3.0 * pi()) / 4.0
                elseif x == plusInfinite() then
                    pi() / 4.0
                else /* isFinite(x) */
                    pi() / 2.0)
        elseif x == minusInfinite() /* and y <> 0.0 */ then
            sign(y) * pi()
        elseif x == plusInfinite() then
            0.0
        /*
            Mathematically well-defined non-limit standard cases:
        */
        elseif x == 0.0 /* and y <> 0.0 */ then
            sign(y) * (pi() / 2.0)
        elseif x < 0.0 /* and y <> 0.0 */ then
            atan(y / x) + (sign(y) * pi())
        else /* x > 0.0 */
            atan(y / x));
    if signal in NAN then
        /* Not possible because of explicit isNan() checks. */
    end if;
end atan2;

function sinh
    input Real x;
    output Real y;
protected
algorithm
    y := ((euler()^x) - (euler()^-x)) / 2.0;
end sinh;

function cosh
    input Real x;
    output Real y;
protected
algorithm
    y := ((euler()^x) + (euler()^-x)) / 2.0;
end cosh;

function tanh
    input Real x;
    output Real y;
protected
algorithm
    y := (if isInfinite(x) then sign(x) else sinh(x) / cosh(x));
end tanh;

function tanSafe
    input Real x;
    output Real y;
protected
algorithm
    y := (
        if x <= (pi() / -2.0) then
            minusInfinite()
        elseif x >= (pi() / 2.0) then
            plusInfinite()
        else
            tan(x));
    if signal in NAN then
        /* Already handled by else branch. */
    end if;
end tanSafe;

function asinSafe
    input Real x(
          min = -1.0
        , max = 1.0);
    output Real y;
protected
algorithm
    y := asin(x);
end asinSafe;

function acosSafe
    input Real x(
          min = -1.0
        , max = 1.0);
    output Real y;
protected
algorithm
    y := acos(x);
end acosSafe;

§10: Systems of equations

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function solveUnivariatePolynomial
    input Real a[:];
    input Real x;
    output Real b;
protected
algorithm
    /* Horner's method with a[1] coefficient of highest power: */
    b := a[1];
    for i in 2:size(a, 1) loop
        b := a[i] + b * x;
    end for;
end solveUnivariatePolynomial;

Part 3: Scalar argument Integer division and remainder built-in functions

Integer division and remainder built-in functions are defined with respect to the various rounding schemes that can be used for the quotient of the division. For every function named roundα of Part 1-2, with α an arbitrary sequence of characters, the respective division and remainder built-in functions are defined in §1 and §2 respectively (for example, for α = Down the divisionDown built-in function is defined based on roundDown, for α = TowardZero the divisionTowardZero built-in function is defined based on roundTowardZero, etc).

The implementation assumes that all Integer values ever encountered throughout the execution of any division or remainder built-in functions can be, according to [IEEE 754-2019], exactly represented as Real, i.e., the real() built-in function never signals OVERFLOW such that the implementation can fallback on the Real-based rounding functions; otherwise, dedicated Integer rounding functions or a higher floating-point precision should be used to avoid significant loss of precision, which otherwise eventually causes a remainder built-in function call to fail its ((quotient * divisor) + remainder) <> dividend sanity check and signal OVERFLOW. For example, in case of 32-bit signed integers in two’s complement representation, not every integer can be exactly represented as 32-bit [IEEE 754-2019] floating-point value; at least 64-bit floating-point precision is required.

§1: Rounded Integer division

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function divisionα
    signals NAN,
            OVERFLOW;
    input Integer dividend;
    input Integer divisor;
    output Integer quotient;
protected
algorithm
    /* Assuming real() never signals OVERFLOW: */
    quotient := integer(roundα(real(dividend) / real(divisor)));
end divisionα;

§2: Remainder of rounded Integer division

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
function remainderα
    signals NAN,
            OVERFLOW;
    input Integer dividend;
    input Integer divisor;
    output Integer remainder;
protected
    Integer quotient;
algorithm
    quotient := divisionα(dividend, divisor);
    remainder := dividend - (quotient * divisor);
    if signal s then
        signal s;
        remainder := dividend;
    elseif ((quotient * divisor) + remainder) <> dividend then
        signal OVERFLOW;
        remainder := dividend;
    end if;
end remainderα;

Part 4: Lifting of scalar argument built-in functions to multidimensional versions

For every built-in function named α, which is lifted to 1D and/or 2D according to §2 of Section 3.11, the lifted built-in functions α1D and/or α2D are defined in §1 and §2 respectively. In the given definitions, ω1,…​,ωm are the errors signaled by α, and τ1,…​,τn and τn1,…​,τnn are the types of its in- and outputs, θ1,…​,θn and θn1,…​,θnn are their ranges, and ξ1,…​,ξn and ξn1,…​,ξnn their names.

§1: Lift to 1D

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function α1D
    signals ω1, ..., ωm;
    input τ1 ξ1[size(ξn1, 1)] θ1;
    ...
    input τn ξn[size(ξn1, 1)] θn;
    output τn1 ξn1[:] θn1;
    ...
    output τnn ξnn[size(ξn1, 1)] θnn;
protected
algorithm
    for index1D in 1:size(ξn1, 1) loop
        (ξn1[index1D], ..., ξnn[index1D]) := α(ξ1[index1D], ..., ξn[index1D]);
    end for;
end α1D;

§2: Lift to 2D

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function α2D
    signals ω1, ..., ωm;
    input τ1 ξ1[size(ξn1, 1), size(ξn1, 2)] θ1;
    ...
    input τn ξn[size(ξn1, 1), size(ξn1, 2)] θn;
    output τn1 ξn1[:, :] θn1;
    ...
    output τnn ξnn[size(ξn1, 1), size(ξn1, 2)] θnn;
protected
algorithm
    for index1D in 1:size(ξn1, 1) loop
        for index2D in 1:size(ξn1, 2) loop
            (ξn1[index1D, index2D], ..., ξnn[index1D, index2D]) :=
                α(ξ1[index1D, index2D], ..., ξn[index1D, index2D]);
        end for;
    end for;
end α2D;

The eFMI Standard consists of (1) the actual specification text and (2) accompanying software artifacts the specification text refers to and leverages on for defining how valid eFMUs must look like and what their meaning is (the XML Schema Definitions (XSD) for the manifests of eFMUs); both are copyrighted by the Modelica Association:

Modelica Association logo 403x192 150dpi

© 2021-2026, Modelica Association and contributors.

Licensing

The specification text of the eFMI Standard, except Appendix A, is released under Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license:

CC BY SA 4.0 logo 403x141 300dpi

This work is licensed under a CC BY-SA 4.0 license.

The XML Schema Definitions and Appendix A of the eFMI Standard are released under 3-Clause BSD License:

BSD 225x105 72dpi

Registered trademarks

Modelica® is a registered trademark of the Modelica Association.

eFMI® is a registered trademark of the Modelica Association.

FMI® is a registered trademark of the Modelica Association.

Third party marks and brands are the property of their respective holders.

Colophon

This document has been typeset in AsciiDoc® using Asciidoctor and Asciidoctor PDF to generate HyperText Markup Language and Portable Document Format (ISO 32000-2:2020) distributions. AsciiDoc® is licensed under Eclipse Public License 2.0, and Asciidoctor and Asciidoctor PDF are licensed under MIT License.

AsciiDoc 1758x436
logo asciidoctor color

The source code listenings are typeset using the Python syntax highlighter Pygmnents, licensed under 2-Clause BSD License.

Pygments 1265x284

The Portable Document Format distribution of this document uses the Sans and Mono font of the Kurinto Font Folio licensed under SIL Open Font License (OFL) version 1.1.

KurintoSpecimenFolio Tall 250x281
OFL logo rect color

The XML Schema Definition (XSD) figures are taken with ALTOVA® XMLSpy® Professional Edition version 2025 rel. 2, a commercially licensed, proprietary tool.

ALTOVA XMLSpy 312x151

Disclaimer

The eFMI Standard is the result of countless hours of dedicated human creativity and work; no artificial intelligence contributed to its creation — neither for its design, nor writing the actual specification, nor editorial work, nor any other form of authorship.

This release is a candidate-draft for the eFMI Standard 1.0.0 (the first stable version of the eFMI Standard); its version is eFMI Standard 1.0.0 Beta 2. It succeeds the eFMI Standard 1.0.0 Beta 1 candidate-draft. Releases — including candidate-drafts — provide no guarantees or implications (neither extent, nor features, nor structure, nor wording, etc) regarding any past or future eFMI Standard release, whether final or candidate-draft.

The eFMI Standard is subject to a disclaimer of warranties and limitation of liability according to its licenses (cf. Licensing Section above).

Appendix C: Normative references

The eFMI Standard utilizes other international standards, typically released by third party standardization bodies independent of the Modelica Association. The referenced standards are listed below, following the template “Publisher (Date). Title. Revision. Additional normative references.”, whereas “Publisher” is the official name of the standardization body, “Date” is the publication date in the format “YYYY-MM” (year-month), “Title” is the official title (typically a standard defines a series with many revisions, whereas all revisions share a common title), and “Revision” is the actual version or reference number of the standard if not already part of its title (if part of the title, “Revision” is left out).

“Additional normative references” are optional cross-references to further amendments, errata, or other historically-relevant related documents. It follows a strict scheme defining if the cross-referenced document is mandatory (i.e., whenever the respective standard is referenced throughout the eFMI Standard, the standard and the listed cross-reference must be satisfied) or just relevant for historic classification (e.g., if the standard is the revision of a series whose title or standardization body changed, or if there are later revisions deliberately not required whenever the respective standard is referenced). Mandatory documents are introduced with “Including”; notes about previous revisions are introduced with “Revision of”; notes about deliberately skipped later revisions are introduced with “Revised by”.

Binary and character encodings, and file formats

  • [IEEE 754-2019] Institute of Electrical and Electronics Engineers (2019-07). IEEE Standard for Floating-Point Arithmetic. IEEE 754-2019.

  • [TIS ELF 1.2] Tool Interface Standard Committee (1995-05). Tool Interface Standard (TIS) Executable and Linking Format (ELF) Specification. Version 1.2. Revised by Chapters 4 and 5 of SYSTEM V APPLICATION BINARY INTERFACE — Edition 4.1 (1997-03), revised by ELF Object File Format — Version 4.2 (2025-01).

  • [FIPS PUB 180-4] National Institute of Standards and Technology, Federal Information Processing Standards (2015-08). Secure Hash Standard. FIPS PUB 180-4.

  • [INCITS 4-1986[R2022]] InterNational Committee for Information Technology Standards (2022-09). INCITS 4-1986[R2022]: Information Systems — Coded Character Sets — 7-Bit American National Standard Code for Information Interchange (7-Bit ASCII). Revision of ANSI X3.4-1986 (US-ASCII).

  • [ISO/IEC 10646:2020] International Organization for Standardization, International Electrotechnical Commission (2020-12). ISO/IEC 10646: Information technology — Universal coded character set (UCS). ISO/IEC 10646:2020(E). Including amendments ISO/IEC 10646:2020/Amd 1:2023(E) and ISO/IEC 10646:2020/Amd 2:2025(en).

  • [RFC 4180] Internet Society (2005-10). Common Format and MIME Type for Comma-Separated Values (CSV) Files. RFC 4180. Including errata 5593, 5714, 5345, 6230, and 7572.

Extensible Markup Language (XML) and XML Schema Definition (XSD)

  • [XML 1.0] World Wide Web Consortium (2008-11). Extensible Markup Language (XML) 1.0 (Fifth Edition). Including errata as of 2013-01-09.

  • [XSD 1.1] World Wide Web Consortium (2012-04). W3C XML Schema Definition Language (XSD) 1.1. Including both parts, Part 1: Structures and Part 2: Datatypes, and the errata for both parts as of 2013-05-31.

C programming language

  • [ISO/IEC 9899:1990] International Organization for Standardization, International Electrotechnical Commission (1990-12). ISO/IEC 9899: Programming languages — C. ISO/IEC 9899:1990. Including corrigenda ISO/IEC 9899:1990/Cor 1:1994 and ISO/IEC 9899:1990/Cor 2:1996, and amendment ISO/IEC 9899:1990/Amd 1:1995.

  • [ISO/IEC 9899:1999] International Organization for Standardization, International Electrotechnical Commission (1999-12). ISO/IEC 9899: Programming languages — C. ISO/IEC 9899:1999(E). Including corrigenda ISO/IEC 9899:1999/Cor 1:2001, ISO/IEC 9899:1999/Cor 2:2004 and ISO/IEC 9899:1999/Cor 3:2007.

  • [ISO/IEC 9899:2011] International Organization for Standardization, International Electrotechnical Commission (2011-12). ISO/IEC 9899: Information technology — Programming languages — C. ISO/IEC 9899:2011(E). Including corrigendum ISO/IEC 9899:2011/Cor 1:2012.

  • [ISO/IEC 9899:2018] International Organization for Standardization, International Electrotechnical Commission (2018-06). ISO/IEC 9899: Information technology — Programming languages — C. ISO/IEC 9899:2018(E).

  • [ISO/IEC 9899:2024] International Organization for Standardization, International Electrotechnical Commission (2024-10). ISO/IEC 9899: Information technology — Programming languages — C. ISO/IEC 9899:2024(en).

C++ programming language

  • [ISO/IEC 14882:1998] International Organization for Standardization, International Electrotechnical Commission (1998-09). ISO/IEC 14882: Programming languages — C++. ISO/IEC 14882:1998(E).

  • [ISO/IEC 14882:2003] International Organization for Standardization, International Electrotechnical Commission (2003-10). ISO/IEC 14882: Programming languages — C++. ISO/IEC 14882:2003(E).

  • [ISO/IEC 14882:2011] International Organization for Standardization, International Electrotechnical Commission (2011-09). ISO/IEC 14882: Information technology — Programming languages — C++. ISO/IEC 14882:2011(E).

  • [ISO/IEC 14882:2014] International Organization for Standardization, International Electrotechnical Commission (2014-12). ISO/IEC 14882: Information technology — Programming languages — C++. ISO/IEC 14882:2014(E).

  • [ISO/IEC 14882:2017] International Organization for Standardization, International Electrotechnical Commission (2017-12). ISO/IEC 14882: Programming languages — C++. ISO/IEC 14882:2017(E).

  • [ISO/IEC 14882:2020] International Organization for Standardization, International Electrotechnical Commission (2020-12). ISO/IEC 14882: Programming languages — C++. ISO/IEC 14882:2020(E).

  • [ISO/IEC 14882:2024] International Organization for Standardization, International Electrotechnical Commission (2024-10). ISO/IEC 14882: Programming languages — C++. ISO/IEC 14882:2024(en).

Other formal languages

  • [ISO/IEC 14977:1996] International Organization for Standardization, International Electrotechnical Commission (1996-12). ISO/IEC 14977: Information technology — Syntactic metalanguage — Extended BNF. ISO/IEC 14977:1996(E).

  • [IEC 61131-3] International Electrotechnical Commission (2025-05). IEC 61131-3: Programmable controllers — Part 3: Programming languages. IEC 61131-3:2025.

  • [ISO/IEC 1539-1:2023] International Organization for Standardization, International Electrotechnical Commission (2023-11). ISO/IEC 1539-1:2023: Programming languages — Fortran — Part 1: Base language. Including corrigendum ISO/IEC 1539-1:2023/Cor 1:2026.

  • [ISO/IEC 7185:1990] International Organization for Standardization, International Electrotechnical Commission (1990-10). ISO/IEC 7185: Information technology — Programming languages — Pascal. ISO/IEC 7185:1990(E).

  • [Modelica 3.7] Modelica Association (2026-05). Modelica® Language Specification — A Unified Object-Oriented Language for Systems Modeling — Version 3.7.

MISRA C and C++ development guidelines

  • [MISRA C:1998] Motor Industry Software Reliability Association (MISRA) Limited (1998-04). Guidelines For the Use Of The C language In Vehicle Based Software. MISRA C First edition (MISRA C:1998, PDF version 1.2, October 2002).

  • [MISRA C:2004] Motor Industry Software Reliability Association (MISRA) Limited (2004-10). MISRA C:2004 — Guidelines for the use of the C language in critical systems. MISRA C Second edition. Including MISRA C:2004 Technical Corrigendum 1.

  • [MISRA C:2012] Motor Industry Software Reliability Association (MISRA) Limited (2013-03). MISRA C:2012 — Guidelines for the use of the C language in critical systems. MISRA C Third edition. Including amendment MISRA C:2012 Amendment 1 and technical corrigendum MISRA C:2012 Technical Corrigendum 1. Revised by [MISRA C:2023] which essentially is [MISRA C:2012] including amendments MISRA C:2012 Amendment 2, MISRA C:2012 Amendment 3, and MISRA C:2012 Amendment 4 and technical corrigendum MISRA C:2012 Technical Corrigendum 2.

  • [MISRA C:2023] Motor Industry Software Reliability Association (MISRA) Consortium Limited (2023-04). MISRA C:2023 — Guidelines for the use of the C language in critical systems. MISRA C Third edition, Second revision. Including addenda MISRA C:2023 Addendum 2, MISRA C:2023 Addendum 3 and MISRA C:2023 Addendum 4.

  • [MISRA C:2025] Motor Industry Software Reliability Association (MISRA) Consortium Limited (2025-03). MISRA C:2025 — Guidelines for the use of the C language in critical systems. Including addenda MISRA C:2025 Addendum 5 and MISRA C:2025 Addendum 6.

  • [MISRA C++:2008] Motor Industry Software Reliability Association (MISRA) Limited (2008-06). MISRA C++:2008 — Guidelines for the use of the C++ language in critical systems.

  • [MISRA C++:2023] Motor Industry Software Reliability Association (MISRA) Consortium Limited (2023-10). MISRA C++:2023 — Guidelines for the use of C++17 in critical systems.

Other development guidelines

  • [SEI CERT C 2016] Carnegie Mellon University, Software Engineering Institute (SEI), Computer Emergency Response Team (CERT) Coordination Center (2016-06). SEI CERT C Coding Standard — Rules for Developing Safe, Reliable, and Secure Systems. 2016 Edition. Including errata as of 2021-04-14.

  • [SEI CERT C++ 2016] Carnegie Mellon University, Software Engineering Institute (SEI), Computer Emergency Response Team (CERT) Coordination Center (2017-03). SEI CERT C++ Coding Standard — Rules for Developing Safe, Reliable, and Secure Systems. 2016 Edition. Including errata as of 2019-06-06.


1. “Any sufficiently advanced technology is indistinguishable from magic.” in Profiles of the future: an inquiry into the limits of the possible (Rev. ed.), 1973, Harper & Row