# CoFmuPy: A Python Framework for Rapid Prototyping of FMI-based Digital Twins

Corentin Friedrich, Andrés Lombana, Jérôme Fasquel, Charlie Schlick, Nora

Bennani, Mouhcine Mendil

## ► To cite this version:

Corentin Friedrich, Andrés Lombana, Jérôme Fasquel, Charlie Schlick, Nora Bennani, et al. CoFmuPy: A Python Framework for Rapid Prototyping of FMI-based Digital Twins. The 2nd International Conference on Engineering Digital Twins, Oct 2025, Grand Rapids, Michigan, USA, United States. hal-05326255v2

HAL Id: hal-05326255

https://hal.science/hal-05326255v2

Submitted on 15 Dec 2025

HAL is a multi-disciplinary open access
archive for the deposit and dissemination of sci-
entific research documents, whether they are pub-
lished or not. The documents may come from
teaching and research institutions in France or
abroad, or from public or private research centers.

L'archive ouverte pluridisciplinaire HAL, est
destinée au dépôt et à la diffusion de documents
scientifiques de niveau recherche, publiés ou non,
émanant des établissements d'enseignement et de
recherche français ou étrangers, des laboratoires
publics ou privés.

<figure><img src="image_1.png" /></figure>
# CoFmuPy: A Python Framework for Rapid Prototyping of
FMI-based Digital Twins

**Coretin Friedrich**†

IRT Saint Exupéry
Toulouse, France

**Andrés Lombana**†

IRT Saint Exupéry
Toulouse, France

**Jérôme Fasquel**†

IRT Saint Exupéry
Toulouse, France

**Charlie Schlick**

IRT Saint Exupéry
Toulouse, France

**Nora Bennani**

IRT Saint Exupéry
Toulouse, France

**Mouhcine Mendil**†

IRT Saint Exupéry
Toulouse, France

†Equal contribution to the conception, development and writing of this work.

## Abstract

Industry 4.0 is driving a paradigm shift in manufacturing, aerospace and other sectors. *Digital Twins* (DTs) are a cornerstone of this transformation, offering real-time insights through data-driven simulations of physical systems. While standards like *Functional Mock-up Interface* (FMI) facilitate interoperability, there remains a lack of flexible, research-oriented tools that support rapid prototyping and unified integration of *Artificial Intelligence* (AI) components into DTs. To address this gap, we introduce CoFmuPy, an extensible open-source platform-independent solution in Python that supports FMI standards for seamless co-simulation and rapid development of Proof of Concept DT applications. CoFmuPy integrates a coordinator for efficient model orchestration and co-simulation, a communication module, and data storage capabilities for long-term data management and analysis. We briefly illustrate CoFmuPy's application through a case study from the European Project HECATE<fnref n="1" />, which involves an AI-powered DT for efficient battery health monitoring in a hybrid aircraft. Source code, documentation and demos are available at https://github.com/IRT-Saint-Exupery/CoFmuPy.

**Keywords:** Digital Twin, Simulation, Co-simulation, FMI, FMU, Master, Synchronization, Prototyping, Machine Learning, Artificial Intelligence, Python, Open-source

## 1 Introduction

*Digital Twins* (DTs) have gathered significant interest in recent years, particularly in manufacturing, energy and aerospace domains [1]. In the current work, we define a DT as a virtual replica of a physical system that leverages digital technologies to create a dynamic, real-time representation. This enables data and model-driven decision-making and optimization through bi-directional interaction between the physical and virtual environments, facilitating monitoring, analysis, and feedback.

Accurately capturing the intricacies of complex physical systems is the primary challenge in developing a reliable DT, as the behavior of such systems often defies straightforward modeling and simulation. Co-simulating models from multiple domains and heterogeneous tools [2] is then crucial to achieve an accurate representation from a DT. Among the widely used standards for co-simulation is *Functional Mock-up Interface* (FMI) [3], which provides a standardized way to share and co-simulate unitary models in the form of *Functional Mock-up Units* (FMU).

