Manuscript Offprint
arXiv:2610.40343Manual binding and semi-automated interface generation for efficient simulation backends with user-friendly frontends: A~demonstration for epidemic use cases
MAXIMILIAN BETZ*, ICE-1, Institute of Climate and Energy Systems, Forschungszentrum Jülich, Germany
DANIEL-MICHEL RICHTER*, Institute of Software Technology, German Aerospace Center, Germany
DANIEL ABELE, Institute of Software Technology, German Aerospace Center, Germany
RENÉ SCHMIEDING, Institute of Software Technology, German Aerospace Center, Germany
HENRIK ZUNKER, Institute of Software Technology, German Aerospace Center, Germany
MARTIN J. KÜHN, Institute of Software Technology, German Aerospace Center, Cologne and Bonn Center for Mathematical Life Sciences and Life and Medical Sciences Institute, University of Bonn, Bonn, Germany
Challenges and chances of mathematical software are directly entangled with the programming language used. Depending on the background of developers and users, conflicts between different goals may arise. While several, e.g., scripting languages allow a low barrier and user-friendly entry to mathematical modeling and simulation, corresponding implementations will most likely not allow timely outcomes for detailed simulations.
In infectious disease modeling, while several large-scale software frameworks rely on C or C++ implementations, most models are implemented in Python or R. While the latter allow for fast prototyping and more interactive development, it has been shown for several applications that C or C++ implementations outperform plain Python or R implementations by factors between one and three orders of magnitude. In particular, in times of pandemics, the urgent need for swift estimation of the system's dynamics makes the use of large-scale models in these noncompiled languages prohibitive.
In order to create synergies and close the gap between scientists from the application and the computational domain, binding libraries allow to execute entire, compiled software frameworks from languages such as Python. However, with iterative model development, extension, or addition of new models, implementing bindings can represent another relevant barrier to developers of the C or C++ backends. In this paper, we show how a large-scale software framework with a multitude of infectious disease models can be efficiently exposed to Python. In addition, we suggest a semi-automated way to generate interface code by analyzing generic C++ code through abstract syntax trees, enabling a modularized approach working with intermediate representations.
Keywords: Programming languages, interoperability, code generation, abstract syntax tree, epidemiological modeling, MEmilio framework
1 Introduction
With individual programming languages serving different purposes, different challenges and opportunities arise. In particular, developers and users need to gain substantially different levels of computational expertise for implementing and using mathematical methods. In epidemiological
Both authors contributed equally to this research.
Authors' Contact Information: Maximilian Betz, m.betz@fz-juelich.de, ICE-1, Institute of Climate and Energy Systems, Forschungszentrum Jülich, Jülich, Germany; Daniel-Michel Richter, daniel-michel.richter@dlr.de, Institute of Software Technology, German Aerospace Center, Cologne, Germany; Daniel Abele, Institute of Software Technology, German Aerospace Center, Cologne, Germany; René Schmieding, Institute of Software Technology, German Aerospace Center, Cologne, Germany; Henrik Zunker, Institute of Software Technology, German Aerospace Center, Cologne, Germany, henrik.zunker@dlr.de; Martin J. Kühn, Institute of Software Technology, German Aerospace Center, Cologne and Bonn Center for Mathematical Life Sciences and Life and Medical Sciences Institute, University of Bonn, Bonn, Germany, martin.kuehn@dlr.de.
Betz et al.
modeling, languages such as R and Python are most widely spread [6], as they offer a low-barrier access to mathematical-epidemiological modeling. However, it has been shown for different applications [27, 29] that compiled languages such as C or C++ outperform Python with respect to time to solution by factors around 50, 100, or more. This well-known fact has led to the development of C, C++, or Fortran compiled packages to, e.g., solve ordinary differential equation-based (ODEs) models in R or Python [19, 39] and for the well known pytorch library, it was recently stated, how non-Python environments such as C++ help to bridge the gap between research prototypes and production deployment [37]. However, addressing individual software components such as numerical ODE solvers for ODE-based problems might not be enough if other costly tasks are conducted in a scripting approach. In [6], it has recently been shown that ODE-based problem formulations with a modest number of spatially distributed subpopulations are simulated 1-2 orders of magnitude faster in fully-bound C++ than when only seeking Fortran or C compiled routines to solve the ODE system. With computation times at the order of seconds, individual simulations will rarely present a bottleneck. Nevertheless, with iterative model development or thousands of simulations necessary for parameter exploration and model calibration, execution will become incompatible with the high timely pressure that is imposed by unfolding or ongoing epidemics. In that direction, efficiently implemented models contribute substantially to timely outputs – an important use factor that increases modeling relevance for policy [32].
While several large-scale software models for infectious disease modeling like OpenABM [14], EpiHiper [8], FRED [13] are implemented in C and C++, primarily targeting users with background knowledge in these languages, others like Covasim [21] or MatSim-episim [25] provide optimized Python or Java implementations to increase the developer and user base. However, eventually, these optimized versions will stay behind the potential of software written in compiled languages. Even other frameworks such as Repast [9, 10] provide separated repositories with models implemented in either C++ or Python. BoostPython [1], pybind11 [16], and nanobind [17] are well established methods to provide Python bindings to C++ implementations. More recent developments based on the Cling C++ interpreter promise better Python binding performance than established solutions with pybind11 but are also less popularized yet [23]. The software frameworks EMOD [5], EpiABM [12], and MEmilio [6] provide Python frontends to their C/C++ backends where the latter both use pybind11. Through this approach, EMOD, EpiABM, and MEmilio are capable to offer low-barrier interfaces tailored to domain-specific users. It has to be noted that in the related domain of veterinary diseases, the provision of R, Python, or even Javascript frontends to compiled language implementations has an already longer history as, e.g., seen by SimInf [40] or BICI [38]. However, the provision of these interfaces comes at substantial cost for developers that need to implement a substantial number of additional lines of code. In these, additional difficulties arise as developers need to understand the particularities of different programming languages using objects through, e.g., pointers, references, or different types of copies. On the other hand, binding large code bases yields a lot of opportunities and, compared to fully new implementations, comes at substantially reduced cost.
To avoid or reduce the cost of manual binding implementations, (semi-)automated approaches have been proposed. AutoWIG [11] or CppInterOp [18] are two approaches that have been suggested for the automated binding generation of C++ libraries. For our application, we distinguish two complementary use cases where automation can come into play. In cases where a clearly separated software module (e.g., a new disease model) is added to the software, bindings can be directly generated with the backend code. Here, a unified description as in MEmilio [6] or a domain-specific language (DSL) as in EMULSION [28] is needed. A popular example of a DSL in biological applications is the Systems Biology Markup Language (SBML) standard [15] which facilitates the task of generating model backend and interface simultaneously from a description in xml.
or yaml formats. DSLs are also used in other domains, e.g., to generate stencil-based code for high-performance computing applications [2, 4, 34]. In cases where the backend code is already available in the compiled language, an analysis of the abstract syntax tree (AST) can enable the semi-automated generation of binding code. For our application, we furthermore distinguish the second use case by the settings where an existing but entire module might need a binding interface or where bindings should only be generated for small entities such as individual functions.
The paper is structured as follows. In Section 2, we first briefly revisit the descriptions of available models in the MEmilio software framework and discuss the advantages and necessity of modular and generic implementations before, in Section 3, explaining the goals, challenges, and essentials chosen in MEmilio to provide C++ implementations to Python. In Section 4, we explain more deeply the (semi-automated) development of Python bindings for existing and new models sharing the same or similar descriptions by analyzing ASTs and transforming them to intermediate representations before generating the target code. We present a modularized approach based on handlers and scanners for ASTs that are connected through an intermediate representation with a code generator for different applications. In Section 5, we show results of the semi-automated generation with respect to code completeness of a comparable MEmilio model and evaluate the performance achieved through Python before, eventually, drawing a conclusion in Section 6.
The MEmilio software framework [6] considered as a base for this article is already set up in a modular fashion and patterns have been unified across different modules of the framework. To better understand the manual and (semi-)automated bindings on top of the C++ backend, we here present structures and several examples from models within the MEmilio framework.
In Code Snippet 1, we provide the flexible definition of infection states for the example of an SEIR-type model representing four infection states (Susceptible, Exposed, Infected, Recovered) and always also integrating a count variable representing the number of states, used for iterating over the states in various places. All models define their individual namespaces inside the global mio namespace. In Code Snippet 2, we show the struct-based definition of a parameter with name TimeExposed for an equation-based model with age stratification. The parameter is templated for the floating point type FP which allows distinction between double precision or the simultaneous consideration of the functional value and an active automatic differentiation (AD) type [26]. For the latter case, relevant components of MEmilio are overloaded for a wide range of equation-based models such that derivative information is directly propagated together with the functional value of the variable. Theoretically, the FP type could also be used to, e.g., use single precision. For models considering aggregated population counts such as in equation-based models, an UncertainValue is used as a generalization of a floating point value, with the allowance of (re)sampling the value from a given distribution. For more complex, agent-based models (ABMs) [20, 22], the UncertainValue in CustomIndexArray is generalized to an AbstractParameterDistribution and stratified according to a VirusVariant.
Betz et al.
namespace oseir { enum class InfectionState { Susceptible, Exposed, Infected, Recovered, Count }; }
Code Snippet 1. Enumeration-based definition of infection states in SEIR model.
template <typename FP> struct TimeExposed { using Type = CustomIndexArray< UncertainValue<FP>, AgeGroup>; static Type get_default(AgeGroup size) { return Type(size, 5.2); } static std::string name() { return "TimeExposed"; } };
Code Snippet 2. Struct-based definition of parameter in equation-based model with age stratification and Exposed state.
While the definition of infection states is identical across all models, transitions or flows between infection states are particularly defined for ODE-based models, from which more than 10 different models are implemented in MEmilio. In Code Snippet 3, we present the flows and model definition for the ODE-based SEIR-type model. Here, only three forward flows from the prior to the later state (without branching nor backward flows) are possible. ODE-based models derive from a FlowModel integrating the floating point type, the list of infection states, a correspondingly resolved population and the list of parameters and flows.
namespace oseir { using Flows = TypeList<Flow<InfectionState>::Susceptible, InfectionState::Exposed>, Flow<InfectionState::Exposed, InfectionState::Infected>, Flow<InfectionState::Infected, InfectionState::Recovered>>; template <typename FP> class Model { : public FlowModel<FP, InfectionState, mio::Populations<FP, AgeGroup, InfectionState>, Parameters<FP>, Flows> { [...] } }
Code Snippet 3. List-based definition of flows between infection states and model constructor for an ODE-based SEIR model.
The correspondingly resolved population is given by a Populations class which stores the numbers of individuals according to different features, e.g., age and infection state in an array, a CustomIndexArray. The Populations object uses a variadic template to allow stratification of the population by an arbitrary number of features or Categories as shown in Code Snippet 4. Stratification by age is resolved through an AgeGroup struct using the curiously recurring template pattern (CRTP). As shown in Code Snippet 5, AgeGroup is used as a tag type for the typesafe index Index, which we refrain from detailing for its technical implementation.
template <typename FP, class... Categories> class Populations : public CustomIndexArray<UncertainValue<FP>, Categories...> [...]
Code Snippet 4. Definition of populations stratified according to a variadic number of categories.
struct AgeGroup : public Index<AgeGroup> { AgeGroup(size_t val) : Index<AgeGroup>(val) { } [...] }
Code Snippet 5. AgeGroup struct to allow for model stratification by age.
The remaining Parameters from the model definition are derived from a ParameterSet which represents a rather technical definition of a parameter set defined at compile time and where parameters are added as template parameters (tags). The ParameterSet constructor exists if all parameters are default constructible and the parameters are passed with their names as shown in Code Snippet 6.
template <typename FP> using ParametersBase = ParameterSet<TransmissionProbabilityOnContact<FP>, TimeExposed<FP>, TimeInfected<FP>, ContactPatterns<FP>>;
template <typename FP> class Parameters : public ParametersBase<FP> { public: Parameters(AgeGroup num_agegroups) : ParametersBase<FP>(num_agegroups) , m_num_groups{num_agegroups} { } } [...]
Code Snippet 6. Definition of the parameter list for an ODE-based SEIR model.
The prior structures are reused throughout the MEmilio framework to realize a large range of mathematical-epidemiological models. For instance, any age-resolved model as presented in Code Snippet 3, can be created on compile time with n age groups by simply calling the constructor in the model's name space with Model(n).
We refrain from providing more technical details or generalizations as, e.g., used in ABMs and refer to the code base and documentation of MEmilio .
3 From C++ backend to a practitioner-targeted Python interface
There are different levels of granularity on how to expose (parts of) a C++ library to Python. In the simplest case, we can bind particular simulation executables with command line interfaces (CLIs) in Python. While this approach is straightforward and requires minimal effort, it also substantially limits the users' interactions with the code backend. The extensive implementation of bindings is tedious and exhausting but can, on the other hand, become the more relevant use case. With flexible bindings, individual users obtain much more freedom in setting up a model according to their needs.
Once the decision for a flexible interface is taken, a comprehensive understanding of, both, programming languages and the architecture of the underlying backend software is required. Developers must be familiar with C++ concepts such as ownership semantics, references, object lifetimes, and template programming while simultaneously understanding how these concepts should be represented in a Pythonic way. In addition, they need to understand the internal structure of the backend to decide which classes, functions, and data structures form part of the public API.
https://memilio.readthedocs.io
Betz et al.
3.1 Development of the MEmilio Python interface
As shown in [6], most infectious disease models are implemented in Python or R which means that the target user base of MEmilio is largely made up from Python developers. In order to allow these users a maximum of flexibility, the Python interface is provided as a fully functional module where users can adapt most of the libraries functionality. Allowing users to adapt parameters and scenarios also enables the coupling of established Python packages, e.g., for sensitivity analysis or parameter estimation. In contrast to a simple binding of a C++ executable with a CLI, our approach targets for a low-barrier and comprehensible line-by-line execution in Python.
MEmilio’s Python interface is made up by manually created bindings and bindings that can be generated semi-automatically as described in the next chapter. Both approaches have different, yet overlapping use cases. While the MEmilio ABM [20], as a unique and flexible model, is developed and extended through changes and patches of limited size, generalizations of equation-based models might require extensive reimplementations based on recurring patterns. This means that MEmilio’s Python interface provides access to the ABM and existing equation-based models through pre-implemented bindings, while the semi-automated generation of new bindings addresses new (equation-based) models and small-scale extensions of general C++ structures. In particular for new models of similar structures, the semi-automated generation maximizes its impact by substantially reducing implementation overhead. Building upon the structure of the C++ library, we provide one module with commonly used utils and submodules for each model where the interface for each module is defined in a single file.
The modular structure of MEmilio allows to create and adapt C++ models and simulations with a lot of flexibility. The Python interface strives to define a common interface between C++ and Python, making the functionality usable in a similar fashion on both ends allowing users to modify domain specific features like age group stratification. As a user, running simulations commonly only involves using a simulation function, which provides an easy interface for solving the model problem until a time point and automatically receiving the result as the return value. When a more granular utilization is needed, the Simulation class can be used directly. In Code Snippet 7, we exemplarily show how the simulation functions using either compartmental values (simulate) or flows (simulate_flows) are translated into Python.
A particular issue originates from templated functions which are resolved in C++ on compile-time but which cannot be handled on Python side in the same fashion. Instead of binding templated functions for each possibly relevant call, we differentiate between the full C++ functionality and the interface which provides the most relevant functionality only. As for instance shown in Code Snippet 7, we only provide the simulation functions for double precision, while, theoretically, the C++ backend allows for substituting the data type. Similarly, we do not bind technical helper functions and low-level numerical functionality which can only be changed in C++ directly.
m.def("simulate", &mio::simulate<double, mio::oseir::Model<double>>,"Simulates an ODE SEIR from t0 to tmax.", py::arg("t0"), py::arg("tmax"), py::arg("dt"), py::arg("model"), py::arg("integrator") = py::none());
m.def("simulate_flows", &mio::simulate_flows<double, mio::oseir::Model<double>>,"Simulates an ODE SEIR with flows from t0 to tmax.", py::arg("t0"), py::arg("tmax"), py::arg("dt"), py::arg("model"), py::arg("integrator") = py::none());
Code Snippet 7. Definition of the interface for simulations of an ODE model.
In Code Snippet 8, we show how the simulate function for an ODE-SEIR model can now be called in particular C++ and Python examples. While we see slight differences, as e.g., the template parameter which is resolved on compile time in C++ and the namespace which is implicitly resolved in Python through our folder structure. For the C++ call, the last argument integrator_core is not given and by default set to nullptr and likewise, Python sets the integrator to py::none(), which for both cases means that the default Runge-Kutta Cash-Karp5(4) integrator is chosen.
C++
auto result = mio::simulate<FP>(t0, tmax, dt, model);
Python
result = simulate(t0, tmax, dt, model)
Code Snippet 8. Comparison of calling the C++ simulate routine for an ODE-SEIR model versus calling the bound Python routine.
Aside from model-specific bindings, the MEmilio Python bindings contain general binding functionality and utilize templated binding helper functions such as bind_population shown in Code Snippet 9. These functions improve the readability of our interface and template deduction from the specific models then enables the corresponding model-specific binding. For instance with the variadic template Cats, the categoric stratification of the population along, e.g., infection states and age groups is inferred.
template <class... Cats> void bind_Population(pybind11::module_& m, std::string const& name, mio::Tag<mio::Populations<double, Cats...>> /tags/) { [...]
Code Snippet 9. Bindings for the templated binding helper function for connecting with the model population.
void bind_time_series(py::module_& m, std::string const& name) { bind_class<mio::TimeSeries<double>, EnablePickling::Required>(m, name.c_str()) [...] .def( "as_ndarray", [](mio::TimeSeries<double>& self) { auto m = Eigen::Map<mio::TimeSeries<double>::Matrix>(self.data(), self.get_num_rows(), self.get_num_time_points()); return Eigen::Ref<mio::TimeSeries<double>::Matrix>(m); }, py::return_value_policy::reference_internal) } }
Code Snippet 10. Binding of the TimeSeries object with consideration of pickling and conversion to numpy array.
To appropriately target the Python user base, we intend to translate the library in a Pythonic way instead of creating a direct copy of the C++ backend. While following the general design of the C++ library, partial adaptations are advised to incorporate Pythonic coding conventions. By these adaptations, we intend to increase the usability and provide a familiarity for developers with Python experience. For instance, we always provide argument names that allow Python developers to hand over objects and parameters not only in the predefined C++ order but also allowing argument names that assist developers in setting up simulations. The TimeSeries object is used in MEmilio's backend for multidimensional, time-dependent arrays, in particular as the output of model simulations. When coupling MEmilio with other (Python) packages, e.g., for plotting with matplotlib, the TimeSeries output should be transformable to standardized objects. By enabling a
Betz et al.
conversion to numpy array, see Code Snippet 10, we facilitate the analysis of simulation outcomes in standardized post-processing or plotting scripts.
Running two languages side by side requires aligning their different memory management models. C++ focuses on manual memory management and RAII (Resource Acquisition Is Initialization), while Python has an automatic approach based on garbage collection and reference counting. Therefore, when introducing bindings, a central concern is the ownership and lifetime of objects shared across the language boundary.
Pybind11 addresses this with return value policies, which define how ownership of a C++ object is handled when it is exposed to Python. Deciding the correct policy can be hard for nontrivial types and depends on the design of the function. The wrong policy can lead to crashes or undefined behavior. For example, if Python wrongfully assumes ownership it may delete an object, even though the object is still used in C++. Or C++ may destroy an object that Python still references, as could happen with the function shown in Code Snippet Listing 10, where the returned object references data that should be managed by C++. We use the reference_internal policy, which leaves ownership with C++ but additionally keeps alive the parent object as long as the reference exists in Python. This prevents an early deallocation of the C++ object, which could otherwise fail silently and possibly lead to data corruption.
Eventually, when implementing additional code in Python, software testing has to be addressed. While generally, good software engineering practices advise to implement extensive unit testing, binding C++ libraries profits from an existing code base that ensures robust solutions without extensive (re)testing. In order to ensure high software quality at a reduced number of new tests and simultaneously minimize errors of interfaces, we opt for more high-level software or integration test on the interface side and compare outcomes to identical tests for the C++ backend. While this leaves a marginally higher chance for introducing errors on the Python interface side, we conclude that with the essential high-level functionality also the individual units behave the same for both interfaces.
3.2 Challenges for new models and structures
The primary design goal of the MEmilio Python interface is to provide a flexible and intuitive interface that evolves together with the MEmilio backend. As new epidemiological models and simulation features are continuously added, the Python bindings must be extended accordingly while maintaining a consistent user experience across all supported models.
The example of the TimeSeries binding from the previous section shows the importance of manual interaction when writing the interface: bindings may follow a common pattern but the decision of and how strongly adapting it to Pythonic coding conventions often relies on case to case decisions. However, the continuous evolution of MEmilio results in a continuous and potentially increasing overhead that cannot be addressed by manually written bindings as the framework grows. Every modification of the underlying C++ library potentially requires corresponding adaptations in the bindings. Maintaining the interface becomes an ongoing software engineering task that overly accompanies the further development of the simulation framework.
4 Semi-automated interface generation through ASTs of existing code
The arrival of publicly available coding agents has facilitated implementation tasks. However, vibe-or co-coded implementations might suffer from different types of issues such as errors from over-confident outputs, overly complex structures, and missing verification and validation [24, 30, 36]. For our dedicated setting, classic code generation through AST analysis is better suited and, in addition, only requires local resources. Building on top of clear modularization, unified structures, and recurring patterns as introduced in Section 2, we suggest a semi-automated approach for interface generation. Our approach is based on the compilation of several targets of the underlying software framework and can then be executed in a matter of seconds to minutes on laptop infrastructure. By providing different templates of the target code, we allow a model- or more general structure-based generation of the binding code. The resulting structure substantially accelerates the manual process of implementation by also avoiding typical typo or copy-and-paste errors. Our long term goal is to provide an automatic creation interface for new user-defined models, including their (full) exposure to Python without any prior knowledge needed of binding libraries. This goal is especially important for Python users, as both the base models, as well as the bindings are written in C++.
4.1 Concept and workflow
To systematically transform the recurring patterns, into reusable Python interfaces, the MEmilio interface generation approach has been developed as a multi-stage processing pipeline illustrated Fig. 1. The workflow consists of three central phases: structural extraction, intermediate representation, and template-based code generation. As the framework itself, the pipeline has been designed in a modular fashion such that the individual components can also serve multiple use cases.
In large and modular software libraries, it is uncommon to provide a single build target that covers the entire code base. Instead, functionality is typically distributed across several targets, each requiring only the components of a specific task. Leveraging this structure in MEmilio, we avoid the creation and maintenance of an additional target that includes all source files and which would have to be adapted with every new model and updated whenever the project structure changes. The processing pipeline therefore starts with multiple C++ targets, each representing a defined build target within the software backend and containing the corresponding components such as a model and its implementation files. The pipeline processes the existing targets individually and combines the extracted information to obtain a complete representation of the library. As shown on the right of Fig. 1, a centralized configuration component acts as the main interface for providing relevant paths and parameters to the processing stages of the ASTHandler and the Scanner. Based on this configuration, the ASTHandler locates the source code belonging to each C++ target and converts it into an AST representation using the appropriate compiler settings.
The ASTHandler serves as the central coordination unit of the first stage and controls the creation of the ASTs ensuring that each target is translated into an independent AST. For increasing numbers of input targets, the ASTHandler allows processing of the individual targets in parallel using Python's multiprocessing functionality. After generation, the ASTs are stored as structured representations and made available for subsequent analysis. The Scanner processes the ASTs sequentially and extracts all user-defined structures, such as selected classes and functions which are intended for the Python bindings. The extracted information is stored in a consolidated Intermediate Representation, which serves as a stable interface between analysis and code generation. The Intermediate Representation serves as a flexible interface that shall allow the Scanner or Generator to be exchanged independently. In the final step, the Generator consumes the information from the Intermediate Representation and applies predefined code templates to produce syntactically correct and consistent C++ binding code, which is written to dedicated output files.
Following the workflow illustrated in Fig. 1, the overall architecture of the code generation process emphasizes modularity and scalability. Each processing stage is clearly separated and communicates through well-defined data structures, which simplifies maintenance and allows individual components to be extended or replaced independently. In particular the strict separation between AST construction, analysis, and code generation ensures that changes in one phase do not propagate unintended side effects to subsequent stages.
Betz et al.

Fig. 1. Workflow of the modular analysis and code generation process. The blue boxes represent components of the modular pipeline while the orange boxes indicate input and output elements. Trapezoidal boxes denote data structures and rounded boxes represent logic classes or active components.
4.2 Extracting structural information
4.2.1 Transforming source code and organizing ASTs. The transformation of source code into ASTs is preceded by a dedicated configuration phase that defines the structural context required for the analysis. This configuration specifies the source environment, including source files, output directories, and compiler-related settings required for AST construction. It ensures that the analyzed code is processed within the correct build context and that all dependencies can be resolved consistently.
The resulting AST provides a hierarchical representation of nodes of the syntactic structure of the source code, preserving structural and semantic relationships while abstracting from irrelevant formatting details. The ASTs form the basis for all subsequent analysis steps. Each node of the AST corresponds to a language construct such as a class, function, parameter, or expression, thereby enabling the systematic identification of recurring structures such as model parameter sets, flow specifications and model definitions.
To manage the creation and organization of ASTs in our framework, we utilize the dedicated ASTHandler class. First, this class provides a unified interface for generating ASTs from source code. Second, the class maintains an internal data structure to manage the created ASTs. This includes functionality for adding new ASTs, removing obsolete ones, and accessing the stored ASTs for subsequent analysis or transformations. By centralizing both the creation and management of ASTs, the ASTHandler simplifies interaction with the underlying Clang infrastructure and provides a scalable solution for analyzing large code bases.
A central conceptual element of the AST approach is the introduction of unique identifiers and line numbers, enabling each node in the AST to be mapped precisely to a corresponding line in the source code and retrieved through an unambiguous identifier. This assignment of IDs and line numbers provides the structural basis for subsequent mechanisms. The design introduces the capability to selectively extract subtrees based on these identifiers. This allows specific code segments, such as individual classes or functions, to be isolated and visualized independently. Such selective visualization supports a more focused examination of individual program components by suppressing irrelevant structures and emphasizing the relevant context. This feature proves particularly valuable when investigating deeply nested constructs. The concept supports a flexible range of output formats. First, it supports a structured tree view within a text file or as a compact excerpt displayed in the console. Second and to facilitate a more effective analysis of ASTs, a dedicated visualization class was introduced. This component serves as the foundation for a set of mechanisms aimed at improving the interpretability and flexibility of AST representations.
In the following Figs. 2 and 3, we provide two examples of such AST representations for structures from the MEmilio framework, illustrating how a C++ function is transformed into its hierarchical AST structure and highlighting the structural decomposition of source code into analyzable language constructs. Together, these two representations demonstrate how the structural components of a function are stored.
Example 4.1 (AST of Parameters constructor). The top node of Fig. 2 represents the declaration of the Parameters constructor as shown in Code Snippet 6 and from which several substructures branch out. These structures can be found in the AST in an hierarchical pattern where all nodes represent different CursorKinds that describe the kind of entity the cursor points to. Most prominently from the left, we see the CursorKind.PARM_DECL which points to the declaration of the input parameter num_agegroups as depicted in Code Snippet 6. Below the PARM_DECL cursor kind, we see the CursorKind.TYPE_REF to the mio::AgeGroup, the type of the expected parameter. From the left, the second and third child of the top node encode the base class initialization, with a TEMPLATE_REF to the base class ParametersBase and a TYPE_REF the its corresponding template type parameter FP. The fourth child refers back to the first node, which is passed as an input parameter to the constructor of the base class. Similarly, the next two child nodes of the constructor MEMBER_REF and CALL_EXPR represent the member initialization of m_num_groups through a call to the constructor of the class AgeGroup. The last child node COMPOUND_STMT represents the body of the constructor as it can be seen in the constructor code itself. The compound statement COMPOUND_STMT of the AST does not contain any further information, as its constructor body is empty.
Betz et al.

Fig. 2. Graph visualization of the Parameters<FP> constructor of the MEmilio framework transformed into AST.
Example 4.2 (Reduced AST of simulate function). In Fig. 3, we show a reduced graphical representation of the AST of the simulate function which has in total 54 nodes. The first node TEMPLATE_TYPE_
PARAMETER is shown with dashed lines as it aggregates the declaration of the three template type parameters for a simplified visualization. The types of the actual nodes are replaced by concrete types during template instantiation. From the left, the next two nodes represent the function return type with TEMPLATE_REF describing the template class and TYPE_REF the corresponding template parameter as a reference to the template type of the simulate function. Finally, the fourth visualized node aggregates five actual nodes of PARM_DECL. Code Snippets 7 and 11 show the corresponding parameter declarations of t0, tmax, dt, model, and integrator_core, where the latter obtains a standard argument. We also show the COMPOUND_STMT, that contains several statements, namely a CALL_EXPR, a DECL_STMT, an IF_STMT, and a RETURN_STMT. The first CALL_EXPR represents a call to a member function of the model. The DECL_STMT declares the simulation object and initializes it using the model, t0, and dt parameters. The IF_STMT checks whether an integrator_core has been provided and, if so, assigns it to the simulation. The subsequent CALL_EXPR advances the

Fig. 3. Reduced graph visualization of the simulate function of the MEmilio framework transformed into AST.
simulation up to tmax. Finally, the RETURN_STMT returns the resulting simulation data through a CALL_EXPR corresponding to mio::simulate.
In Code Snippet 11, we additionally provide the list-based subtree output. The simulate function has node identifier 754637. The list-based subtree includes the selected node as its root along with all of its direct and indirect descendants.
ID:754637 simulate <CursorKind.FUNCTION_TEMPLATE> ../compartments/simulation.h:100 ID:754638 FP <CursorKind.TEMPLATE_TYPE_PARAMETER> ../compartments/simulation.h:99 ID:754639 Model <CursorKind.TEMPLATE_TYPE_PARAMETER> ../compartments/simulation.h:99 ID:754640 Sim <CursorKind.TEMPLATE_TYPE_PARAMETER> ../compartments/simulation.h:99 ID:754641-754644 [...] ID:754645 TimeSeries <CursorKind.TEMPLATE_REF> ../compartments/simulation.h:100 ID:754646 FP <CursorKind.TYPE_REF> ../compartments/simulation.h:100 ID:754647 t0 <CursorKind.PARM_DECL> ../compartments/simulation.h:100 ID:754648 FP <CursorKind.TYPE_REF> ../compartments/simulation.h:100 ID:754649 tmax <CursorKind.PARM_DECL> ../compartments/simulation.h:100 ID:754650 FP <CursorKind.TYPE_REF> ../compartments/simulation.h:100 ID:754651 dt <CursorKind.PARM_DECL> ../compartments/simulation.h:100 ID:754652 FP <CursorKind.TYPE_REF> ../compartments/simulation.h:100 ID:754653 model <CursorKind.PARM_DECL> ../compartments/simulation.h:100 ID:754654 Model <CursorKind.TYPE_REF> ../compartments/simulation.h:100 ID:754655 integrator_core <CursorKind.PARM_DECL> ../compartments/simulation.h:101 ID:754656-754660 [...] ID:754661 <CursorKind.COMPOUND_STMT> ../compartments/simulation.h:102 ID:754662 <CursorKind.CALL_EXPR> ../compartments/simulation.h:103 ID:754663 <CursorKind.MEMBER_REF_EXPR> ../compartments/simulation.h:103 ID:754664 model <CursorKind.DECL_REF_EXPR> ../compartments/simulation.h:103 ID:754665 <CursorKind.DECL_STMT> ../compartments/simulation.h:104 ID:754666 sim <CursorKind.VAR_DECL> ../compartments/simulation.h:104 ID:754667 Sim <CursorKind.TYPE_REF> ../compartments/simulation.h:104 ID:754668 <CursorKind.UNEXPOSED_EXPR> ../compartments/simulation.h:104 ID:754669-754671 [...] ID:754672 <CursorKind.IF_STMT> ../compartments/simulation.h:105 ID:754673 integrator_core <CursorKind.DECL_REF_EXPR> ../compartments/simulation.h:105 ID:754674 <CursorKind.COMPOUND_STMT> ../compartments/simulation.h:105 ID:754675-754682 [...] ID:754683 <CursorKind.CALL_EXPR> ../compartments/simulation.h:108 ID:754684 <CursorKind.MEMBER_REF_EXPR> ../compartments/simulation.h:108 ID:754685 sim <CursorKind.DECL_REF_EXPR> ../compartments/simulation.h:108 ID:754686 tmax <CursorKind.DECL_REF_EXPR> ../compartments/simulation.h:108 ID:754687 <CursorKind.RETURN_STMT> ../compartments/simulation.h:109 ID:754688 <CursorKind.CALL_EXPR> ../compartments/simulation.h:109 ID:754689 <CursorKind.MEMBER_REF_EXPR> ../compartments/simulation.h:109 ID:754690 sim <CursorKind.DECL_REF_EXPR> ../compartments/simulation.h:109
Code Snippet 11. Reduced Subtree of an AST in textual representation.
4.2.2 Identifying relevant structures from ASTs. The Scanner is the central component responsible for analyzing ASTs and extracting relevant structures from them. It systematically traverses the ASTs, identifies key elements according to predefined criteria and collects the information necessary for subsequent processing stages in a dictionary. By isolating and organizing these structures, the Scanner enables efficient and structured handling of the program's syntactic and semantic information. To determine which elements of the AST should be extracted, the Scanner is equipped with a configuration dictionary (see Code Snippet 12) in which all target structures are defined in advance. This dictionary specifies types, function names, class identifiers, or syntactic constructs that are relevant for the analysis and later code generation stages.
While high-level dictionary input referring to an entire model automatically identifies and extracts large sets of AST nodes, user-defined configuration also allows individual functions to
Betz et al.
be selected. In Code Snippet 12, we, for instance, provide the short and simple notation for the simulate function to be added to the model components that are identified automatically. With this approach, we allow, on one hand, simplified and automatic selection of all model components while, on the other hand, we maximize flexibility for instances where automatic deduction from model level is not sufficient. Additionally defining the desired function in the configuration dictionary extends the set of extracted components according to the requirements of a particular analysis or code generation task.
{ "type": "function", "name": "simulate" }
Code Snippet 12. User-defined selection for simulate function.
The traversal of the AST is performed using a depth-first search (DFS) approach. Each node in the tree is visited, starting from the root node and exploring as far as possible along each branch before backtracking. This method ensures that all nodes and their hierarchical relationships are examined in a structural manner. The DFS traversal is implemented recursively, allowing the Scanner to efficiently process nested structures and extract the relevant information from every node within the AST. At each visited node the Scanner compares the nodes' attributes with the specifications contained in the configuration dictionary. If the node matches an entry defined in the dictionary the Scanner triggers the extraction step. The extracted information is first stored in a temporary dictionary called found_info. Each completed found_info dictionary is then appended to a list named found_bindings which accumulates all discovered and processed bindings throughout the traversal. This mechanism ensures that the Scanner produces a structured and easy accessible representation of all elements that match the predefined search criteria.
4.3 Organization of information in Intermediate Representation
After identifying and extracting the relevant information from the AST, the data must be stored in an intermediate form before it can be used by the Generator. To do so, we introduce our Intermediate Representation, which serves as the data model between the scanning and generation stages. Its purpose is to organize and preserve the extracted information in a structured manner, allowing the subsequent generation step to access and process it. With the Intermediate Representation, the Generator can operate exclusively on this structured model, no longer needing to access or traverse the original ASTs.
found_info = binding_type_info( type=binding_type, name=node.spelling, cursorkind=node.kind.name, namespace=namespace, return_type=node.result_type.spelling if node.kind.is_declaration() else "", arg_types=function_arguments.get("arg_types", []), arg_names=function_arguments.get("arg_names", []), parent_name=function_arguments.get("parent_name", ""), is_const=function_arguments.get("is_const", False), is_member=function_arguments.get("is_member", False), methods=[] )
Code Snippet 13. Intermediate Representation entry.
The found_info dictionary in Code Snippet 13 illustrates the creation of one entry in the Intermediate Representation. For each relevant declaration encountered during the AST traversal, an object of type binding_type_info is instantiated. The object stores essential metadata, including the declaration type, name, cursor kind, and namespace. For function declarations, additional information such as the return type, parameter types, and parameter names are recorded. Furthermore, properties describing the declaration context, for instance whether the function is a member or independent, are included. In another step, class declarations collect their associated member functions.
The Intermediate Representation in Code Snippet 14 is tailored to the description of a (new) model implemented in MEmilio and it combines configuration information, model-specific properties, and the bindings extracted during the AST analysis. While attributes such as model_class, namespace, and scalartype describe the model and generation context, collections such as model_init, population_groups and include_list preserve structural information required during code generation. The found_bindings field provides the connection to the individual binding_type_info entries. It stores all relevant declarations identified during the scanning phase and therefore forms the main input for the binding generation process.
@dataclass class IntermediateRepresentation: namespace: str = "" model_class: str = "" python_module_name: str = "" parameterset: str = "" parameterset_wrapper: str = "" simulation: bool = False is_compartmentalmodel: bool = False is_flowmodel: bool = False has_age_group: bool = False has_draw_sample: bool = False scalartype: str = "double" python_generation_module_path: str = "" target_folder: str = "" enum_populations: dict = field(default_factory=dict) model_init: list = field(default_factory=list) model_base: list = field(default_factory=list) model_base_templates: str = "" population_groups: list = field(default_factory=list) include_list: list = field(default_factory=list) age_group: dict = field(default_factory=dict) found_bindings: list[binding_type_info] = field( default_factory=list) ...
Code Snippet 14. Structure of the Intermediate Representation.
4.4 Interface generation
In this section, we first present the model-specific binding generation in Section 4.4.1 as required by our initial use case. In Section 4.4.2, we present a generalization of binding code generation, considering general C++ structures, to be used either independently or complementary to the model-specific generation..
4.4.1 Model-specific generation. After the successful identification and extraction of relevant structures within the Intermediate Representation, the next step is the generation of bindings. The binding generation phase uses a template-based representation to transform the structural information collected by the Scanner into concrete binding code. The template shown in Code Snippet 15 defines the overall structure of the generated PYBIND11_MODULE and contains placeholders for model-specific binding components. For each placeholder, of the form ${name_of_the_placeholder},
Betz et al.
the Generator provides a function that receives the Intermediate Representation and returns the corresponding string. Some placeholders, for instance {parameterset}, and {model_init}, {draw_sample}, stand on their own and are replaced by complete code segments. The placeholder ${simulation} illustrates how the generated code adapts to the model-specific structures. For instance, if the model is defined as a FlowModel, the binding statement exposes the class and an additional function for simulating with flows. The function composing these binding statements used to replace the placeholder, including all possible variants, is shown in Code Snippet 18 in the appendix. The template itself remains independent of a particular model, while the generated binding code is specialized to the structures identified for the respective model.
[...] PYBIND11_MODULE(simulation{python_module_name}, m) { {population_enums} {parameterset}<{parameterset}"); {model_class_name}<{population}>{}); pymio::bind_CompartmentalModel<{model_base_templates}>(m, "{namespace}{ScalarType}>, pymio::EnablePickling::Required, {model_class_name}"); {simulation} ${draw_sample} [...] }
Code Snippet 15. Placeholders for the binding text.
4.4.2 Generalization to structural C++ level. Either independently or combined with the model-specific generation, we can generate selected parts of the code with the user-defined selection of structures described in Section 4.1. This more versatile approach for semi-automated code generation of prominent C++ structures such as classes, templated classes, or functions enables more flexibility but also requires more user-specific input. As in the previous section, the generated code is based on templates. However, we no longer work with a fixed template structure but require the selection of a suitable template for each extracted element.
To select the appropriate template for each extracted structure, the system employs a coordination component as visualized in Fig. 4. This component iterates over all entries identified and integrated in the Intermediate Representation and determines which template category should be applied. The decision is based primarily on the general type of the extracted structure and when necessary on more fine grained classification attributes.
More precisely, class like structures are first distinguished according to their specific form, enabling the system to separate classes from functions. Each category is then forwarded to a specialized processing routine that is responsible for generating the corresponding binding representation.

Fig. 4. Template selection and generation workflow.
Function like structures undergo a similar process and are routed to dedicated handling mechanisms that evaluate their characteristics and choose an appropriate generation strategy.
This separation of responsibilities ensures that the extracted information is placed into the correct semantic context and establishes a clear link between the analysis phase and the code generation phase. It allows the simple expansion to previously nonconsidered structures, also including novel functionality of C++ or the binding library. The template selection mechanism acts as the core decision layer that governs how the abstract information is transformed into concrete bindings.
Once an element has been assigned to a template, a dedicated generation procedure processes the relevant properties associated with that element. These properties such as names, signatures, or structural relationships form the foundation for determining how the resulting binding code should be composed. During this step the system evaluates specific conditions to identify the correct generation strategy. Structures with special characteristics such as overloaded functions or otherwise not directly exposable functions are handled using more flexible or adaptive template variants. Depending on the structural context the generated representation may vary, e.g., between methods that belong to a class and standalone functions as shown in Code Snippet 16, ensuring that each binding is correctly integrated into its surrounding module or object hierarchy. Note that
Betz et al.
standalone as well as member functions always obtain a scalartype template which is defined by the utilized computation precision in MEmilio.
def direct_binding(name: str, namespace: str, scalartype: str, py_args: str, prefix: str, is_member: bool, parent_name: str) -> str:
if not is_member: return ( f'\t{prefix}.def(' f'\n\t{{name}}', f'\n\t&{namespace}{name}<{scalartype}', f'\n\t\t{py_args}\n\t); \n\n' ) else: return ( f'\t{prefix}.def("name", &{namespace}{parent_name}<{scalartype}::{name})\n' )
Code Snippet 16. Template used for generating bindings of standalone and member functions.
The combination of AST analysis, the Intermediate Representation, and general structure-based code generation forms a complete transformation pipeline. Once all preceding processing steps have been executed, the resulting output is the final binding code, an example of which is shown in Code Snippet 17.
m.def( "simulate", &mio::simulate<double>, py::arg("t0"), py::arg("tmax"), py::arg("dt"), py::arg("model"), py::arg("integrator_core") );
Code Snippet 17. Generated binding for the simulate function.
5 Results
In the previous sections, we have presented our approach for providing a Python frontend to the efficient C++ backend in MEmilio. For users, the corresponding Python shall deliver a flexible frontend that does not stand back the C++ performance when executing MEmilio's models and that allows to couple established Python frameworks for, e.g., sensitivity analysis or parameter estimation. For developers, the semi-automated generation approach shall deliver a fast and flexible way of binding functional extensions or new models. We demonstrate that our approach is indeed capable of addressing these requirements in individual sections.
5.1 Runtime overhead of the Python bindings
We first show that the overhead of the Python bindings, despite its flexibility in setting up user-specific simulations, is negligible. Therefore, we consider a graph-based epidemic simulation where, at every graph node, the local infection dynamics are represented by an age-stratified ODE-based SECIR-type model. Individuals progress from susceptible through exposed but not yet infectious, infectious without symptoms, and symptomatic infectious states. The model additionally resolves severe and critical infections, corresponding to hospitalization and intensive-care treatment, as well as recovery and death. The local models are coupled through the graph edges, which describe commuter mobility occurring at discrete time points twice a day. Local infection dynamics are advanced between these discrete mobility events. The parameters are taken from [6] and further details on the model are given in [41].
We consider graphs with 10 to 1000 nodes where 40 % of the edges represent nontrivial mobility exchange, all other edges are removed. The local models are all initialized with either age groups. All simulations advance the system from t = 0 to t = 1 with a fourth-order Runge-Kutta method of step size . For each configuration, 30 measurements were performed after one warm-up in each of three independent jobs. The reported values are medians of the per-job medians, and the error bars span their minimum and maximum. We measure only the time for the simulate itself as the initialization is excluded from timing. All measurements use one CPU core on an exclusively allocated node with two AMD EPYC 9555 64-Core processors.
(a) Simulation advance

(b) Binding overhead relative to C++

Fig. 5. Runtime of the graph-based ODE-SECIR simulation in Python and C++ (left) and relative Python-binding overhead (right) for a step size of . Panel (a) compares the C++ runtime with the runtime obtained for execution for Python. Panel (b) shows their relative difference. G denotes the number of age groups.
Figures 5 and 6 compare the runtimes for simulating the same scenarios directly in C++ against running the simulation through Python bindings for different step sizes. Panel (a) shows that the runtime increases with both the number of graph nodes and the number of age groups. The C++ and Python markers nearly coincide because both execute the same C++ backend simulation code. Panel (b) isolates the cost of the Python execution and demonstrate the comparatively small cost of across all simulations.
For simulations with 10 graph nodes, the absolute overhead only ranges around 3 s, which is too small to be visible in Panel (a). With , this corresponds to an overhead between 0.5 % and 2.5 %, depending on the number of age groups. For , fewer Runge-Kutta steps are performed within the same bound function and the relative overhead at 10 nodes ranges from approximately 2.1 % to 5.9 %.
The differences becomes even less relevant as the graph size increases. At 30 ( ) or 100 ( ) nodes, the relative overhead is already below 1 %. At 1000 nodes, the absolute overhead is approximately 23–28 s for and 20–23 s for . Relative to the simulation runtime, this corresponds to only 0.0008 %–0.0038 % for and 0.0033 %–0.0137 % for . The larger relative values for result from the smaller amount of computational work performed per Python call rather than from a larger absolute binding cost. Overall, invoking the
Betz et al.
(a) Simulation advance

(b) Binding overhead relative to C++

Fig. 6. Runtime of the graph-based ODE-SECIR simulation in Python and C++ (left) and relative Python-binding overhead (right) for a step size of . Panel (a) compares the C++ runtime with the runtime obtained for execution for Python. Panel (b) shows their relative difference. G denotes the number of age groups.
graph simulation through Python introduces no practically relevant overhead for computationally substantial configurations. Moreover, the C++ and Python results were bitwise identical in all validation runs.
5.2 Coupling with established Python frameworks
Aside from providing a good performance, our Python bindings also enable the coupling of MEmilio with established Python frameworks. While selected MEmilio models have already been coupled successfully with advanced parameter estimation pipelines using BayesFlow [31] or pyABC [35] (see [6, 7]), we here demonstrate how a (novel) MEmilio model can be swiftly connected to, e.g., a sensitivity analysis pipeline, only requiring a couple of additional lines. OpenTURNS [3] is an open-source initiative for the treatment of uncertainties and allows to compute first-order Sobol' indices to assess how the variation in input parameter x alone explains the output variance. We consider an ODE-based SECIR-type model as in the previous section and compute Sobol' sensitivity indices using a rank-based algorithm. We take the weighted average values as given in [33, Table 2] and assume uniform marginal distributions with lower bound at 50 % of the average value and upper bound at 150 % of the average. The corresponding parameters and their values are also reprinted in Table 1. We consider a joint distribution made up by the 12 independent parameter distributions. Computing 1000 samples, we estimate Sobol' indices with respect to the total number of infections and deaths after 30 days of simulation. The code is provided with MEmilio . While the focus here is not on the assessment of the model, we briefly comment the results in Fig. 7. The transmission probability on contact is observed as the most influential parameter, while the analysis also correctly assigns a high importance to the transmission by nonsymptomatic individuals ( ). Also, we see that the shares (or deterministic probabilities) of severe and critical cases are observed to


Fig. 7. Sobol' indices for the ODE-SECIR model with respect to the total number of infections (left) and deaths (right) after 30 days of simulation.
have little to no influence on the total number of infections while these parameters are as expected more important for the total number of deaths.
5.3 Generating bindings to a new model
As part of our results, we exemplarily show how the bindings of a (new) model can be generated with the memilio-generation package. For the Bindings Generator, we use the Clang C++ library together with the libclang Python bindings in required version 18.1.1, the Python packages scikit-build, dataclasses, dataclasses_json, graphviz and importlib-resources, as well as the Python development libraries (python3.x-dev). The package installation with its dependencies is installed from the MEmilio repository , directory pycode/memilio-generation. Installation instructions are also provided in the documentation of the MEmilio Generation package with the Bindings Generator .
We configure the generator for the SEIR model using the example script example_oseir.py for a single C++ target and AST. For the SECIR-type target, we only adapt source file path.
https://github.com/SciCompMod/memilio
https://memilio.readthedocs.io/en/latest/python/m-generation.html



Fig. 8. Runtime distributions of the entire workflow for SEIR and SECIR models. Boxplots show the median, interquartile range and whiskers for AST creation (blue), scanning process (orange) and code generation (green). The panels use different y-axis scales to improve readability.
Betz et al.
For comparison we consider the generation of an ODE-based SEIR and SECIR-type model, with both having handwritten bindings we can validate to. The runtime measurements of the entire process are split into building the AST of the C++ target, the Scanner extracting all relevant model information and lastly the generation of the binding code by the Generator. The benchmark is executed on a nonexclusive, single core of an Ubuntu 24.04 based work station with two Intel(R) Xeon(R) Gold 6230R CPU @ 2.10GHz (26 Cores, 52 Threads) CPUs. We conduct ten runs per model to obtain a more robust timing.
Figure 8 provides the results and shows that in both cases the runtime of the entire workflow takes on average less than one minute on a single core. More precisely, we obtain an average of 52 s for the SEIR model and 53 s for the SECIR model. Even in the slowest measured run, where system components might have interacted, the generation took less than 70 seconds. The largest part of this time is spent on the creation of the AST, while the Scanner itself requires only about four seconds, and the time needed for the generation itself is negligible.
6 Conclusion
In this paper, we have presented an approach for the (semi-automatical) provision of user-friendly interfaces for efficient simulation backends. Based upon pybind11, we bind the C++ high performance Modular EpideMics simuLatIOn software MEmilio in a Python interface, translating MEmilio's functionalities in a Pythonic way. Instead of high-level coupling of single executables, we strive for a maximum of flexibility. Providing the framework's major functionalities in Python, users can set up scenarios, choose model stratifications, manipulate model parameters, simulate ensemble settings, and couple established Python frameworks for sensitivity analysis or parameter estimation.
Binding all relevant functionality, we demonstrate numerically that our holistic coupling approach represents minimal to no overhead and yields almost the same performance as our C++ baseline. Addressing Python developers as the largest group of developers and users in mathematical-epidemiological modeling, we effectively reduce the barriers for simulation-based pandemic mitigation. The latter holds in particular true as MEmilio's modular resolution in demography and space enables advanced, yet swift epidemic simulations from Python.
Through our suggested three stage process of semi-automatically generating Python bindings, we allow for the direct utilization of extensions and generalizations of the backend in Python. Translating a set of relevant C++ executables into abstract syntax trees (ASTs), we provide the base for a Scanner that flexibly extracts information corresponding to a user-defined configuration. Based upon an Intermediate Representation, a Generator generates new binding code based on a templated target code. While initially build for binding entirely new models, the Generator has been extended to create more general code based on structural C++ level. By replacing repetitive implementation work through automation and decoupling interface creation from the individual extension of the backend, our semi-automated approach establishes a scalable mechanism for extending the Python interface of MEmilio. Importantly, the entire process requires less than one minute of a single core of a Linux workstation. It is thus highly efficient with respect to the required computational resources and does not introduce additional delays in the modeling process. Modifications or extensions in the underlying codebase require only adjusting the general configuration that describes which elements should be exposed. The generation process itself remains unaffected, enabling rapid integration of new features while preserving maintainability. This is particularly relevant as it enables the integration into Python without explicit knowledge of the underlying binding framework.
In future work, we will consider how C++ model and Python binding code could simultaneously be generated by leveraging the already existing C++ code together with user-defined input on model generalizations or extensions, e.g., through the inclusion of vector-borne diseases.
Acknowledgments
This work was supported by the Initiative and Networking Fund of the Helmholtz Association (grant agreement number KA1-Co-08, Project LOKI-Pandemics) and by the German Federal Ministry for Digital and Transport under grant agreement FKZ19F2211A (Project PANDEMOS). It was furthermore supported by the German Federal Ministry of Education and Research and the German Federal Ministry of Research, Technology and Space under grant agreement 031L0325A (Project TwinChain) and 031L0324E (Project EPISERVE) and the Deutsche Forschungsgemeinschaft (DFG, German Research Foundation) (grant agreement 528702961). TwinChain and EPISERVE are part of the Modeling Network for Severe Infectious Diseases (MONID).
References
[1] Dave Abrahams and Stefan Seefeld. 2015. Boost.Python. https://www.boost.org/doc/libs/latest/libs/python/doc/html/index.html.
[2] Samer Alhaddad, Jens Förstner, Stefan Groth, Daniel Grünewald, Yevgen Grynko, Frank Hannig, Tobias Kenter, Franz-Josef Pfeundt, Christian Plessl, Merlind Schotte, Thomas Steinke, Jürgen Teich, Martin Weiser, and Florian Wende. 2022. The HighPerMeshes framework for numerical algorithms on unstructured grids. Concurrency and Computation: Practice and Experience 34, 14 (June 2022), e6616. doi:10.1002/cpe.6616
[3] Michaël Baudin, Anne Dutfoy, Bertrand Iooss, and Anne-Laure Popelin. 2016. OpenTURNS: An Industrial Software for Uncertainty Quantification in Simulation. Springer International Publishing, Cham, 1–38. doi:10.1007/978-3-319-11259-6_64-1
[4] Martin Bauer, Harald Köstler, and Ulrich Rüde. 2021. lbmpy: Automatic code generation for efficient parallel lattice Boltzmann methods. Journal of Computational Science 49 (Feb. 2021), 101269. doi:10.1016/j.jocs.2020.101269
[5] Anna Bershteyn, Jaline Gerardin, Daniel Bridenbecker, Christopher W Lorton, Jonathan Bloedow, Robert S Baker, Guillaume Chabot-Couture, Ye Chen, Thomas Fischle, Kurt Frey, Jillian S Gauld, Hao Hu, Amanda S Izzo, Daniel J Klein, Dejan Lukacevic, Kevin A McCarthy, Joel C Miller, Andre Lin Ouedraogo, T Alex Perkins, Jeffrey Steinkraus, Quirine A ten Bosch, Hung-Fu Ting, Svetlana Titova, Bradley G Wagner, Philip A Welkhoff, Edward A Wenger, Christian N Wiswell, and for the Institute for Disease Modeling. 2018. Implementation and applications of EMOD, an individual-based multi-disease modeling platform. Pathogens and Disease 76, 5 (July 2018). doi:10.1093/femspd/fty059
[6] Julia Bicker, Carlotta Gerstein, David Kerkmann, Sascha Korf, René Schmieding, Anna Wendler, Henrik Zunker, Daniel Abele, Maximilian Betz, Khoa Nguyen, Lena Plötzke, Kilian Volmer, Agatha Schmidt, Nils Waßmuth, Patrick Lenz, Daniel Richter, Hannah Tritzschak, Ralf Hannemann-Tamas, Julian Litz, Paul Johannssen, Marielena Borges, Annika Jungklaus, Manuel Heger, Annalena Lange, Elisabeth Kluth, Kathrin Rack, Vincent Wieland, Jonas Arruda, Sebastian Binder, Margrit Klitz, Martin Siggel, Manuel Dahmen, Achim Basermann, Michael Meyer-Hermann, Jan Hasenauer, and Martin J. Kühn. 2026. MEmilio – A high performance Modular Epidemic SimuLatIon software for multi-scale and comparative simulations of infectious disease dynamics. arXiv (2026). doi:10.48550/arXiv.2602.11381
[7] Julia Bicker, Natalie Tomza, Karina Wallrafen-Sam, Nina Schmid, Andreas F. Hofmann, Sascha Korf, Alain Schengen, Jasmin Javanmardi, Andreas Wieser, Martin J. Kühn, and Jan Hasenauer. 2025. Coupled Epidemiological and Wastewater Modeling at the Urban Scale: A Case Study for Munich. medRxiv (2025). doi:10.1101/2025.09.25.25336633
[8] Jiangzhuo Chen, Stefan Hoops, Henning S Mortveit, Bryan L Lewis, Dustin Machi, Parantapa Bhattacharya, Srinivasan Venkatramanan, Mandy L Wilson, Chris L Barrett, and Madhav V Marathe. 2025. Epihiper-A high performance computational modeling framework to support epidemic science. PNAS Nexus 4, 1 (Jan. 2025), pgae557. doi:10.1093/pnasnexus/pgae557
[9] Nicholson Collier and Michael North. 2013. Parallel agent-based simulation with Repast for High Performance Computing. SIMULATION 89, 10 (Oct. 2013), 1215–1235. https://doi.org/10.1177/0037549712462620
[10] Nicholson Collier and Jonathan Ozik. 2022. Distributed Agent-Based Simulation with Repast4Py. In 2022 Winter Simulation Conference (WSC). 192–206. doi:10.1109/WSC57314.2022.10015389
[11] Pierre Fernique and Christophe Pradal. 2017. AutoWIG: Automatic Generation of Python Bindings for C++ Libraries. doi:10.48550/arXiv.1705.11000 arXiv:1705.11000 [cs.SE] version: 1.
[12] Kit Gallagher, Ioana Bouros, Nicholas Fan, Elizabeth Hayman, Luke Heirene, Patricia Lamirande, Annabelle Lemenuel-Diot, Ben Lambert, David Gavaghan, and Richard Creswell. 2022. Epidemiological agent-based Modelling Software (Epiabm). http://arxiv.org/abs/2212.04937 arXiv:2212.04937 [q-bio].
Betz et al.
[13] John J. Grefenstette, Shawn T. Brown, Roni Rosenfeld, Jay DePasse, Nathan TB Stone, Phillip C. Cooley, William D. Wheaton, Alona Fyshe, David D. Galloway, Anuroop Sriram, Hasan Guclu, Thomas Abraham, and Donald S. Burke. 2013. FRED (A Framework for Reconstructing Epidemic Dynamics): an open-source software system for modeling infectious diseases and control strategies using census-based populations. BMC Public Health 13, 1 (Oct. 2013), 940. doi:10.1186/1471-2458-13-940
[14] Robert Hinch, William J. M. Probert, Anel Nurtay, Michelle Kendall, Chris Wymant, Matthew Hall, Katrina Lythgoe, Ana Bulas Cruz, Lele Zhao, Andrea Stewart, Luca Ferretti, Daniel Montero, James Warren, Nicole Mather, Matthew Abueg, Neo Wu, Olivier Legat, Katie Bentley, Thomas Mead, Kelvin Van-Vuuren, Dylan Feldner-Busztin, Tommaso Ristori, Anthony Finkelstein, David G. Bonsall, Lucie Abeler-Dörner, and Christophe Fraser. 2021. OpenABM-Covid19—An agent-based model for non-pharmaceutical interventions against COVID-19 including contact tracing. PLOS Computational Biology 17, 7 (07 2021), 1–26. doi:10.1371/journal.pcbi.1009146
[15] M. Hucka, A. Finney, H. M. Sauro, H. Bolouri, J. C. Doyle, H. Kitano, A. P. Arkin, B. J. Bornstein, D. Bray, A. Cornish-Bowden, A. A. Cuellar, S. Dronov, E. D. Gilles, M. Ginkel, V. Gor, I. I. Goryanin, W. J. Hedley, T. C. Hodgman, J.-H. Hofmeyr, P. J. Hunter, N. S. Juty, J. L. Kasberger, A. Kremling, U. Kummer, N. Le Novère, L. M. Loew, D. Lucio, P. Mendes, E. Minch, E. D. Mjolsness, Y. Nakayama, M. R. Nelson, P. F. Nielsen, T. Sakurada, J. C. Schaff, B. E. Shapiro, T. S. Shimizu, H. D. Spence, J. Stelling, K. Takahashi, M. Tomita, J. Wagner, and J. Wang. 2003. The systems biology markup language (SBML): a medium for representation and exchange of biochemical network models. Bioinformatics 19, 4 (March 2003), 524–531. doi:10.1093/bioinformatics/btg015
[16] Wenzel Jakob. 2016. pybind11 (v3) — Seamless interoperability between C++ and Python. https://github.com/pybind/pybind11.
[17] Wenzel Jakob. 2022. nanobind: tiny and efficient C++/Python bindings. https://github.com/wjakob/nanobind.
[18] Aaron Jomy, Baidyanath Kundu, Wim Lavrijsen, Alexander Penev, and Vassil Vassilev. 2025. CppInterOp: Advancing Interactive C++ for High Energy Physics. EPJ Web of Conferences 337 (2025), 01165. doi:10.1051/epjconf/202533701165
[19] Karline Soetaert, Thomas Petzoldt, and R. Woodrow Setzer. 2010. Solving Differential Equations in R: Package deSolve. Journal of Statistical Software 33, 9 (2010), 1–25. doi:10.18637/jss.v033.i09
[20] David Kerkmann, Sascha Korf, Khoa Nguyen, Daniel Abele, Alain Schengen, Carlotta Gerstein, Jens Henrik Göbbert, Achim Basermann, Martin J. Kühn, and Michael Meyer-Hermann. 2025. Agent-based modeling for realistic reproduction of human mobility and contact behavior to evaluate test and isolation strategies in epidemic infectious disease spread. Computers in Biology and Medicine 193 (2025), 110269. doi:10.1016/j.compbiomed.2025.110269
[21] Cliff C. Kerr, Robyn M. Stuart, Dina Mistry, Romesh G. Abeysuriya, Katherine Rosenfeld, Gregory R. Hart, Rafael C. Núñez, Jamie A. Cohen, Prashanth Selvaraj, Brittany Hagedorn, Lauren George, Michal Jastrzebski, Amanda S. Izzo, Greer Fowler, Anna Palmer, Dominic Delport, Nick Scott, Sherrie L. Kelly, Caroline S. Bennette, Bradley G. Wagner, Stewart T. Chang, Assaf P. Oron, Edward A. Wenger, Jasmina Panovska-Griffiths, Michael Famulare, and Daniel J. Klein. 2021. Covasim: An agent-based model of COVID-19 dynamics and interventions. PLOS Computational Biology 17, 7 (July 2021), 1–32. doi:10.1371/journal.pcbi.1009149
[22] Sascha Korf, Sophia Johanna Wagner, Gerta Köster, and Martin J. Kühn. 2026. On the effect of missing transmission chain information in agent-based models: Outcomes of superspreading events and workplace transmission. Chaos, Solitons & Fractals 208 (2026), 118179. doi:10.1016/j.chaos.2026.118179
[23] Baidyanath Kundu, Vassil Vassilev, and Wim Lavrijsen. 2023. Efficient and Accurate Automatic Python Bindings with cppyy & Cling. doi:10.48550/arXiv.2304.02712 arXiv:2304.02712 [cs.PL].
[24] Jiawei Liu, Chunqiu Steven Xia, Yuyao Wang, and LINGMING ZHANG. 2023. Is Your Code Generated by ChatGPT Really Correct? Rigorous Evaluation of Large Language Models for Code Generation. In Advances in Neural Information Processing Systems, A. Oh, T. Naumann, A. Globerson, K. Saenko, M. Hardt, and S. Levine (Eds.), Vol. 36. Curran Associates, Inc., 21558–21572. doi:10.52202/075280-0943
[25] Sebastian A. Müller, Michael Balmer, William Charlton, Ricardo Ewert, Andreas Neumann, Christian Rakow, Tilmann Schlenther, and Kai Nagel. 2021. Predicting the effects of COVID-19 related interventions in urban settings by combining activity-based modelling, agent-based simulation, and mobile phone data. PLOS ONE 16, 10 (10 2021), 1–32. doi:10.1371/journal.pone.0259037
[26] Uwe Naumann. 2011. The Art of Differentiating Computer Programs. Society for Industrial and Applied Mathematics. doi:10.1137/1.9781611972078
[27] Rui Pereira, Marco Couto, Francisco Ribeiro, Rui Rua, Jácome Cunha, João Paulo Fernandes, and João Saraiva. 2017. Energy efficiency across programming languages: how do energy, time, and memory relate?. In Proceedings of the 10th ACM SIGPLAN International Conference on Software Language Engineering. ACM, Vancouver BC Canada, 256–267. doi:10.1145/3136014.3136031
[28] Sébastien Picault, Yu-Lin Huang, Vianney Sicard, Sandie Arnoux, Gaël Beaunée, and Pauline Ezanno. 2019. EMULSION: Transparent and flexible multiscale stochastic models in human, animal and plant epidemiology. PLOS Computational Biology 15, 9 (Sept. 2019), e1007342. doi:10.1371/journal.pcbi.1007342
[29] Simon Portegies Zwart. 2020. The ecological impact of high-performance computing in astrophysics. Nature Astronomy 4, 9 (Sept. 2020), 819–822. doi:10.1038/s41550-020-1208-y
[30] Stefan T. Radev, Marvin Schmitt, Valentin Pratz, Umberto Picchini, Ullrich Köthe, and Paul-Christian Bürkner. 2023. Jana: Jointly amortized neural approximation of complex Bayesian models. In Proceedings of the Thirty-Ninth Conference on Uncertainty in Artificial Intelligence (Proceedings of Machine Learning Research, Vol. 216), Robin J. Evans and Ilya Shpitser (Eds.). PMLR, 1695–1706. https://proceedings.mlr.press/v216/radev23a.html
[31] Stefan T. Radev, Marvin Schmitt, Lukas Schumacher, ar Lasse Elsemüller, Valentin Pratz, Yannik Schälte, Ullrich Köthe, and Paul-Christian Bürkner. 2023. BayesFlow: Amortized Bayesian workflows with neural networks. Journal of Open Source Software 8, 89 (2023), 5702. https://doi.org/10.21105/joss.05702
[32] Klara Roebl, Emil Nafis Iftekhar, Kathryn Oliver, Hanna-Tina Fischer, Sebastian Funk, Julia Fitzner, and Johanna Hanefeld. 2026. Developing an Evaluation Framework for Infectious Disease Modelling-to-Policy Pathways: A Qualitative Study Across Five Continents. medRxiv (2026). doi:10.64898/2026.07.22.26358658
[33] Agatha Schmidt, Henrik Zunker, Alexander Heinlein, and Martin J. Kühn. 2026. Graph Neural Network Surrogates to leverage Mechanistic Expert Knowledge towards Reliable and Immediate Pandemic Response. Scientific Reports (2026). https://doi.org/10.1038/s41598-026-39431-5
[34] Christian Schmitt, Sebastian Kuckuk, Frank Hannig, Harald Köstler, and Jürgen Teich. 2014. ExaSlang: A Domain-Specific Language for Highly Scalable Multigrid Solvers. In 2014 Fourth International Workshop on Domain-Specific Languages and High-Level Frameworks for High Performance Computing. 42–51. doi:10.1109/WOLFHPC.2014.11
[35] Yannik Schälte, Emmanuel Klinger, Emad Alamoudi, and Jan Hasenauer. 2022. pyABC: Efficient and robust easy-to-use approximate Bayesian computation. Journal of Open Source Software 7, 74 (June 2022), 4304. doi:10.21105/joss.04304
[36] Claudio Spiess, David Gros, Kunal Suresh Pai, Michael Pradel, Md Rafiqul Islam Rabin, Amin Alipour, Susmit Jha, Prem Devanbu, and Toufique Ahmed. 2024. Calibration and Correctness of Language Models for Code. arXiv:2402.02047 [cs.SE] https://arxiv.org/abs/2402.02047
[37] Dave Bergmann Stryker, Cole. 2023. What is PyTorch? | IBM. https://www.ibm.com/think/topics/pytorch
[38] The iTEAM. 2026. Bayesian Individual-based Compartmental Inference (BICI). https://theiteam.github.io/BICI.html
[39] Pauli Virtanen, Ralf Gommers, Travis E. Oliphant, Matt Haberland, Tyler Reddy, David Cournapeau, Evgeni Burovski, Pearu Peterson, Warren Weckesser, Jonathan Bright, Stéfan J. van der Walt, Matthew Brett, Joshua Wilson, K. Jarrod Millman, Nikolay Mayorov, Andrew R. J. Nelson, Eric Jones, Robert Kern, Eric Larson, C J Carey, Ilhan Polat, Yu Feng, Eric W. Moore, Jake VanderPlas, Denis Laxalde, Josef Perktold, Robert Cimrman, Ian Henriksen, E. A. Quintero, Charles R. Harris, Anne M. Archibald, Antônio H. Ribeiro, Fabian Pedregosa, Paul van Mulbregt, and SciPy 1.0 Contributors. 2020. SciPy 1.0: Fundamental Algorithms for Scientific Computing in Python. Nature Methods 17 (2020), 261–272. doi:10.1038/s41592-019-0686-2
[40] Stefan Widgren, Pavol Bauer, Robin Eriksson, and Stefan Engblom. 2019. SimInf: an R package for data-driven stochastic disease spread simulations. Journal of Statistical Software 91 (2019), 1–42.
[41] Henrik Zunker, René Schmieding, Jan Hasenauer, and Martin J. Kühn. 2027. Efficient numerical computation of traveler states in explicit mobility-based metapopulation models: Mathematical theory and application to epidemics. Mathematics and Computers in Simulation 251 (2027), 798–812. doi:10.1016/j.matcom.2026.08.029
Appendix
Binding text for the simulation function
def simulation(intermed_repr: IntermediateRepresentation) -> str: """ Generate the code for the Simulation class. Not used by every model.
:param intermed_repr: Dataclass holding the model features. :returns: Formatted string representing a part of the bindings.
""" namespace = intermed_repr.namespace
if intermed_repr.simulation is True:
simulation = "&" + namespace + "simulate< " +
ScalarType(intermed_repr)+">
flow_simulation = "&" + namespace +
"flow_simulation<"+ScalarType(intermed_repr)+">
bind_simulation_class_string = "" + namespace + "Simulation"
bind_flowsimulation_class_string = "" + namespace + "FlowSimulation"
bind_simulation_string = ""
Betz et al.
else:
simulation = "&mio::simulate<"+ScalarType(intermed_repr) +
", " + namespace + "Model<"+ScalarType(intermed_repr)+">>"
flow_simulation = "&mio::flow_simulation<"+
namespace + "Model<"+ScalarType(intermed_repr)+">>"
bind_simulation_class_string = "mio::Simulation"
bind_flowsimulation_class_string = "mio::FlowSimulation"
bind_simulation_string = "" +
ScalarType(intermed_repr)+", " + namespace +
"Model<"+ScalarType(intermed_repr)+">>"
sub_string = ""
sub_string += ( "pymio::bind_Simulation<{b_sim}<sub>">(m, "\Simulation");\n\n\t" 'm.def(\n\t\t"simulate", {sim},\n\t\t' 'py::arg("t0"), py::arg("tmax"), py::arg("dt"), py::arg("model"), py::arg("integrator") = py::none(),\n\t\t' "Simulate a {namespace} from t0 to tmax." \n\t\t' ); \n\n\t'
"pymio::bind_ModelNode<{namespace}Model<"+
ScalarType(intermed_repr)+">>(m, "\ModelNode");\n\t"
"pymio::bind_SimulationNode<{namespace}Simulation<>>(m, "\SimulationNode");\n\t"
"pymio::bind_ModelGraph<{namespace}Model<"+
ScalarType(intermed_repr)+">>(m, "\ModelGraph");\n\t"
"pymio::bind_MobilityGraph<{namespace}Simulation<>>(m, "\MobilityGraph");\n\t"
"pymio::bind_GraphSimulation<mio::Graph<mio::SimulationNode<{b_sim}<>>>, mio::MobilityEdge<"+
ScalarType(intermed_repr)+">>(m, "\MobilitySimulation");\n\n\t"
).format( namespace=intermed_repr.namespace, sim=simulation, b_sim=bind_simulation_class_string, sub=bind_simulation_string )
if intermed_repr.is_flowmodel is True:
sub_string += ( "pymio::bind_Flow_Simulation<{b_sim}<"+ScalarType(intermed_repr) + ", mio::FlowSimulation<{sub}>(m, "\FlowSimulation");\n\n\t" 'm.def(\n\t\t"simulate_flows", {flow_sim},\n\t\t' 'py::arg("t0"), py::arg("tmax"), py::arg("dt"), py::arg("model"), py::arg("integrator") = py::none(),\n\t\t' "Simulate a {namespace} with flows from t0 to tmax." \n\t\t' ); \n\n\t'
"pymio::bind_SimulationNode<{namespace}FlowSimulation<>>(m, "\SimulationNode");\n\t"
"pymio::bind_MobilityGraph<{namespace}FlowSimulation<>>(m, "\MobilityGraph");\n\t"
"pymio::bind_GraphSimulation<mio::Graph<mio::SimulationNode<{b_flowsim}<>>>, mio::MobilityEdge<"+
ScalarType(intermed_repr)+">>(m, "\MobilitySimulation");\n\t"
)
.format( namespace=intermed_repr.namespace, flow_sim=flow_simulation, b_sim=bind_simulation_class_string, b_flowsim=bind_flowsimulation_class_string, sub=bind_simulation_string )
return sub_string
Code Snippet 18. Structure to generate binding string to replace the $simulate placeholder.
Parameters, explanations, and average value for sensitivity analysis
| Parameter | Explanation | Average value |
|---|---|---|
| Time in exposed state | 3.335 | |
| Time in infectious, nonsymptomatic state | 2.58916 | |
| Time in infectious, symptomatic state | 6.94547 | |
| Time in severe state | 7.28196 | |
| Time in critical state | 13.066 | |
| Transmission probability on contact | 0.07333 | |
| Relative transmission from infectious, nonsymptomatic | 1.0 | |
| Relative transmission from infectious, symptomatic (nonisolation share) | 0.25 | |
| Share of recovered per nonsymptomatic, infectious | 0.2069 | |
| Share of severe per symptomatic, infectious | 0.07864 | |
| Share of critical per severe | 0.17318 | |
| Share of dead per critical | 0.21718 |
Table 1. Parameters for wild-type SARS-CoV-2 based on [33].