pythonfmu3 0.3.3__py3-none-any.whl → 1.0.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.
- pythonfmu3/_version.py +1 -1
- pythonfmu3/builder.py +96 -24
- pythonfmu3/fmi3slave.py +80 -40
- pythonfmu3/modelexchange.py +17 -2
- pythonfmu3/osutil.py +34 -9
- pythonfmu3/pythonfmu-export/CMakeLists.txt +36 -4
- pythonfmu3/pythonfmu-export/generate_shim.py +88 -0
- pythonfmu3/pythonfmu-export/src/CMakeLists.txt +41 -13
- pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_common.hpp +3 -0
- pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_cs.cpp +20 -10
- pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_cs.hpp +20 -10
- pythonfmu3/pythonfmu-export/src/cppfmu/fmi_functions.cpp +16 -14
- pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.cpp +570 -570
- pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.hpp +30 -17
- pythonfmu3/pythonfmu-export/src/shim/fmi3_forwarders.cpp +612 -0
- pythonfmu3/pythonfmu-export/src/shim/shim_loader.cpp +157 -0
- pythonfmu3/pythonfmu-export/src/shim/shim_loader.hpp +29 -0
- pythonfmu3/resources/binaries/x86_64-linux/libpythonfmu-backend.so +0 -0
- pythonfmu3/resources/binaries/x86_64-linux/libpythonfmu-export.so +0 -0
- pythonfmu3/resources/binaries/x86_64-windows/pythonfmu-export.dll +0 -0
- pythonfmu3/tests/data/fmi3_host.c +31 -0
- pythonfmu3/tests/fmi3_ctypes_driver.py +137 -0
- pythonfmu3/tests/slaves/pythonslave_arraytypes.py +80 -0
- pythonfmu3/tests/test_builder.py +48 -2
- pythonfmu3/tests/test_docs.py +70 -61
- pythonfmu3/tests/test_integration.py +106 -0
- pythonfmu3/tests/test_non_python_host.py +75 -0
- pythonfmu3/tests/test_osutil.py +23 -0
- pythonfmu3/tests/test_variables.py +1 -1
- pythonfmu3/tests/test_wrapper_ctypes.py +61 -0
- pythonfmu3/variables.py +72 -47
- {pythonfmu3-0.3.3.dist-info → pythonfmu3-1.0.0.dist-info}/METADATA +61 -25
- {pythonfmu3-0.3.3.dist-info → pythonfmu3-1.0.0.dist-info}/RECORD +37 -26
- {pythonfmu3-0.3.3.dist-info → pythonfmu3-1.0.0.dist-info}/WHEEL +1 -1
- {pythonfmu3-0.3.3.dist-info → pythonfmu3-1.0.0.dist-info}/entry_points.txt +0 -0
- {pythonfmu3-0.3.3.dist-info → pythonfmu3-1.0.0.dist-info}/licenses/LICENSE +0 -0
- {pythonfmu3-0.3.3.dist-info → pythonfmu3-1.0.0.dist-info}/top_level.txt +0 -0
|
@@ -280,6 +280,57 @@ def test_integration_get(tmp_path):
|
|
|
280
280
|
model.terminate()
|
|
281
281
|
model.freeInstance()
|
|
282
282
|
|
|
283
|
+
@pytest.mark.integration
|
|
284
|
+
def test_integration_get_array(tmp_path):
|
|
285
|
+
script_file = Path(__file__).parent / "slaves/pythonslave_arraytypes.py"
|
|
286
|
+
fmu = FmuBuilder.build_FMU(script_file, dest=tmp_path, needsExecutionTool="false")
|
|
287
|
+
assert fmu.exists()
|
|
288
|
+
|
|
289
|
+
md = fmpy.read_model_description(fmu)
|
|
290
|
+
unzip_dir = fmpy.extract(fmu)
|
|
291
|
+
|
|
292
|
+
model = fmpy.fmi3.FMU3Slave(
|
|
293
|
+
guid=md.guid,
|
|
294
|
+
unzipDirectory=unzip_dir,
|
|
295
|
+
modelIdentifier=md.coSimulation.modelIdentifier,
|
|
296
|
+
instanceName='instance1')
|
|
297
|
+
|
|
298
|
+
model.instantiate()
|
|
299
|
+
model.enterInitializationMode()
|
|
300
|
+
model.exitInitializationMode()
|
|
301
|
+
|
|
302
|
+
to_test = {
|
|
303
|
+
"int32_output": [1,2,3,4,5,6,7,8,9,10],
|
|
304
|
+
"int64_output": [1,2,3,4,5,6,7,8,9,10],
|
|
305
|
+
"uint64_output": [1,2,3,4,5,6,7,8,9,10],
|
|
306
|
+
"float64_output": [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0],
|
|
307
|
+
"boolean_output": [False, True, False, True, True, False, False, True, False, True]
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
model_value = None
|
|
311
|
+
variables = mapped(md)
|
|
312
|
+
for key, value in to_test.items():
|
|
313
|
+
var = variables[key]
|
|
314
|
+
vrs = [var.valueReference]
|
|
315
|
+
if var.type == "Int32":
|
|
316
|
+
model_values = model.getInt32(vrs, nValues=10)
|
|
317
|
+
elif var.type == "Int64":
|
|
318
|
+
model_values = model.getInt64(vrs, nValues=10)
|
|
319
|
+
elif var.type == "UInt64":
|
|
320
|
+
model_values = model.getUInt64(vrs, nValues=10)
|
|
321
|
+
elif var.type == "Float64":
|
|
322
|
+
model_values = model.getFloat64(vrs, nValues=10)
|
|
323
|
+
elif var.type == "Boolean":
|
|
324
|
+
model_values = model.getBoolean(vrs, nValues=10)
|
|
325
|
+
else:
|
|
326
|
+
pytest.xfail("Unsupported type")
|
|
327
|
+
|
|
328
|
+
assert len(model_values) == len(value)
|
|
329
|
+
assert model_values == value
|
|
330
|
+
|
|
331
|
+
model.terminate()
|
|
332
|
+
model.freeInstance()
|
|
333
|
+
|
|
283
334
|
|
|
284
335
|
@pytest.mark.integration
|
|
285
336
|
def test_integration_read_from_file(tmp_path):
|
|
@@ -367,6 +418,61 @@ def test_integration_set(tmp_path):
|
|
|
367
418
|
model.terminate()
|
|
368
419
|
model.freeInstance()
|
|
369
420
|
|
|
421
|
+
@pytest.mark.integration
|
|
422
|
+
def test_integration_set_array(tmp_path):
|
|
423
|
+
script_file = Path(__file__).parent / "slaves/pythonslave_arraytypes.py"
|
|
424
|
+
fmu = FmuBuilder.build_FMU(script_file, dest=tmp_path, needsExecutionTool="false")
|
|
425
|
+
assert fmu.exists()
|
|
426
|
+
|
|
427
|
+
md = fmpy.read_model_description(fmu)
|
|
428
|
+
unzip_dir = fmpy.extract(fmu)
|
|
429
|
+
|
|
430
|
+
model = fmpy.fmi3.FMU3Slave(
|
|
431
|
+
guid=md.guid,
|
|
432
|
+
unzipDirectory=unzip_dir,
|
|
433
|
+
modelIdentifier=md.coSimulation.modelIdentifier,
|
|
434
|
+
instanceName='instance1')
|
|
435
|
+
|
|
436
|
+
model.instantiate()
|
|
437
|
+
model.enterInitializationMode()
|
|
438
|
+
model.exitInitializationMode()
|
|
439
|
+
|
|
440
|
+
to_test = {
|
|
441
|
+
"int32_input": [1,2,3,4,5,6,7,8,9,10],
|
|
442
|
+
"int64_input": [1,2,3,4,5,6,7,8,9,10],
|
|
443
|
+
"uint64_input": [1,2,3,4,5,6,7,8,9,10],
|
|
444
|
+
"float64_input": [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0],
|
|
445
|
+
"boolean_input": [False, True, False, True, True, False, False, True, False, True]
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
model_value = None
|
|
449
|
+
variables = mapped(md)
|
|
450
|
+
for key, value in to_test.items():
|
|
451
|
+
var = variables[key]
|
|
452
|
+
vrs = [var.valueReference]
|
|
453
|
+
if var.type == "Int32":
|
|
454
|
+
model.setInt32(vrs, value)
|
|
455
|
+
model_value = model.getInt32(vrs, nValues=10)
|
|
456
|
+
elif var.type == "Int64":
|
|
457
|
+
model.setInt64(vrs, value)
|
|
458
|
+
model_value = model.getInt64(vrs, nValues=10)
|
|
459
|
+
elif var.type == "UInt64":
|
|
460
|
+
model.setUInt64(vrs, value)
|
|
461
|
+
model_value = model.getUInt64(vrs, nValues=10)
|
|
462
|
+
elif var.type == "Float64":
|
|
463
|
+
model.setFloat64(vrs, value)
|
|
464
|
+
model_value = model.getFloat64(vrs,nValues=10)
|
|
465
|
+
elif var.type == "Boolean":
|
|
466
|
+
model.setBoolean(vrs, value)
|
|
467
|
+
model_value = model.getBoolean(vrs, nValues=10)
|
|
468
|
+
else:
|
|
469
|
+
pytest.xfail("Unsupported type")
|
|
470
|
+
|
|
471
|
+
assert list(model_value) == value
|
|
472
|
+
|
|
473
|
+
model.terminate()
|
|
474
|
+
model.freeInstance()
|
|
475
|
+
|
|
370
476
|
|
|
371
477
|
@pytest.mark.integration
|
|
372
478
|
def test_simple_integration_fmpy(tmp_path):
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Load a built FMU from a plain C program, i.e. without a Python interpreter in the host.
|
|
2
|
+
|
|
3
|
+
This is how most FMI importers (OMSimulator, fmusim, Simulink, ...) use an FMU. The
|
|
4
|
+
Linux/macOS shim must locate libpython itself in that case.
|
|
5
|
+
"""
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import zipfile
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import pytest
|
|
14
|
+
|
|
15
|
+
import pythonfmu3
|
|
16
|
+
from pythonfmu3.builder import FmuBuilder
|
|
17
|
+
from pythonfmu3.osutil import get_lib_extension, get_platform
|
|
18
|
+
|
|
19
|
+
HERE = Path(__file__).parent
|
|
20
|
+
CC = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
|
|
21
|
+
|
|
22
|
+
pytestmark = [
|
|
23
|
+
pytest.mark.skipif(sys.platform == "win32", reason="the shim is only used on Linux/macOS"),
|
|
24
|
+
pytest.mark.skipif(not FmuBuilder.has_binary(), reason="needs the compiled wrapper"),
|
|
25
|
+
pytest.mark.skipif(CC is None, reason="needs a C compiler"),
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@pytest.fixture(scope="module")
|
|
30
|
+
def host(tmp_path_factory):
|
|
31
|
+
out = tmp_path_factory.mktemp("host") / "fmi3_host"
|
|
32
|
+
include = Path(pythonfmu3.__path__[0]) / "pythonfmu-export" / "src" / "fmi"
|
|
33
|
+
libs = ["-ldl"] if sys.platform.startswith("linux") else []
|
|
34
|
+
subprocess.run([CC, f"-I{include}", str(HERE / "data" / "fmi3_host.c"), "-o", str(out), *libs], check=True)
|
|
35
|
+
return out
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@pytest.fixture(scope="module")
|
|
39
|
+
def fmu_dir(tmp_path_factory):
|
|
40
|
+
dest = tmp_path_factory.mktemp("fmu")
|
|
41
|
+
fmu = FmuBuilder.build_FMU(HERE / "slaves" / "pythonslave.py", dest=dest)
|
|
42
|
+
target = dest / "extracted"
|
|
43
|
+
with zipfile.ZipFile(fmu) as z:
|
|
44
|
+
z.extractall(target)
|
|
45
|
+
return target
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _run(host, fmu_dir, env):
|
|
49
|
+
library = fmu_dir / "binaries" / get_platform() / f"PythonSlave.{get_lib_extension()}"
|
|
50
|
+
# Minimal environment: nothing Python-related is inherited from the test process
|
|
51
|
+
base = {k: v for k, v in os.environ.items() if k in ("PATH", "HOME", "LANG", "TMPDIR")}
|
|
52
|
+
return subprocess.run(
|
|
53
|
+
[str(host), str(library), str(fmu_dir / "resources")],
|
|
54
|
+
capture_output=True, text=True, timeout=120, env={**base, **env},
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def test_runs_without_python_host(host, fmu_dir):
|
|
59
|
+
proc = _run(host, fmu_dir, {})
|
|
60
|
+
assert proc.returncode == 0, proc.stdout + proc.stderr
|
|
61
|
+
assert "realOut 1.5" in proc.stdout
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_library_path_from_environment(host, fmu_dir, tmp_path):
|
|
65
|
+
hints = fmu_dir / "resources" / "pythonfmu_libpython.txt"
|
|
66
|
+
if not hints.exists():
|
|
67
|
+
pytest.skip("building interpreter has no shared libpython")
|
|
68
|
+
library = hints.read_text().splitlines()[0]
|
|
69
|
+
backup = tmp_path / "hints.txt"
|
|
70
|
+
shutil.move(hints, backup)
|
|
71
|
+
try:
|
|
72
|
+
proc = _run(host, fmu_dir, {"PYTHONFMU_PYTHON_LIBRARY": library})
|
|
73
|
+
finally:
|
|
74
|
+
shutil.move(backup, hints)
|
|
75
|
+
assert proc.returncode == 0, proc.stdout + proc.stderr
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from pythonfmu3 import osutil
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@pytest.mark.parametrize(
|
|
7
|
+
"system, machine, is_64bit, expected",
|
|
8
|
+
[
|
|
9
|
+
("Darwin", "arm64", True, "aarch64-darwin"), # Apple Silicon
|
|
10
|
+
("Darwin", "x86_64", True, "x86_64-darwin"), # Intel Mac (or Rosetta)
|
|
11
|
+
("Linux", "x86_64", True, "x86_64-linux"),
|
|
12
|
+
("Linux", "aarch64", True, "aarch64-linux"), # Raspberry Pi 4/5, Graviton
|
|
13
|
+
("Linux", "armv7l", False, "aarch32-linux"),
|
|
14
|
+
("Windows", "AMD64", True, "x86_64-windows"),
|
|
15
|
+
("Windows", "AMD64", False, "x86-windows"), # 32-bit Python on 64-bit Windows
|
|
16
|
+
("Windows", "ARM64", True, "aarch64-windows"),
|
|
17
|
+
],
|
|
18
|
+
)
|
|
19
|
+
def test_fmi3_platform_tuple(monkeypatch, system, machine, is_64bit, expected):
|
|
20
|
+
monkeypatch.setattr(osutil.platform, "system", lambda: system)
|
|
21
|
+
monkeypatch.setattr(osutil.platform, "machine", lambda: machine)
|
|
22
|
+
monkeypatch.setattr(osutil, "_is_64bit", lambda: is_64bit)
|
|
23
|
+
assert osutil.get_platform() == expected
|
|
@@ -324,7 +324,7 @@ def test_array_to_xml(name, start, dims):
|
|
|
324
324
|
])
|
|
325
325
|
def test_array_output_to_xml(name, start, dims):
|
|
326
326
|
import numpy as np
|
|
327
|
-
start = np.reshape(start,
|
|
327
|
+
start = np.reshape(start, dims)
|
|
328
328
|
r = Float64(name, start, dimensions=[Dimension(start=val) for val in dims], causality=Fmi3Causality.output)
|
|
329
329
|
xml = r.to_xml()
|
|
330
330
|
if start is not None:
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Exercise the native wrapper directly through ctypes (no fmpy needed).
|
|
2
|
+
|
|
3
|
+
Each scenario runs in its own interpreter so a crash in the wrapper fails the test
|
|
4
|
+
instead of taking down the test session.
|
|
5
|
+
"""
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
import zipfile
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import pytest
|
|
12
|
+
|
|
13
|
+
from pythonfmu3.builder import FmuBuilder
|
|
14
|
+
|
|
15
|
+
pytestmark = pytest.mark.skipif(
|
|
16
|
+
not FmuBuilder.has_binary() or not sys.platform.startswith("linux"),
|
|
17
|
+
reason="needs the compiled wrapper (ctypes driver is Linux-only)",
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
HERE = Path(__file__).parent
|
|
21
|
+
DRIVER = HERE / "fmi3_ctypes_driver.py"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _extract(script: Path, dest: Path) -> Path:
|
|
25
|
+
fmu = FmuBuilder.build_FMU(script, dest=dest)
|
|
26
|
+
target = dest / fmu.stem
|
|
27
|
+
with zipfile.ZipFile(fmu) as z:
|
|
28
|
+
z.extractall(target)
|
|
29
|
+
return target
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@pytest.fixture(scope="module")
|
|
33
|
+
def python_slave(tmp_path_factory):
|
|
34
|
+
# A space in the path exercises the resource-path handling
|
|
35
|
+
return _extract(HERE / "slaves/pythonslave.py", tmp_path_factory.mktemp("with space"))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@pytest.fixture(scope="module")
|
|
39
|
+
def exception_slave(tmp_path_factory):
|
|
40
|
+
return _extract(HERE / "slaves/PythonSlaveWithException.py", tmp_path_factory.mktemp("exc"))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _run(scenario: str, fmu_dir: Path):
|
|
44
|
+
proc = subprocess.run(
|
|
45
|
+
[sys.executable, str(DRIVER), scenario, str(fmu_dir)],
|
|
46
|
+
capture_output=True, text=True, timeout=120,
|
|
47
|
+
)
|
|
48
|
+
assert proc.returncode == 0, proc.stdout + proc.stderr
|
|
49
|
+
assert f"OK {scenario}" in proc.stdout
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@pytest.mark.parametrize(
|
|
53
|
+
"scenario",
|
|
54
|
+
["basic", "bad_vr_type", "too_few_values", "null_logger", "bad_resources", "uri_resources"],
|
|
55
|
+
)
|
|
56
|
+
def test_wrapper(scenario, python_slave):
|
|
57
|
+
_run(scenario, python_slave)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_wrapper_exception_in_step(exception_slave):
|
|
61
|
+
_run("exception_in_step", exception_slave)
|
pythonfmu3/variables.py
CHANGED
|
@@ -50,6 +50,11 @@ class ModelVariable(ABC):
|
|
|
50
50
|
self.setter = setter
|
|
51
51
|
self._type = None
|
|
52
52
|
self.local_name = name.split(".")[-1]
|
|
53
|
+
|
|
54
|
+
# demanagle names
|
|
55
|
+
self.local_name = self.local_name.lstrip('_')
|
|
56
|
+
|
|
57
|
+
|
|
53
58
|
self.__attrs = {
|
|
54
59
|
"name": name,
|
|
55
60
|
"valueReference": None,
|
|
@@ -151,7 +156,6 @@ class Start(object):
|
|
|
151
156
|
attrib["value"] = self.value
|
|
152
157
|
return Element("Start", attrib)
|
|
153
158
|
|
|
154
|
-
|
|
155
159
|
class Dimension(object):
|
|
156
160
|
def __init__(self, start: str = "", valueReference: str = ""):
|
|
157
161
|
if start and valueReference and any((start, valueReference)):
|
|
@@ -177,15 +181,38 @@ class Dimension(object):
|
|
|
177
181
|
ele = Element("Dimension", attrib)
|
|
178
182
|
return ele
|
|
179
183
|
|
|
180
|
-
class
|
|
184
|
+
class Arrayable(object):
|
|
185
|
+
def __init__(self, dimensions : List[Dimension] = [], **kwargs):
|
|
186
|
+
if dimensions:
|
|
187
|
+
check_numpy()
|
|
188
|
+
self._dimensions = dimensions
|
|
189
|
+
|
|
190
|
+
@property
|
|
191
|
+
def dimensions(self) -> List[Dimension]:
|
|
192
|
+
return self._dimensions
|
|
193
|
+
|
|
194
|
+
def get_start_str(self, value, formatter):
|
|
195
|
+
if len(self.dimensions) > 0:
|
|
196
|
+
output = " ".join([formatter(val) for val in flatten(value)])
|
|
197
|
+
if len(output) > MAX_LENGTH:
|
|
198
|
+
output = output[0]
|
|
199
|
+
return output
|
|
200
|
+
else:
|
|
201
|
+
return formatter(value)
|
|
202
|
+
|
|
203
|
+
def dimensions_xml(self) -> List[Element]:
|
|
204
|
+
return [dim.to_xml() for dim in self._dimensions]
|
|
205
|
+
|
|
206
|
+
def size(self, vars):
|
|
207
|
+
return reduce(lambda x, dim: x * int(dim.size(vars)), self._dimensions, 1)
|
|
208
|
+
|
|
209
|
+
class Float64(ModelVariable, Arrayable):
|
|
181
210
|
def __init__(self, name: str, start: Optional[Any] = None, derivative: Optional[Any] = None, dimensions: List[Dimension] = [], unit: Optional[str] = None, **kwargs):
|
|
182
|
-
|
|
211
|
+
ModelVariable.__init__(self, name, **kwargs)
|
|
212
|
+
Arrayable.__init__(self, dimensions)
|
|
183
213
|
self.__attrs = {"start": start, "derivative": derivative}
|
|
184
214
|
self._type = "Float64"
|
|
185
215
|
self._unit = unit
|
|
186
|
-
if dimensions:
|
|
187
|
-
check_numpy()
|
|
188
|
-
self.__dimensions = dimensions
|
|
189
216
|
|
|
190
217
|
@property
|
|
191
218
|
def start(self) -> Optional[Any]:
|
|
@@ -206,11 +233,6 @@ class Float64(ModelVariable):
|
|
|
206
233
|
@property
|
|
207
234
|
def derivative(self):
|
|
208
235
|
return self.__attrs["derivative"]
|
|
209
|
-
|
|
210
|
-
@property
|
|
211
|
-
def dimensions(self) -> List[Dimension]:
|
|
212
|
-
return self.__dimensions
|
|
213
|
-
|
|
214
236
|
|
|
215
237
|
def to_xml(self) -> Element:
|
|
216
238
|
attrib = dict()
|
|
@@ -218,13 +240,7 @@ class Float64(ModelVariable):
|
|
|
218
240
|
if value is not None:
|
|
219
241
|
# In order to not loose precision, a number of this type should be
|
|
220
242
|
# stored on an XML file with at least 16 significant digits
|
|
221
|
-
output = ""
|
|
222
|
-
if len(self.dimensions) > 0:
|
|
223
|
-
output = " ".join([f"{val:.16g}" for val in flatten(value)])
|
|
224
|
-
if len(output) > MAX_LENGTH:
|
|
225
|
-
output = output[0]
|
|
226
|
-
else:
|
|
227
|
-
output = f"{value:.16g}"
|
|
243
|
+
output = self.get_start_str(value, lambda v: f"{v:.16g}")
|
|
228
244
|
attrib[key] = output
|
|
229
245
|
|
|
230
246
|
if self.unit:
|
|
@@ -233,18 +249,15 @@ class Float64(ModelVariable):
|
|
|
233
249
|
self._extras = attrib
|
|
234
250
|
parent = super().to_xml()
|
|
235
251
|
|
|
236
|
-
|
|
237
|
-
parent.append(dimension.to_xml())
|
|
252
|
+
parent.extend(self.dimensions_xml())
|
|
238
253
|
|
|
239
254
|
return parent
|
|
240
255
|
|
|
241
|
-
def size(self, vars):
|
|
242
|
-
return reduce(lambda x, dim: x * int(dim.size(vars)), self.__dimensions, 1)
|
|
243
|
-
|
|
244
256
|
|
|
245
|
-
class Int32(ModelVariable):
|
|
246
|
-
def __init__(self, name: str, start: Optional[Any] = None, **kwargs):
|
|
247
|
-
|
|
257
|
+
class Int32(ModelVariable, Arrayable):
|
|
258
|
+
def __init__(self, name: str, start: Optional[Any] = None, dimensions: List[Dimension] = [], **kwargs):
|
|
259
|
+
ModelVariable.__init__(self, name, **kwargs)
|
|
260
|
+
Arrayable.__init__(self, dimensions, **kwargs)
|
|
248
261
|
self.__attrs = {"start": start}
|
|
249
262
|
self._type = "Int32";
|
|
250
263
|
|
|
@@ -260,15 +273,18 @@ class Int32(ModelVariable):
|
|
|
260
273
|
attrib = dict()
|
|
261
274
|
for key, value in self.__attrs.items():
|
|
262
275
|
if value is not None:
|
|
263
|
-
attrib[key] = str(
|
|
276
|
+
attrib[key] = self.get_start_str(value, lambda v: str(v))
|
|
264
277
|
self._extras = attrib
|
|
265
278
|
parent = super().to_xml()
|
|
279
|
+
|
|
280
|
+
parent.extend(self.dimensions_xml())
|
|
266
281
|
|
|
267
282
|
return parent
|
|
268
283
|
|
|
269
|
-
class Int64(ModelVariable):
|
|
270
|
-
def __init__(self, name: str, start: Optional[Any] = None, **kwargs):
|
|
271
|
-
|
|
284
|
+
class Int64(ModelVariable, Arrayable):
|
|
285
|
+
def __init__(self, name: str, start: Optional[Any] = None, dimensions: List[Dimension] = [], **kwargs):
|
|
286
|
+
ModelVariable.__init__(self, name, **kwargs)
|
|
287
|
+
Arrayable.__init__(self, dimensions, **kwargs)
|
|
272
288
|
self.__attrs = {"start": start}
|
|
273
289
|
self._type = "Int64";
|
|
274
290
|
|
|
@@ -284,15 +300,18 @@ class Int64(ModelVariable):
|
|
|
284
300
|
attrib = dict()
|
|
285
301
|
for key, value in self.__attrs.items():
|
|
286
302
|
if value is not None:
|
|
287
|
-
attrib[key] = str(
|
|
303
|
+
attrib[key] = self.get_start_str(value, lambda v: str(v))
|
|
288
304
|
self._extras = attrib
|
|
289
305
|
parent = super().to_xml()
|
|
290
306
|
|
|
307
|
+
parent.extend(self.dimensions_xml())
|
|
308
|
+
|
|
291
309
|
return parent
|
|
292
310
|
|
|
293
|
-
class UInt64(ModelVariable):
|
|
294
|
-
def __init__(self, name: str, start: Optional[Any] = None, **kwargs):
|
|
295
|
-
|
|
311
|
+
class UInt64(ModelVariable, Arrayable):
|
|
312
|
+
def __init__(self, name: str, start: Optional[Any] = None, dimensions: List[Dimension] = [], **kwargs):
|
|
313
|
+
ModelVariable.__init__(self, name, **kwargs)
|
|
314
|
+
Arrayable.__init__(self, dimensions, **kwargs)
|
|
296
315
|
self.__attrs = {"start": start}
|
|
297
316
|
self._type = "UInt64";
|
|
298
317
|
|
|
@@ -308,15 +327,18 @@ class UInt64(ModelVariable):
|
|
|
308
327
|
attrib = dict()
|
|
309
328
|
for key, value in self.__attrs.items():
|
|
310
329
|
if value is not None:
|
|
311
|
-
attrib[key] = str(
|
|
330
|
+
attrib[key] = self.get_start_str(value, lambda v: str(v))
|
|
312
331
|
self._extras = attrib
|
|
313
332
|
parent = super().to_xml()
|
|
314
333
|
|
|
315
|
-
|
|
334
|
+
parent.extend(self.dimensions_xml())
|
|
316
335
|
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
336
|
+
return parent
|
|
337
|
+
|
|
338
|
+
class Boolean(ModelVariable, Arrayable):
|
|
339
|
+
def __init__(self, name: str, start: Optional[Any] = None, dimensions: List[Dimension] = [], **kwargs):
|
|
340
|
+
ModelVariable.__init__(self, name, **kwargs)
|
|
341
|
+
Arrayable.__init__(self, dimensions, **kwargs)
|
|
320
342
|
self.__attrs = {"start": start}
|
|
321
343
|
self._type = "Boolean"
|
|
322
344
|
|
|
@@ -332,16 +354,18 @@ class Boolean(ModelVariable):
|
|
|
332
354
|
attrib = dict()
|
|
333
355
|
for key, value in self.__attrs.items():
|
|
334
356
|
if value is not None:
|
|
335
|
-
attrib[key] = str(
|
|
357
|
+
attrib[key] = self.get_start_str(value, lambda v: str(v).lower())
|
|
336
358
|
self._extras = attrib
|
|
337
359
|
parent = super().to_xml()
|
|
360
|
+
|
|
361
|
+
parent.extend(self.dimensions_xml())
|
|
338
362
|
|
|
339
363
|
return parent
|
|
340
364
|
|
|
341
365
|
|
|
342
366
|
class String(ModelVariable):
|
|
343
|
-
def __init__(self, name: str, start: Optional[Any] = None, **kwargs):
|
|
344
|
-
|
|
367
|
+
def __init__(self, name: str, start: Optional[Any] = None, dimensions: List[Dimension] = [], **kwargs):
|
|
368
|
+
ModelVariable.__init__(self, name, **kwargs)
|
|
345
369
|
self.__attrs = dict()
|
|
346
370
|
self._type = "String"
|
|
347
371
|
self._start = Start(start)
|
|
@@ -358,18 +382,19 @@ class String(ModelVariable):
|
|
|
358
382
|
attrib = dict()
|
|
359
383
|
for key, value in self.__attrs.items():
|
|
360
384
|
if value is not None:
|
|
361
|
-
attrib[key] = str(value)
|
|
385
|
+
attrib[key] = str(value, lambda v: str(v))
|
|
362
386
|
self._extras = attrib
|
|
363
387
|
parent = super().to_xml()
|
|
364
388
|
|
|
365
389
|
if self.start is not None:
|
|
366
390
|
parent.append(self._start.to_xml())
|
|
367
|
-
|
|
391
|
+
|
|
368
392
|
return parent
|
|
369
393
|
|
|
370
|
-
class Enumeration(ModelVariable):
|
|
371
|
-
def __init__(self, name: str, start: Optional[Any] = None, declared_type: Optional[Any] = None, **kwargs):
|
|
372
|
-
|
|
394
|
+
class Enumeration(ModelVariable, Arrayable):
|
|
395
|
+
def __init__(self, name: str, start: Optional[Any] = None, declared_type: Optional[Any] = None, dimensions: List[Dimension] = [], **kwargs):
|
|
396
|
+
ModelVariable.__init__(self, name, **kwargs)
|
|
397
|
+
Arrayable.__init__(self, dimensions, **kwargs)
|
|
373
398
|
self.__attrs = {"start": start, "declaredType": declared_type}
|
|
374
399
|
self._type = "Enumeration"
|
|
375
400
|
|
|
@@ -1,23 +1,31 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pythonfmu3
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary: A lightweight framework that enables the packaging of
|
|
5
|
-
Home-page: https://github.com/stephensmith25/PythonFMU3
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A lightweight framework that enables the packaging of Python 3 code as FMI 3.0 co-simulation and model exchange FMUs.
|
|
6
5
|
Author: Stephen Smith
|
|
7
|
-
License: MIT
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/StephenSmith25/PythonFMU3
|
|
8
|
+
Project-URL: Documentation, https://pythonfmu3.readthedocs.io/
|
|
9
|
+
Project-URL: Issues, https://github.com/StephenSmith25/PythonFMU3/issues
|
|
10
|
+
Keywords: FMI,FMI3,FMU,co-simulation,model exchange,simulation
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
10
12
|
Classifier: Intended Audience :: End Users/Desktop
|
|
11
13
|
Classifier: Intended Audience :: Developers
|
|
12
14
|
Classifier: Intended Audience :: Science/Research
|
|
13
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
14
15
|
Classifier: Natural Language :: English
|
|
16
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
17
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
18
|
+
Classifier: Operating System :: MacOS
|
|
15
19
|
Classifier: Programming Language :: C++
|
|
16
20
|
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
-
Classifier: Programming Language :: Python :: 3.
|
|
18
|
-
Classifier: Programming Language :: Python :: 3.
|
|
19
|
-
Classifier: Programming Language :: Python :: 3.
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
27
|
Classifier: Topic :: Scientific/Engineering
|
|
28
|
+
Requires-Python: >=3.9
|
|
21
29
|
Description-Content-Type: text/markdown
|
|
22
30
|
License-File: LICENSE
|
|
23
31
|
Provides-Extra: tests
|
|
@@ -41,8 +49,30 @@ This project is a fork of the original PythonFMU repository available at https:/
|
|
|
41
49
|
|
|
42
50
|
### Support:
|
|
43
51
|
|
|
44
|
-
|
|
45
|
-
|
|
52
|
+
Both the Model Exchange and Co-simulation interfaces are supported, with Float64, Int32,
|
|
53
|
+
Int64, UInt64, Boolean, String and Enumeration variables (plus NumPy arrays of the numeric
|
|
54
|
+
types). See the [documentation](https://pythonfmu3.readthedocs.io/) for the full list of
|
|
55
|
+
supported features and current limitations, and the `examples` folder for more models.
|
|
56
|
+
|
|
57
|
+
See the [changelog](docs/changelog.md) for what changed in each release.
|
|
58
|
+
|
|
59
|
+
### Where can I run the FMU?
|
|
60
|
+
|
|
61
|
+
In any FMI 3.0 importer: Python-based tools such as FMPy, and native tools such as
|
|
62
|
+
OMSimulator, `fmusim` or Simulink.
|
|
63
|
+
|
|
64
|
+
The machine running the simulation needs Python 3 with a **shared** Python library, plus
|
|
65
|
+
the packages your model imports (see `pythonfmu3 deploy` below). Inside a Python-based
|
|
66
|
+
importer the FMU uses that interpreter. Otherwise, on Linux and macOS the FMU finds and
|
|
67
|
+
loads `libpython` itself; if it picks the wrong one, or none, point it at the right library:
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
export PYTHONFMU_PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.12.so.1.0
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
On Windows, `python3.dll` must be on the `PATH`. See
|
|
74
|
+
[Running FMUs outside Python](docs/install.md#running-fmus-outside-python-linux-and-macos)
|
|
75
|
+
for the full lookup order.
|
|
46
76
|
|
|
47
77
|
### How do I build an FMU from python code?
|
|
48
78
|
|
|
@@ -53,35 +83,37 @@ pip install pythonfmu3
|
|
|
53
83
|
```
|
|
54
84
|
|
|
55
85
|
2. Create a new class extending the `Fmi3Slave` class declared in the `pythonfmu3.fmi3slave` module (see below for an example).
|
|
86
|
+
Keep a single FMU class per script.
|
|
56
87
|
3. Run `pythonfmu3 build` to create the fmu.
|
|
57
88
|
|
|
58
89
|
```
|
|
59
|
-
usage: pythonfmu3 build [-h] -f SCRIPT_FILE [-d DEST] [--doc DOCUMENTATION_FOLDER] [--terminals
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
90
|
+
usage: pythonfmu3 build [-h] -f SCRIPT_FILE [-d DEST] [--doc DOCUMENTATION_FOLDER] [--terminals TERMINALS]
|
|
91
|
+
[--no-external-tool] [--only-one-per-process] [--handle-state] [--serialize-state]
|
|
92
|
+
[--no-variable-step] [--needs-completed-step]
|
|
93
|
+
[Project files ...]
|
|
63
94
|
|
|
64
95
|
Build an FMU from a Python script.
|
|
65
96
|
|
|
66
97
|
positional arguments:
|
|
67
98
|
Project files Additional project files required by the Python script.
|
|
68
99
|
|
|
69
|
-
|
|
100
|
+
options:
|
|
70
101
|
-h, --help show this help message and exit
|
|
71
102
|
-f SCRIPT_FILE, --file SCRIPT_FILE
|
|
72
103
|
Path to the Python script.
|
|
73
104
|
-d DEST, --dest DEST Where to save the FMU.
|
|
74
105
|
--doc DOCUMENTATION_FOLDER
|
|
75
106
|
Documentation folder to include in the FMU.
|
|
76
|
-
--terminals
|
|
107
|
+
--terminals TERMINALS
|
|
77
108
|
Terminals file (terminalsAndIcons.xml) to include in the FMU.
|
|
78
109
|
--no-external-tool If given, needsExecutionTool=false
|
|
79
|
-
--no-variable-step If given, canHandleVariableCommunicationStepSize=false
|
|
80
|
-
--interpolate-inputs If given, canInterpolateInputs=true
|
|
81
110
|
--only-one-per-process
|
|
82
111
|
If given, canBeInstantiatedOnlyOncePerProcess=true
|
|
83
|
-
--handle-state If given,
|
|
84
|
-
--serialize-state If given,
|
|
112
|
+
--handle-state If given, canGetAndSetFMUState=true
|
|
113
|
+
--serialize-state If given, canSerializeFMUState=true
|
|
114
|
+
--no-variable-step If given, canHandleVariableCommunicationStepSize=false
|
|
115
|
+
--needs-completed-step
|
|
116
|
+
If given, needsCompletedIntegratorStep=true
|
|
85
117
|
```
|
|
86
118
|
|
|
87
119
|
### How do I build an FMU from python code with third-party dependencies?
|
|
@@ -91,7 +123,7 @@ _PythonFMU_ does not package a full environment within the FMU.
|
|
|
91
123
|
However, you can package a `requirements.txt` or `environment.yml` file within your FMU following these steps:
|
|
92
124
|
|
|
93
125
|
1. Install _pythonfmu_ package: `pip install pythonfmu3`
|
|
94
|
-
2. Create a new class extending the `Fmi3Slave` class declared in the `pythonfmu3.fmi3slave` module (see
|
|
126
|
+
2. Create a new class extending the `Fmi3Slave` class declared in the `pythonfmu3.fmi3slave` module (see the examples below).
|
|
95
127
|
3. Create a `requirements.txt` file (to use _pip_ manager) and/or a `environment.yml` file (to use _conda_ manager) that defines your dependencies.
|
|
96
128
|
4. Run `pythonfmu3 build -f myscript.py requirements.txt` to create the fmu including the dependencies file.
|
|
97
129
|
|
|
@@ -133,6 +165,8 @@ class PythonSlave(Fmi3Slave):
|
|
|
133
165
|
self.author = "John Doe"
|
|
134
166
|
self.description = "A simple description"
|
|
135
167
|
|
|
168
|
+
# Create attributes before registering them: register_variable only adds a setter
|
|
169
|
+
# (needed for inputs and parameters) for attributes that already exist.
|
|
136
170
|
self.time = 0.0
|
|
137
171
|
self.intOut = 1
|
|
138
172
|
self.realOut = 3.0
|
|
@@ -172,7 +206,7 @@ To create a model exchange FMU you must inherit from `Fmi3SlaveBase` and one of
|
|
|
172
206
|
|
|
173
207
|
```python
|
|
174
208
|
|
|
175
|
-
from pythonfmu3 import Fmi3Causality, Fmi3SlaveBase, Float64, ModelExchange
|
|
209
|
+
from pythonfmu3 import Fmi3Causality, Fmi3Initial, Fmi3SlaveBase, Fmi3Variability, Float64, ModelExchange
|
|
176
210
|
from typing import List
|
|
177
211
|
|
|
178
212
|
|
|
@@ -207,7 +241,9 @@ class PythonSlaveMX(Fmi3SlaveBase, ModelExchange):
|
|
|
207
241
|
|
|
208
242
|
```
|
|
209
243
|
|
|
210
|
-
Note:
|
|
244
|
+
Note: Model Exchange classes must define a `self.time` member. Derivative variables give the
|
|
245
|
+
value reference of their state with `derivative=`; value references are assigned in
|
|
246
|
+
registration order starting at 0 (here `time` = 0, `x0` = 1, `x1` = 2).
|
|
211
247
|
|
|
212
248
|
#### Create the FMU
|
|
213
249
|
|