<footnote n="1">¹https://hecate-project.eu/</footnote>
Existing DT solutions range from proprietary platforms to open-source tools. Commercial products such as Ansys TwinBuilder<fnref n="2" /> and Dassault Systèmes 3DEXPERIENCE<fnref n="3" /> offer robust simulation capabilities, tight integration with CAD systems, and advanced analytics, targeting physical systems and manufacturing environments. On the open-source side, INTO-CPS/Maestro and OMSimulator are mature co-simulation engines implemented in Java and C++, respectively, with bindings to multiple programming languages. INTO-CPS [4] offers a comprehensive Cyber-Physical Systems (CPS) toolchain, incorporating advanced master algorithms, hierarchical FMUs, and support for distributed co-simulation. OMSimulator [5] targets large-scale composite models based on the System Structure and Parameterization (SSP) standard, provides multiple algebraic loop solvers, and includes scripting interfaces in Lua and Python. A lighter-weight alternative is PyFMI [6], a Python-based environment primarily focused on FMU execution, often used together with Assimulo [7] for numerical integration of Ordinary Differential Equations (ODEs) within a single FMU.

This landscape illustrates the diversity of approaches to co-simulation and DT development, ranging from comprehensive industrial platforms to lightweight Python libraries. Within this context, we introduce CoFmuPy, a complementary solution designed to combine lightweight deployment with Python's flexibility while supporting the core requirements of DT prototyping. In particular, CoFmuPy provides:

1. *Open and platform independence*: Portable, open-source, and Python-based. 2. *Comprehensive FMI support*: Execution and management of FMUs compliant with the FMI standard. 3. *Integrated and extensible orchestration*: Unified coordination of co-simulation, algebraic loops resolution, distributed data exchange, structured results storage, and extensible interoperability with external co-simulation tools. 4. *Native Artificial Intelligence (AI) and Python interoperability*: Direct execution of Python functions and AI frameworks within the co-simulation loop, avoiding FMU export/import overhead during iterative development. 5. *Communication with the Physical Twin (PT)*: Acquisition from remote physical sensors and structured transfer to the DT. 6. *Simplicity of use*: Lightweight interface and clear documentation.

## 2 Architecture and Design of CoFmuPy

CoFmuPy leverages the FMI standard to enable seamless integration of heterogeneous simulation models exported from different tools as FMUs, while Python's ecosystem accelerates the development of orchestration logic, interface layers, and AI components. Its architecture relies on three critical components: the *co-simulation master* where the master algorithm manages the simulation of inter-operating FMUs, a *communication component* handling data streams from and to the physical twin, and a *storage element* to keep track of the simulated and observed data. Each of these blocks plays a unique role in facilitating efficient co-simulation and data exchange between the digital and physical twins.

### 2.1 Master Component for Co-simulation

The *co-simulation* component is the core element of the simulation environment, using FMUs and a master algorithm to manage the interactions of the various subsystems and ensuring numerical stability. The modularity brought by the use of FMU enables different subsystems, potentially developed in diverse simulation tools, to interoperate seamlessly within the DT framework.

On top of the FMPy library [8], CoFmuPy introduces a high-level Python master class that implements multiple co-simulation algorithms. The master algorithm orchestrates the execution of FMUs, synchronizing their interactions to ensure that all submodels operate coherently to produce a reliable system-level simulation. It handles subsystem initialization, manages time stepping, and resolves algebraic loops<fnref n="4" />.

<footnote n="2">²Ansys TwinBuilder: https://www.ansys.com/products/digital-twin/ansys-twin-builder</footnote>

<footnote n="3">³Dassault Systèmes 3DEXPERIENCE: https://www.3ds.com/3dexperience/</footnote>

<footnote n="4">⁴Algebraic loops in co-simulation refer to cyclic dependencies between component outputs and inputs that must be resolved at each time step.</footnote>
CoFmuPy is designed to either integrate existing master orchestrators from other co-simulation tools or to operate with its native implementation, enabling users to select orchestration strategies that best fit their requirements.

