Skip to content

Commit ee2a86f

Browse files
[iss-3202]
Squashed commit of the following: commit 4d3a331 Author: joaquin.f.fernandez <joaquin.f.fernandez@gmail.com> Date: Mon May 11 13:42:15 2026 -0300 Updated example script. commit 048551b Author: joaquin.f.fernandez <joaquin.f.fernandez@gmail.com> Date: Mon May 11 13:40:35 2026 -0300 Moved Python examples and doc. commit 81289f5 Author: joaquin.f.fernandez <joaquin.f.fernandez@gmail.com> Date: Thu May 7 13:34:11 2026 -0300 Updated Python modules. commit 3a58518 Author: joaquin.f.fernandez <joaquin.f.fernandez@gmail.com> Date: Thu May 7 10:56:47 2026 -0300 iPython API examples and docs.
1 parent 208250a commit ee2a86f

6 files changed

Lines changed: 634 additions & 18 deletions

File tree

Lines changed: 312 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,312 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Example script demonstrating autonomous QSS simulation execution from Python.
4+
5+
This script shows how to:
6+
1. Configure environment variables
7+
2. Set up model parameters and annotations
8+
3. Compile and run simulations
9+
4. Process results
10+
11+
Author: QSS Solver Python API
12+
"""
13+
14+
import os
15+
import sys
16+
import logging
17+
from pathlib import Path
18+
19+
# Add the qss_solver module to the Python path
20+
# Adjust this path according to your installation
21+
sys.path.insert(0, '/opt/CIFASIS-CONICET/qss-solver/src/python')
22+
23+
try:
24+
from qss_solver import (
25+
# Simulation functions
26+
compile_model, execute_model, run,
27+
# Model manipulation functions
28+
annotations, set_annotations,
29+
constants, parameters, set_constant, set_parameter, set_constants, set_parameters,
30+
config, set_config,
31+
# Result functions
32+
simulation_log, output_files
33+
)
34+
except ImportError as e:
35+
print(f"Error importing qss_solver modules: {e}")
36+
print("Make sure the qss_solver package is in your Python path")
37+
sys.exit(1)
38+
39+
def setup_environment():
40+
"""
41+
Configure required environment variables for QSS Solver.
42+
43+
Adjust these paths according to your QSS Solver installation.
44+
"""
45+
# Base installation directory
46+
qss_base = "/home/joaquin/work/qss-solver"
47+
48+
# Required environment variables
49+
env_vars = {
50+
'MMOC_BIN': os.path.join(qss_base, 'bin'),
51+
'MMOC_MODELS': os.path.join(qss_base, 'models'),
52+
'MMOC_OUTPUT': os.path.join(qss_base, 'output'),
53+
'MMOC_BUILD': os.path.join(qss_base, 'build')
54+
}
55+
56+
# Set environment variables
57+
for var, value in env_vars.items():
58+
os.environ[var] = value
59+
print(f"Set {var} = {value}")
60+
61+
# Create directories if they don't exist
62+
for var in ['MMOC_OUTPUT', 'MMOC_BUILD']:
63+
path = os.environ[var]
64+
Path(path).mkdir(parents=True, exist_ok=True)
65+
print(f"Ensured directory exists: {path}")
66+
67+
return env_vars
68+
69+
def configure_logging():
70+
"""Configure logging for detailed output."""
71+
logging.basicConfig(
72+
level=logging.INFO,
73+
format='%(asctime)s - %(levelname)s - %(message)s',
74+
handlers=[
75+
logging.StreamHandler(sys.stdout),
76+
logging.FileHandler('simulation_example.log')
77+
]
78+
)
79+
80+
def example_basic_simulation(model_name):
81+
"""
82+
Basic example: compile and run a model with default settings.
83+
84+
Args:
85+
model_name (str): Name of the Modelica model file (without .mo extension)
86+
"""
87+
print(f"\n=== Basic Simulation Example: {model_name} ===")
88+
89+
model_file = f"{model_name}.mo"
90+
91+
# Step 1: Check current model annotations
92+
print("Current model annotations:")
93+
current_ann = annotations(model_file)
94+
if current_ann:
95+
for key, value in current_ann.items():
96+
print(f" {key}: {value}")
97+
else:
98+
print(" No annotations found")
99+
100+
# Step 2: Compile the model
101+
print(f"\nCompiling model: {model_file}")
102+
if compile_model(model_file):
103+
print(" Compilation successful")
104+
else:
105+
print(" Compilation failed")
106+
return False
107+
108+
# Step 3: Run the simulation
109+
print(f"\nRunning simulation: {model_file}")
110+
if execute_model(model_file):
111+
print(" Simulation completed successfully")
112+
else:
113+
print(" Simulation failed")
114+
return False
115+
116+
# Step 4: Get simulation results
117+
print("\nSimulation results:")
118+
log_data = simulation_log(model_name)
119+
if log_data:
120+
for key, value in log_data.items():
121+
print(f" {key}: {value} ms")
122+
123+
output_files_list = output_files(model_name)
124+
print(f"\nOutput files ({len(output_files_list)}):")
125+
for file_path in output_files_list:
126+
print(f" {file_path}")
127+
128+
return True
129+
130+
def example_advanced_configuration(model_name):
131+
"""
132+
Advanced example: modify model parameters and annotations before simulation.
133+
134+
Args:
135+
model_name (str): Name of the Modelica model file (without .mo extension)
136+
"""
137+
print(f"\n=== Advanced Configuration Example: {model_name} ===")
138+
139+
model_file = f"{model_name}.mo"
140+
141+
# Step 1: Read current model parameters and constants
142+
print("Current model parameters:")
143+
try:
144+
current_params = parameters(model_file)
145+
if current_params:
146+
for key, value in current_params.items():
147+
print(f" {key}: {value}")
148+
else:
149+
print(" No parameters found")
150+
except Exception as e:
151+
print(f" Error reading parameters: {e}")
152+
153+
print("\nCurrent model constants:")
154+
try:
155+
current_constants = constants(model_file)
156+
if current_constants:
157+
for key, value in current_constants.items():
158+
print(f" {key}: {value}")
159+
else:
160+
print(" No constants found")
161+
except Exception as e:
162+
print(f" Error reading constants: {e}")
163+
164+
# Step 2: Modify model annotations
165+
new_annotations = {
166+
'startTime': 0.0,
167+
'stopTime': 10.0,
168+
'tolerance': 1e-8,
169+
'stepSize': 1e-4
170+
}
171+
172+
print(f"\nSetting new annotations:")
173+
for key, value in new_annotations.items():
174+
print(f" {key}: {value}")
175+
176+
set_annotations(model_file, new_annotations)
177+
178+
# Step 3: Modify model parameters (example values)
179+
new_parameters = {
180+
'k': 2.5,
181+
'omega': 1.0,
182+
'damping': 0.1
183+
}
184+
185+
print(f"\nSetting new parameters:")
186+
for key, value in new_parameters.items():
187+
print(f" {key}: {value}")
188+
189+
try:
190+
set_parameters(model_file, new_parameters)
191+
except Exception as e:
192+
print(f" Warning: Could not set parameters: {e}")
193+
194+
# Step 4: Run the complete simulation
195+
print(f"\nRunning complete simulation: {model_file}")
196+
success = run(model_file, "-O3") # With optimization flags
197+
198+
if success:
199+
print(" Simulation completed successfully")
200+
201+
# Step 5: Process results
202+
log_data = simulation_log(model_name)
203+
if log_data:
204+
print("\nPerformance metrics:")
205+
for key, value in log_data.items():
206+
print(f" {key}: {value} ms")
207+
else:
208+
print(" Simulation failed")
209+
210+
return success
211+
212+
def example_batch_simulation(model_name, parameter_sets):
213+
"""
214+
Batch simulation example: run multiple simulations with different parameter sets.
215+
216+
Args:
217+
model_name (str): Name of the Modelica model file
218+
parameter_sets (list): List of dictionaries containing parameter sets
219+
"""
220+
print(f"\n=== Batch Simulation Example: {model_name} ===")
221+
222+
model_file = f"{model_name}.mo"
223+
results = []
224+
225+
for i, params in enumerate(parameter_sets):
226+
print(f"\n--- Simulation {i+1}/{len(parameter_sets)} ---")
227+
print(f"Parameters: {params}")
228+
229+
# Set parameters for this run
230+
try:
231+
set_parameters(model_file, params)
232+
except Exception as e:
233+
print(f" Warning: Could not set parameters: {e}")
234+
continue
235+
236+
# Run simulation
237+
success = run(model_file)
238+
239+
if success:
240+
# Collect results
241+
log_data = simulation_log(model_name)
242+
result = {
243+
'run': i+1,
244+
'parameters': params,
245+
'simulation_time': log_data.get('Simulation time', 0) if log_data else 0,
246+
'compilation_time': log_data.get('Compilation time', 0) if log_data else 0
247+
}
248+
results.append(result)
249+
print(f" Success: Sim time = {result['simulation_time']} ms")
250+
else:
251+
print(f" Failed")
252+
253+
# Summary
254+
print(f"\n=== Batch Simulation Summary ===")
255+
print(f"Total runs: {len(parameter_sets)}")
256+
print(f"Successful runs: {len(results)}")
257+
258+
if results:
259+
avg_sim_time = sum(r['simulation_time'] for r in results) / len(results)
260+
avg_comp_time = sum(r['compilation_time'] for r in results) / len(results)
261+
print(f"Average simulation time: {avg_sim_time:.2f} ms")
262+
print(f"Average compilation time: {avg_comp_time:.2f} ms")
263+
264+
return results
265+
266+
def main():
267+
"""Main function demonstrating various simulation scenarios."""
268+
print("QSS Solver Python API - Autonomous Simulation Example")
269+
print("=" * 60)
270+
271+
# Setup
272+
configure_logging()
273+
env_vars = setup_environment()
274+
275+
# Example model names (adjust according to your available models)
276+
# example_models = ["bouncing_ball", "pendulum", "van_der_pol"]
277+
278+
# Choose a model that exists in your models directory
279+
model_name = "bball_downstairs" # Change this to your model
280+
281+
# Check if model file exists
282+
model_path = os.path.join(env_vars['MMOC_MODELS'], f"{model_name}.mo")
283+
if not os.path.exists(model_path):
284+
print(f"Error: Model file not found: {model_path}")
285+
print("Please update the model_name variable to point to an existing model")
286+
return
287+
288+
try:
289+
# Example 1: Basic simulation
290+
example_basic_simulation(model_name)
291+
292+
# Example 2: Advanced configuration
293+
#example_advanced_configuration(model_name)
294+
295+
# Example 3: Batch simulation with different parameters
296+
#parameter_sets = [
297+
# {'k': 1.0, 'damping': 0.1},
298+
# {'k': 2.0, 'damping': 0.2},
299+
# {'k': 3.0, 'damping': 0.3}
300+
#]
301+
#example_batch_simulation(model_name, parameter_sets)
302+
303+
except Exception as e:
304+
print(f"Error during simulation: {e}")
305+
logging.error(f"Simulation error: {e}", exc_info=True)
306+
307+
print("\n" + "=" * 60)
308+
print("Example completed successfully!")
309+
print(f"Check the log file: simulation_example.log")
310+
311+
if __name__ == "__main__":
312+
main()

0 commit comments

Comments
 (0)