New Content for pages/docs/tutorials/python-model.mdx Please replace the entire contents of your python-model.mdx file with the following.
Tutorial: Converting a Python Model
This tutorial provides a step-by-step guide to converting a simulation model written in Python into a Functional Mock-up Unit (FMU) using the Jingongo SDK.
The SDK intelligently packages your local Python model files, uploads them to the Jingongo cloud platform, and manages the remote process of creating a self-contained, high-performance FMU.
Prerequisites
Before you begin, please ensure you have completed the following steps from our "Getting Started" guide:
- Installed the SDK:
pip install jingongo-framework
- Generated and configured your API Key: The
JINGONGO_API_KEY
environment variable must be set.
The Example Python Model
For this tutorial, we will use the sample python_identity_block_model
located in the examples/example_models/
directory of our repository. This is a simple "pass-through" model that demonstrates the required file structure and configuration.
1. The Python Source Code
A Python-based model for Jingongo requires a single model.py
file containing a class named Model
. This class must implement a specific interface that the Jingongo engine can call into.
model.py
(The Model Class)
This file defines the behavior of your simulation. The Model
class holds the model's state and contains initialize
and do_step
methods.
# examples/example_models/python_identity_block_model/model.py
class Model:
"""
A simple pass-through model for the Jingongo Framework.
This class structure is required by the conversion engine.
"""
def __init__(self):
# All inputs, outputs, and parameters must be declared as
# attributes of the class instance.
self.input_value = 0.0
self.output_value = 0.0
self.gain = 1.0 # This is a parameter
def initialize(self):
"""
Called once at the beginning of the simulation to set the
initial state.
"""
# In this simple model, the default values are sufficient.
# No additional initialization is needed.
pass
def do_step(self, dt):
"""
Called at each time step of the simulation. This is where the
core logic of the model resides.
Args:
dt (float): The time step size for the current step.
"""
# The model's logic: output = input * gain
self.output_value = self.input_value * self.gain
2. The Jingongo Configuration File
Just like with C models, the .jingongo.yml file is crucial. It acts as the "manifest" for your model, telling the Jingongo engine which class attributes are inputs, outputs, and parameters.
.jingongo.yml
# examples/example_models/python_identity_block_model/.jingongo.yml
model:
# Basic metadata for your model
model_name: "Python_Identity_Block"
version: "1.0.0"
description: "A simple pass-through model implemented in Python."
language: "python"
# Define the variables the outside world can interact with
inputs:
- name: "input_value" # Must match an attribute in the Model class
type: "Real"
outputs:
- name: "output_value" # Must match an attribute in the Model class
type: "Real"
parameters:
- name: "gain" # Must match an attribute in the Model class
type: "Real"
default: 1.0
The Conversion Script The Python script below orchestrates the entire conversion process. It points the Jingongo SDK to your local model directory, and the SDK handles the rest. This script is available at examples/02_convert_python_model.py in the repository.
# examples/02_convert_python_model.py
import os
import sys
import json
import logging
from pathlib import Path
# Make the SDK importable when running from the repo root
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))
from jingongo import Jingongo
# --- Configuration ---
JINGONGO_API_BASE_URL = "https://jingongo-backend-api-723715926581.us-central1.run.app"
def main():
"""
Demonstrates converting a local Python-based model into an FMU.
"""
print("--- Tutorial: Converting a Python model to an FMU ---")
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
api_key = os.environ.get("JINGONGO_API_KEY")
if not api_key:
print("\n❌ Error: Please set the JINGONGO_API_KEY environment variable.")
return
try:
# 1. Initialize the Jingongo client
client = Jingongo(JINGONGO_API_BASE_URL, api_key, verbose=True)
# 2. Define the path to the local model directory
py_model_path = Path(__file__).parent / "example_models" / "python_identity_block_model"
if not py_model_path.exists():
raise FileNotFoundError(f"❌ Model directory not found: {py_model_path.resolve()}")
print(f"\n🚀 Starting conversion for model at: {py_model_path}")
# 3. Call the core conversion method
# The SDK will zip the directory, upload it, and start the conversion.
# It automatically reads the .jingongo.yml for metadata.
py_job = client.convert_to_fmu(
project_path=py_model_path,
language="python" # We specify the language here
)
print("\n✅ Python Conversion Job Finished!")
print("Backend Response:")
print(json.dumps(py_job, indent=2))
except Exception as e:
print(f"\n❌ An error occurred during conversion: {e}")
if __name__ == "__main__":
main()
How to Run It Make sure your JINGONGO_API_KEY is set in your terminal. Navigate to the root of the repository. Run the script:
python -m examples.02_convert_python_model
You will see the SDK log its progress as it packages and uploads your Python model. The cloud engine will then build it into a high-performance FMU, with real-time status updates appearing in your console.