The CoFmuPy-native master supports both Jacobi and Gauss-Seidel co-simulation approaches. It relies on a coupling graph constructed by the coordinator (see Section 2.4) to automatically detects algebraic loops, and resolves them using fixed-point schemes built on top of FMPy. Initialization is performed through a fixed-point solve to ensure a consistent starting state. Beyond the native master, CoFmuPy also enables integration of multidisciplinary co-simulation platforms with Python APIs, such as Gemseo [9] and OMSimulator, which provide advanced FMI-based orchestration capabilities. Illustrative examples are available in the online documentation.

In addition, CoFmuPy provides a Python FMU proxy: a lightweight Python class replicating the FMI co-simulation interface while executing native Python code. This enables rapid integration of AI models (e.g., PyTorch, TensorFlow, JAX) as well as simple logical components (e.g., sums, switches) without FMU packaging, while maintaining interoperability with standard FMUs. The approach leverages Python's rich ecosystem of libraries and performance optimizations through hardware acceleration (e.g., GPU), facilitating experimentation with diverse AI tools throughout the entire model life-cycle (training, inference, monitoring, etc.). Components can subsequently be exported as FMUs using tools such as PythonFMU [10] and unifmu [11] for cross-tool deployment, enabling hybrid AI-physics co-simulation within a unified framework.

## 2.2 Communication Block for Data Stream Management

To support reliable and low-latency data streaming, communication needs to employ robust messaging protocols capable of handling heterogeneous data types, such as sensor measurements, control signals, and metadata. Fast and reliable data exchange is critical for high-fidelity simulations and real-time control. Commonly used solutions in DTs include MQTT, RabbitMQ, AMQP, OPC UA, Kafka, and HTTP RESTful APIs.

CoFmuPy implements a communication interface based on Apache Kafka<fnref n="5" />, acting as a producer/consumer system for communication with the PT. Kafka has numerous advantages for DT platforms, such as scalability, high throughput, and low latency. The communication block is designed to handle the bidirectional data streams between the DT and its physical counterpart. It is responsible for receiving sensor data from the physical twin and transmitting control or actuation commands back, ensuring that the DT remains an accurate and timely representation of the real-world system. In addition, CoFmuPy provides an offline mode for development and testing using post-hoc tabular data, such as time series stored in local files.

By default, the payload of Kafka messages in CoFmuPy is structured as timestamp-indexed records, where each entry corresponds to a specific state variable or data stream. These variables are assigned to the inputs or outputs of local simulated subsystems through the coordinator and the user-defined configuration file.

More generally, CoFmuPy's modular design enables advanced users to implement custom communication interfaces by subclassing the base data stream management API. Alternative messaging systems like RabbitMQ, or proprietary protocols, can be easily integrated in CoFmuPy.

## 2.3 Storage Component

The storage component is essential for managing the substantial data generated from both the PT's observations and the DT's simulations. This component provides a centralized repository for storing various data types, including historical observation data, simulation outputs, model parameters, and interaction logs. The component allows for long-term tracking of both simulated and observed data, facilitating iterative improvements and optimization.

As an easy-to-use prototyping tool, CoFmuPy offers straightforward local data storage in separate log files that requires no additional cloud services or complex local setups. Following the documentation, users can also create their own storage component.

<footnote n="5">⁵Apache Kafka: https://kafka.apache.org/</footnote>
## 2.4 The Coordinator: Orchestrating the DT Framework

The Coordinator is the administration unit that supervises the three blocks aforementioned to create a unified DT environment. The Coordinator plays a multifaceted role. First, it is responsible for the instantiation of the different blocks based on configuration files provided by the user at start-up. During operation, its main role is to control the three components and the interactions between them: run the co-simulation steps, transfer data between the blocks, handle what data is streamed and stored, define actuation to send to the PT, etc. Figure 1 gives an overview of the framework architecture.

<figure><img src="image_2.png" /><figcaption>Figure 1: Overview of CoFmuPy framework architecture</figcaption></figure>

```json
"fmus": [{"id":"S1","path":"source.fmu"},
         {"id":"R","path":"resistor.fmu"}],
"connections": [{
  "source": {"id":"S1","variable":"V","unit":"V"},
  "target": {"id":"R1","variable":"V","unit":"V"}
}]
```

