ovfmi 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ovfmi/__init__.py ADDED
@@ -0,0 +1,30 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Supported Python API for USD-authored FMI co-simulation.
5
+
6
+ Only the names exported here are part of ovfmi's compatibility contract.
7
+ Package submodules are implementation details and may change without notice.
8
+ """
9
+
10
+ from .api import FmiHost
11
+ from .types import (
12
+ AttributeWrite,
13
+ FmiHostConfig,
14
+ InstanceInfo,
15
+ MissingInputPolicy,
16
+ PopulationReport,
17
+ ReadGroup,
18
+ ReadResult,
19
+ )
20
+
21
+ __all__ = [
22
+ "AttributeWrite",
23
+ "FmiHost",
24
+ "FmiHostConfig",
25
+ "InstanceInfo",
26
+ "MissingInputPolicy",
27
+ "PopulationReport",
28
+ "ReadGroup",
29
+ "ReadResult",
30
+ ]
ovfmi/_fmpy_runtime.py ADDED
@@ -0,0 +1,433 @@
1
+ # Adapted from usd_fmi (omni/source/extensions/fmi/source/fmi.usd.runtime)
2
+ # SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
3
+ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+ #
6
+ # Change from upstream: import from local fmi_parser instead of fmi.usd.parser package.
7
+
8
+ from ._parser import FmuParserInstance
9
+ import fmpy
10
+ import os
11
+ import tempfile
12
+ import sys
13
+ from fmpy.fmi1 import FMU1Slave, FMU1Model
14
+ from fmpy.fmi2 import FMU2Slave, FMU2Model
15
+ from fmpy.fmi3 import FMU3Slave, FMU3Model, FMU3ScheduledExecution
16
+ from fmpy.model_description import ModelDescription, ScalarVariable
17
+ from fmpy.simulation import SimulationResult
18
+ import shutil
19
+ import copy
20
+ from pathlib import Path
21
+
22
+ FMPYType = FMU1Slave | FMU2Slave | FMU3Slave | FMU1Model | FMU2Model | FMU3Model | FMU3ScheduledExecution
23
+
24
+
25
+ def fmpy_resolve_model_description_shapes(model_description: ModelDescription, fmu_instance: FMPYType):
26
+ resolved_variables: dict[int, tuple[ScalarVariable, int]] = {}
27
+ for variable in model_description.modelVariables:
28
+ if variable.shape is not None:
29
+ for index, dimension in enumerate(variable.dimensions):
30
+ if dimension.valueReference is not None:
31
+ if dimension.valueReference in resolved_variables:
32
+ _, resolved_value = resolved_variables[dimension.valueReference]
33
+ else:
34
+ refVariable = next(
35
+ (v for v in model_description.modelVariables
36
+ if v.valueReference == dimension.valueReference),
37
+ None,
38
+ )
39
+ if refVariable is None:
40
+ raise Exception(f"Variable {refVariable.name} not found in model description")
41
+ type = refVariable.type
42
+ getter = getattr(fmu_instance, "get" + type)
43
+ resolved_value = getter(vr=[refVariable.valueReference], nValues=1)[0]
44
+ resolved_variables[refVariable.valueReference] = (refVariable, resolved_value)
45
+ shape = list(variable.shape)
46
+ shape[index] = int(resolved_value)
47
+ variable.shape = tuple(shape)
48
+
49
+
50
+ class FmuRuntimeInstance:
51
+ def __init__(self, parser_instance: FmuParserInstance, model_description: ModelDescription, fmu_instance: FMPYType):
52
+ self._parser_instance = parser_instance
53
+ self._model_description = copy.deepcopy(model_description)
54
+ self._fmu_instance = fmu_instance
55
+ self._must_terminate = False
56
+ self._last_successful_time = 0
57
+ self._prev_time = 0
58
+ self._prev_results = []
59
+ self._start_values = {}
60
+ self._structural_parameters = {}
61
+
62
+ def get_parser_instance(self) -> FmuParserInstance:
63
+ return self._parser_instance
64
+
65
+ def get_model_description(self) -> ModelDescription:
66
+ return self._model_description
67
+
68
+ def get_fmu_instance(self) -> FMPYType:
69
+ return self._fmu_instance
70
+
71
+ def set_start_values(self, start_values: dict):
72
+ self._start_values = start_values
73
+
74
+ def destroy(self):
75
+ if self._must_terminate:
76
+ try:
77
+ self._fmu_instance.terminate()
78
+ except Exception as e:
79
+ print(e)
80
+ finally:
81
+ self._fmu_instance.freeInstance()
82
+ self._fmu_instance = None
83
+ self._must_terminate = False
84
+
85
+ @staticmethod
86
+ def find_result_earlier_than(time: float, results: SimulationResult) -> int:
87
+ if len(results) == 0:
88
+ return None
89
+ idx = -1
90
+ for result in results:
91
+ idx = idx + 1
92
+ if result[0] > time:
93
+ idx = idx - 1
94
+ break
95
+ if idx == -1:
96
+ return 0
97
+ return idx
98
+
99
+ def reset(self):
100
+ self._prev_results = []
101
+ self._structural_parameters = {}
102
+ self._last_successful_time = 0
103
+ self._fmu_instance.reset()
104
+ self._must_terminate = False
105
+
106
+ def resume(self):
107
+ pass
108
+
109
+ def _set_variable_values(self, variable: ScalarVariable, values):
110
+ if not isinstance(values, list):
111
+ values = [values]
112
+ if variable.type == "Float32":
113
+ self._fmu_instance.setFloat32([variable.valueReference], values)
114
+ elif variable.type in ("Float64", "Real"):
115
+ setter = getattr(self._fmu_instance, "setFloat64", None)
116
+ if setter is None:
117
+ setter = getattr(self._fmu_instance, "setReal")
118
+ setter([variable.valueReference], values)
119
+ elif variable.type in ("Int32", "Integer"):
120
+ setter = getattr(self._fmu_instance, "setInt32", None)
121
+ if setter is None:
122
+ setter = getattr(self._fmu_instance, "setInteger")
123
+ setter([variable.valueReference], values)
124
+ elif variable.type == "UInt32":
125
+ self._fmu_instance.setUInt32([variable.valueReference], values)
126
+ elif variable.type == "Boolean":
127
+ bool_values = [bool(v) for v in values]
128
+ self._fmu_instance.setBoolean([variable.valueReference], bool_values)
129
+
130
+ def step(self, filename: str, inputs, outputs: list, time: float):
131
+ if self._prev_time > time:
132
+ self._prev_results = []
133
+ self._last_successful_time = 0
134
+ self._fmu_instance.reset()
135
+ self._must_terminate = False
136
+ self._prev_time = time
137
+
138
+ if time - self._last_successful_time == 0:
139
+ return
140
+
141
+ if len(self._prev_results):
142
+ result_idx = self.find_result_earlier_than(time, self._prev_results)
143
+ if result_idx is not None:
144
+ result = self._prev_results[result_idx]
145
+ self._prev_results = self._prev_results[result_idx + 1:]
146
+ return result
147
+
148
+ if self._last_successful_time == 0:
149
+ for variable in self._model_description.modelVariables:
150
+ if (
151
+ variable.causality == "parameter"
152
+ and variable.variability == "fixed"
153
+ and variable.type == "String"
154
+ and variable.name in self._start_values
155
+ ):
156
+ self._fmu_instance.setString([variable.valueReference], [self._start_values[variable.name]])
157
+ if variable.causality == "structuralParameter" and variable.name in self._start_values:
158
+ self._structural_parameters[variable.name] = self._start_values[variable.name]
159
+ self._fmu_instance.fmi3EnterConfigurationMode(self._fmu_instance.component)
160
+ self._fmu_instance.setUInt32([variable.valueReference], [self._start_values[variable.name]])
161
+ self._fmu_instance.fmi3ExitConfigurationMode(self._fmu_instance.component)
162
+
163
+ fmpy_resolve_model_description_shapes(self._model_description, self._fmu_instance)
164
+
165
+ results = fmpy.simulate_fmu(
166
+ filename=filename,
167
+ fmi_type="CoSimulation",
168
+ model_description=self._model_description,
169
+ fmu_instance=self._fmu_instance,
170
+ start_values=self._start_values,
171
+ output=outputs,
172
+ stop_time=time,
173
+ set_stop_time=False,
174
+ terminate=False,
175
+ fmi_call_logger=lambda s: print("[FMI] " + s),
176
+ )
177
+ else:
178
+ needs_configuration_mode = False
179
+ for variable in self._model_description.modelVariables:
180
+ if variable.causality == "structuralParameter" and variable.name in inputs:
181
+ if (variable.name not in self._structural_parameters
182
+ or self._structural_parameters[variable.name] != inputs[variable.name]):
183
+ self._structural_parameters[variable.name] = inputs[variable.name]
184
+ needs_configuration_mode = True
185
+
186
+ if needs_configuration_mode:
187
+ self._fmu_instance.fmi3EnterConfigurationMode(self._fmu_instance.component)
188
+
189
+ try:
190
+ for variable in self._model_description.modelVariables:
191
+ if not variable.name in inputs:
192
+ continue
193
+ if variable.variability == "fixed":
194
+ continue
195
+ if variable.causality == "output":
196
+ continue
197
+ if not needs_configuration_mode and variable.causality == "structuralParameter":
198
+ continue
199
+ self._set_variable_values(variable, inputs[variable.name])
200
+ finally:
201
+ if needs_configuration_mode:
202
+ self._fmu_instance.fmi3ExitConfigurationMode(self._fmu_instance.component)
203
+
204
+ results = fmpy.simulate_fmu(
205
+ filename=filename,
206
+ fmi_type="CoSimulation",
207
+ model_description=self._model_description,
208
+ fmu_instance=self._fmu_instance,
209
+ start_time=self._last_successful_time,
210
+ stop_time=time,
211
+ set_stop_time=False,
212
+ initialize=False,
213
+ terminate=False,
214
+ output=outputs,
215
+ fmi_call_logger=lambda s: print("[FMI] " + s),
216
+ )
217
+
218
+ self._must_terminate = True
219
+ if len(results) > 0:
220
+ self._last_successful_time = results[-1][0]
221
+ result_idx = self.find_result_earlier_than(time, results)
222
+ if result_idx is not None:
223
+ result = results[result_idx]
224
+ self._prev_results = results[result_idx + 1:]
225
+ return result
226
+ else:
227
+ self._last_successful_time = time
228
+ return None
229
+
230
+
231
+ class FmuRuntimeExtractedFMU:
232
+ def __init__(self, fmu_location: str):
233
+ self._unzip_fmu(fmu_location)
234
+ self._runtime_fmus: list[FmuRuntimeInstance] = []
235
+
236
+ def get_runtime_instances(self) -> list[FmuRuntimeInstance]:
237
+ return self._runtime_fmus
238
+
239
+ def get_unzip_dir(self) -> str:
240
+ return self._unzip_dir
241
+
242
+ def destroy(self):
243
+ for instance in self._runtime_fmus:
244
+ instance.destroy()
245
+ self._runtime_fmus.clear()
246
+ try:
247
+ if self._should_delete_unzip_directory:
248
+ shutil.rmtree(self._unzip_dir)
249
+ finally:
250
+ self._unzip_dir = None
251
+ self._model_description = None
252
+
253
+ def _unzip_fmu(self, fmu_location: str):
254
+ self._fmu_location = fmu_location
255
+ self._should_delete_unzip_directory = False
256
+ if os.path.isdir(self._fmu_location):
257
+ self._unzip_dir = self._fmu_location
258
+ else:
259
+ unzipdir = tempfile.mkdtemp()
260
+ if sys.platform.startswith("win") and "~" in unzipdir:
261
+ import ntpath
262
+ unzipdir = ntpath.realpath(unzipdir)
263
+ try:
264
+ self._unzip_dir = unzipdir
265
+ fmpy.extract(filename=self._fmu_location, unzipdir=unzipdir)
266
+ except Exception as e:
267
+ print(e)
268
+ return
269
+ self._should_delete_unzip_directory = True
270
+ self._model_description = fmpy.read_model_description(filename=self._unzip_dir)
271
+ self._add_bundled_windows_binary_if_needed()
272
+ print(f"fmu guid={self._model_description.guid}")
273
+ print(f"fmu model={self._model_description.coSimulation.modelIdentifier}")
274
+
275
+ def _add_bundled_windows_binary_if_needed(self):
276
+ if not sys.platform.startswith("win"):
277
+ return
278
+ if self._model_description.coSimulation is None:
279
+ return
280
+
281
+ model_identifier = self._model_description.coSimulation.modelIdentifier
282
+ platform_dir = (
283
+ "win64"
284
+ if str(self._model_description.fmiVersion).startswith("2")
285
+ else "x86_64-windows"
286
+ )
287
+ expected = (
288
+ Path(self._unzip_dir)
289
+ / "binaries"
290
+ / platform_dir
291
+ / f"{model_identifier}.dll"
292
+ )
293
+ if expected.exists():
294
+ return
295
+
296
+ staged = self._find_staged_windows_fmu_binary(model_identifier)
297
+ if staged is None:
298
+ return
299
+
300
+ augmented_dir = Path(tempfile.mkdtemp(prefix="ov_fmi_"))
301
+ shutil.copytree(self._unzip_dir, augmented_dir, dirs_exist_ok=True)
302
+ target = (
303
+ augmented_dir
304
+ / "binaries"
305
+ / platform_dir
306
+ / f"{model_identifier}.dll"
307
+ )
308
+ target.parent.mkdir(parents=True, exist_ok=True)
309
+ shutil.copy2(staged, target)
310
+
311
+ if self._should_delete_unzip_directory:
312
+ shutil.rmtree(self._unzip_dir)
313
+ self._unzip_dir = str(augmented_dir)
314
+ self._should_delete_unzip_directory = True
315
+ print(f"Using staged Windows FMU binary: {staged}")
316
+
317
+ def _find_staged_windows_fmu_binary(self, model_identifier: str) -> Path | None:
318
+ repo_root = Path(__file__).resolve().parent.parent
319
+ fmu_name = Path(self._fmu_location).name
320
+ candidates = []
321
+ for config in ("Release", "RelWithDebInfo", "Debug"):
322
+ candidates.append(
323
+ repo_root
324
+ / "build"
325
+ / config
326
+ / "fmus"
327
+ / fmu_name
328
+ / "binaries"
329
+ / "x86_64-windows"
330
+ / f"{model_identifier}.dll"
331
+ )
332
+ candidates.append(
333
+ repo_root
334
+ / "build"
335
+ / config
336
+ / "fmus"
337
+ / fmu_name
338
+ / "binaries"
339
+ / "win64"
340
+ / f"{model_identifier}.dll"
341
+ )
342
+ candidates.append(repo_root / "build" / config / f"{model_identifier}.dll")
343
+
344
+ for candidate in candidates:
345
+ if candidate.exists():
346
+ return candidate
347
+ return None
348
+
349
+ def add_instance(self, parser_instance: FmuParserInstance):
350
+ if not parser_instance.enabled:
351
+ return
352
+ fmu_instance = fmpy.instantiate_fmu(
353
+ unzipdir=self._unzip_dir, model_description=self._model_description
354
+ )
355
+ runtime_instance = FmuRuntimeInstance(
356
+ parser_instance=parser_instance,
357
+ fmu_instance=fmu_instance,
358
+ model_description=self._model_description,
359
+ )
360
+ self._runtime_fmus.append(runtime_instance)
361
+
362
+
363
+ class FMIRuntimeInputHead:
364
+ """Abstract base: implement to feed USD/external values into FMU inputs."""
365
+ def cache_connections(self, instance: FmuRuntimeInstance): pass
366
+ def empty_cache_for(self, instance: FmuRuntimeInstance): pass
367
+ def write_start_values(self, instance: FmuRuntimeInstance): pass
368
+ def get_inputs_for(self, instance: FmuRuntimeInstance): pass
369
+
370
+
371
+ class FMIRuntimeOutputTail:
372
+ """Abstract base: implement to consume FMU outputs and write to USD/renderer."""
373
+ def cache_connections(self, instance: FmuRuntimeInstance): pass
374
+ def empty_cache_for(self, instance: FmuRuntimeInstance): pass
375
+ def write_outputs(self, instance: FmuRuntimeInstance, outputs, result): pass
376
+ def get_outputs_for(self, instance: FmuRuntimeInstance): pass
377
+
378
+
379
+ class FMIRuntime:
380
+ def __init__(self, runtime_input_head: FMIRuntimeInputHead, runtime_output_tail: FMIRuntimeOutputTail):
381
+ self._runtime_fmus: dict[str, FmuRuntimeExtractedFMU] = {}
382
+ self._runtime_input_head = runtime_input_head
383
+ self._runtime_output_tail = runtime_output_tail
384
+
385
+ def init(self, parser_instances: dict):
386
+ for parser_instance in parser_instances.values():
387
+ # Check if this is an SSP instance (tagged by _deserialise_instances)
388
+ is_ssp = getattr(parser_instance, '_is_ssp', False)
389
+ if is_ssp:
390
+ from ._ssp_runtime import SspRuntimeExtracted # noqa: PLC0415
391
+ if self._runtime_fmus.get(parser_instance.fmu) is None:
392
+ self._runtime_fmus[parser_instance.fmu] = SspRuntimeExtracted(parser_instance.fmu)
393
+ self._runtime_fmus[parser_instance.fmu].add_instance(parser_instance)
394
+ else:
395
+ if self._runtime_fmus.get(parser_instance.fmu) is None:
396
+ self._runtime_fmus[parser_instance.fmu] = FmuRuntimeExtractedFMU(parser_instance.fmu)
397
+ self._runtime_fmus[parser_instance.fmu].add_instance(parser_instance)
398
+
399
+ def resume(self):
400
+ for runtime_fmu in self._runtime_fmus.values():
401
+ for instance in runtime_fmu.get_runtime_instances():
402
+ self._runtime_input_head.empty_cache_for(instance)
403
+ self._runtime_input_head.cache_connections(instance)
404
+ self._runtime_input_head.write_start_values(instance)
405
+ self._runtime_output_tail.empty_cache_for(instance)
406
+ self._runtime_output_tail.cache_connections(instance)
407
+ instance.resume()
408
+
409
+ def step(self, time: float):
410
+ for runtime_fmu in self._runtime_fmus.values():
411
+ for instance in runtime_fmu.get_runtime_instances():
412
+ inputs = self._runtime_input_head.get_inputs_for(instance)
413
+ outputs = self._runtime_output_tail.get_outputs_for(instance)
414
+ result = instance.step(
415
+ filename=runtime_fmu.get_unzip_dir(),
416
+ inputs=inputs,
417
+ outputs=outputs,
418
+ time=time,
419
+ )
420
+ if result is not None:
421
+ self._runtime_output_tail.write_outputs(instance, outputs, result)
422
+
423
+ def reset(self):
424
+ for runtime_fmu in self._runtime_fmus.values():
425
+ for instance in runtime_fmu.get_runtime_instances():
426
+ self._runtime_input_head.empty_cache_for(instance)
427
+ self._runtime_output_tail.empty_cache_for(instance)
428
+ instance.reset()
429
+
430
+ def destroy(self):
431
+ for runtime_fmu in self._runtime_fmus.values():
432
+ for instance in runtime_fmu.get_runtime_instances():
433
+ instance.destroy()