### Example of JSON Configuration File

The CoFmuPy configuration file, written in JSON, specifies the FMUs involved (IDs, paths, step sizes), the connections between components (defining data flow), and global settings (e.g., co-simulation method, graph formatting). This structure enables flexible and extensible simulation setups. A detailed description of the configuration file structure and a guide for building it are provided in the online documentation.

Once the configuration file is defined, the coordinator can be instantiated and executed. The following code snippet illustrates a minimal example of how to initialize the coordinator and run the co-simulation:

```python
from cofmpy import Coordinator

config_path = "<path_to_config_file.json>"
coordinator = Coordinator() # Instantiation
coordinator.start(config_path) # Start services
coordinator.run_simulation(step_size=0.05, end_time=10)
```
Behind the scenes, the coordinator parses the configuration file to construct the coupling graph that represents the system architecture. It loads the specified FMUs (and proxies) and connects them according to the defined topology. If external data streams are configured, such as local files or remote Kafka endpoints, the coordinator automatically launches the corresponding services and routes data to the appropriate destination. During each co-simulation time step, algebraic loops are detected and handled, outputs are propagated through the system, and all relevant variables are logged. Once the simulation reaches the specified end time, the results are returned to the user for further analysis.

In addition, CoFmuPy provides functionality to visualize the underlying dependency graph constructed from the configuration file, to better understand and verify the data and control flow between FMUs. To further simplify high-level interaction with the simulation environment, a graphical user interface is currently under development.

## 3 Application: AI-Powered DT for Battery Systems in Hybrid Aircraft

As part of the HECATE European project, CoFmuPy has been applied to develop a DT for the efficient monitoring of a lithium-ion battery embedded in a hybrid-electric aircraft. The DT continuously estimates key indicators such as *State of Health* (SoH), *State of Charge* (SoC), and power output to enable predictive maintenance, anomaly detection, and safe power management strategies during flight.

In this use case, the PT is implemented as a software oracle that emulates the real battery system and streams telemetry data (voltage, current, etc.) via Kafka into the co-simulation. Due to model calibration issues, the DT may drift from the battery's actual behavior over time. To mitigate this, an AI-based discrepancy model is trained on telemetry data and DT results to improve the DT's SoH estimates. During operation, telemetry continuously informs the model, which adjusts the SoH and other outputs to compensate for biases and maintain alignment with the physical battery.

The high-level architecture, shown in Figure 2, integrates physical models with AI-based discrepancy models within CoFmuPy's simulation loop.

<figure><img src="image_3.png" /><figcaption>Figure 2: Overview of the AI-powered DT for battery system health monitoring in the HECATE project.</figcaption></figure>

A key challenge in this setup lies in rapidly iterating on the discrepancy correction problem using different AI models and approaches, while leveraging hardware acceleration and handling remote PT data exchange seamlessly. CoFmuPy facilitates this by allowing experimental models to be integrated without the immediate overhead of exporting them as FMUs, and by providing communication blocks that buffer telemetry streams and align them with the simulation timeline.
In our workflow, the offline mode was first used to replay historical mission profiles from the PT, generating a dataset for training models that learn to correct residual discrepancies between simulated and emulated system behaviors. Candidate models were then seamlessly integrated into the co-simulation environment through Python FMU proxies for systematic validation and comparison. With CoFmuPy's compliance with the FMI standard and its modular architecture, this process required no changes to the coordinator logic. Once the best-performing AI model was identified, it was exported as FMU using PythonFMU and deployed in the co-simulation.

The co-simulation is entirely defined through a JSON configuration file, making the setup declarative, reproducible, and easy to modify. This allows to quickly iterate on different configurations (such as swapping FMU versions or enabling/disabling the AI component) without altering core code.

Overall, CoFmuPy enables research-driven prototyping where system architectures and model components are reconfigured frequently. Its abstraction of communication and orchestration details reduces the implementation effort required to analyze results.

# 4 Conclusion

This study presents CoFmuPy, a versatile framework that supports the creation of DTs by combining co-simulation consistent with FMI standard, data communication with low-latency streaming methods, data persistence, visualization capabilities and AI workflow integration. Its open-source nature, Python-based implementation, and modular architecture lower barriers to entry, making it well suited for fast prototyping, research and development of DTs. In particular, CoFmuPy's features enable seamless coupling of co-simulation with AI model prototyping, supporting hybrid AI-physics workflows and accelerating experimentation across the entire model lifecycle.

CoFmuPy currently executes in Python, constraining its applicability in hard real-time contexts due to the absence of deterministic scheduling and low-latency execution support. Moreover, while several co-simulation groups can operate independently and exchange data, a fully distributed execution solution would require a high-level orchestrator such as Maestro [4].

Future work will leverage CoFmuPy's modularity to expand orchestration to improve stability, optimize execution, and extend seamless support for several orchestration backends.

# 5 Acknowledgment

This work is part of the HECATE project, funded by the European Union under Grant Agreement no. 101101961. The project receives support from the Clean Aviation Joint Undertaking and its Members.

# References

[1] F. Tao, B. Xiao, Q. Qi, J. Cheng, and P. Ji, "Digital twin modeling," *Journal of Manufacturing Systems*, vol. 64, pp. 372-389, 2022.

[2] L. I. Hatledal, A. Styve, G. Hovland, and H. Zhang, "A language and platform independent co-simulation framework based on the functional mock-up interface," *IEEE Access*, vol. 7, pp. 109328-109339, 2019.

[3] T. Blochwitz, M. Otter, M. Arnold, C. Bausch, C. Clauß, H. Elmqvist, A. Junghanns, J. Mauss, M. Monteiro, T. Neidhold et al., "The functional mockup interface for tool independent exchange of simulation models," in *Proceedings of the 8th international Modelica conference*. Linköping University Press, 2011, pp. 105-114.

[4] C. Thule, K. Lausdahl, C. Gomes, G. Meisl, and P. G. Larsen, "Maestro: the into-cps co-simulation framework," *Simulation Modelling Practice and Theory*, vol. 92, pp. 45-61, 2019.
[5] L. A. Ochel, R. Braun, B. Thiele, A. Asghar, L. Buffoni, M. Eek, P. Fritzson, D. Fritzson, S. Horkeby, R. Hällquist et al., "Omsimulator-integrated fmi and tlm-based co-simulation with composite model editing and ssp." in *Modelica*, 2019, pp. 157–007.

[6] C. Andersson, J. Åkesson, and C. Führer, "Pyfmi: A python package for simulation of coupled dynamic models with the functional mock-up interface," 2016.

[7] C. Andersson, C. Führer, and J. Åkesson, "Assimulo: A unified framework for ode solvers," *Mathematics and Computers in Simulation*, vol. 116, pp. 26–43, 2015.

[8] Dassault Systèmes, "FMPy: A python library for working with functional mock-up units (FMUs)," 2017. [Online]. Available: https://github.com/CATIA-Systems/FMPy

[9] F. Gallard, C. Vanaret, D. Guénot, V. Gachelin, R. Lafage, B. Pauwels, P.-J. Barjhoux, and A. Gazaix, "Gems: A python library for automation of multidisciplinary design optimization process generation," in *2018 AIAA/ASCE/AHS/ASC Structures, Structural Dynamics, and Materials Conference*, 2018.

[10] L. I. Hatledal, F. Collonval, and H. Zhang, "Enabling python driven co-simulation models with pythonfmu," in *Proceedings of the 34th International ECMS-Conference on Modelling and Simulation-ECMS 2020*. ECMS European Council for Modelling and Simulation, 2020.

[11] C. M. Legaard, D. Tola, T. Schranz, H. D. Macedo, and P. G. Larsen, "A universal mechanism for implementing functional mock-up units," in *11th International Conference on Simulation and Modeling Methodologies, Technologies and Applications*, ser. SIMULTECH 2021, Virtual Event, 2021, pp. 121–129.