diff --git a/.gitignore b/.gitignore index 91dd3fc..fdd7247 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,11 @@ # binaries -*.dll -*.dll.manifest -*.so +#*.dll +#*.dll.manifest +#*.so # pythonfmu binaries folder -/**/pythonfmu3/resources/binaries +#/**/pythonfmu3/resources/binaries # CLion /**/cmake-build-debug @@ -27,7 +27,7 @@ build/ # test and examples artifacts /**/*_log.txt /**/*_result.mat -/**/*.fmu +#/**/*.fmu # Generated TensorFlow model /examples/tensorflow-model-export/stored-model/ diff --git a/.python-version b/.python-version new file mode 100644 index 0000000..24ee5b1 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.13 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e53d8a7 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,48 @@ +# Changelog + +All notable changes to the [PythonFMU3s] project from version 0.4.0 will be documented in this file.
+The changelog format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +## [Unreleased] + +* -/- + + + +## [0.4.0] - 2026-11 +The main goal was the inclusion of event-related functions in the package. +In addition also other functions have been implemented, but there are still some pending FMI3 functions. +All changes where implemented in the branch *eis* + +* Re-structured project to the standard src/pythonfmu3/ structure and moving tests/ out. Ran ruff check --fix and ruff format on project +* Fixed tests so that ============================= test session starts ============================== +* Added the PID-controller example to /examples. Needed fixes. Changed therefore docs/usage.md and adapted the documentation build process (adding conf.py, /_static and /_templates) +* Added the implementation of EnterEventMode fmi3 function to the Cpp code. Successfull compilation. Added a basic discrete event example. +* Updated the documentation of ModelVariables class and added since this is not only in use for ME, but also for CS in event mode. It is set to True per default as per FMI spec +* Added a variable type 'Clock' to ModelVariables. Added some documentation also to other variable types and added ModelVariables.to_str as formatter for python types to xml strings +* Implemented all event-related functions in cppfmu/ and pythonfmu/. Code compiles, but is so far not yet tested. +* Added the function EnterStepMode, which was completely missing, such that no switch back to step mode was possible. Compilation ok. +* In order to receive results from UpdateDiscreteStates() a dedicated NamedTuple needs to be defined and used. +* Ensure all FMI3 model options, so that the system can work with FMI3 features. Options are now implemented as dataclass and it is possible to provide options directly to the Slave (not only through cli). Tested features. +* Change in builder.py to include model options properly +* Corrected errors in fmi3slave.py and variables.py leading to errors in FMU building and FMU usage with respect to variables with dimensions +* Added an FMI3 FMU 'function' as an example for a *pass-through* event-based FMU. Tested basic usage. +* Adapted function signatures to be as close as possible to FMI3 standard. SetupExperiment deprecated, EnterInitializationMode updated, EnterContinuousTimeMode and CompletedIntegratorStep added. Recompiled and basic tests. +* Added the arguments 'eventModeUsed' and 'earlyReturnAllowed' in InstantiateCosimulation, which where so far not included. Related changes in fmi3slave are also implemented. Compiles and test works. IntermediateUpdate management is still not included. +* Some last changes as part of moving back to windows. Windows compilation not yet included. +* Added windows support to the package. The dynamic libraries and the generated FMUs have been added to the git package (.gitignore changed). +* Minor updates within the example FMUs to support discrete_event mode +* Added a CHANGELOG.md file to the package and included this point list from the git commit messages. +* Fixed findings from verification. Mainly PySlaveInstance.cpp fixes and adaptations in some .py files. test_cli.py has been removed, since it needs complete re-write +* One step towards satisfying ruff, mypy and pyright. Still there are a lot of comments. All tests are working. +* Added the remaining Int* and UInt* standard FMI3 variable types. Added suitable tests and the FMU Variables3.fmu containing all variable types + Clock variables are still missing and Enumeration variables are untested. +* Added two array variabels to examples/Variables3.fmu +* Fixed a misunderstanding in update_discrete_states, where it is important to not use discreteStatesNeedsUpdate=True as way to signal that outputs are updated. Use it only to stay in event mode! +* Made all imports into explicit imports and reduced src/pythonfmu3.__init__.py to nothing. +* Removed _version.py and replaced pythonfmu3 version retrieval with retrieval from pyproject.toml as single source + + + + + diff --git a/PythonFMU23.rst b/PythonFMU23.rst new file mode 100644 index 0000000..529965b --- /dev/null +++ b/PythonFMU23.rst @@ -0,0 +1,87 @@ +######################## +PythonFMU for FMI2 and 3 +######################## +Notes on how to make PythonFMU3 work for both FMI2 and FMI3. + +* Folder `src/pythonfmu3` should be renamed to `src/pythonfmu` +* Folder `src/pythonfmu3/pythonfmu-export` should be renamed to src/pythonfmu/pythonfmu3-export` +* Folder `src/pythonfmu/pythonfmu2-export` should be added with content from the `PythonFMU` repository. + +Files in src/pythonfmu3/ +======================== + +builder.py +---------- +* `get_model_description()`: should work, but should probably be replaced by the more flexible version from PythonFMU. Requires also that the related c-code (adapted) is replaced. +* **FmuBuilder.build_FMU()** should be simplified in any case and needs adaptation. + Add also a parameter telling the builder which FMI version to use - or make automatic?? + Change also _FMU to _fmu. +* `create_command_parser`: needs to be changed in relation to changes in build_FMU + +cosimulation.py +--------------- +* **CoSimulation(ABC)**: need to decide how to handle the method `do_step()` and `enter_initialization_mode()`, + which have a different signature in FMI2 and FMI3. + +modelexchange.py +---------------- +* **ModelExchange(ABC,...)**: some of the methods do not exist in FMI2 + +default_experiment.py +--------------------- +* keep as is. Note that this is used differently in FMI2 (`setup_experiment()`) and FMI3 (`enter_initialization_mode()`) + +deploy.py +--------- +* keep as is + +enums.py +-------- +* all enums are defined as **Fmi3...**. Need to decide whether to make equivalent fmi2 enums or make the classes neutral with respect to FMI version. Note that a few minor changes between FMI2 and FMI3 must be handled and the Fmi3Type enum seems both wrong and unused. + +fmi3slave.py +------------ +* **Fmi3Slave** and **Fmi3SlaveBase** are made for FMI3. Make a similar fmi2slave.py for FMI2. + +logmsg.py +--------- +* keep as is. Check whether the logging strategy is aligned with the FMI standard. + +model_options.py +---------------- +* all class names are **Fmi3...**. Need to decide whether to make equivalent fmi2 classes or make the classes neutral with respect to FMI version. Some properties do not exist in FMI2, which would need to be managed, so that they are not listed in modelDescription.xml + +model_returns.py +---------------- +* only relevant for FMI3, since FMI2 does not use these more comåplex returns. + +osutil.py +--------- +* keep as is. The file should probably be **moved to a utils/ folder**. + +unit.py +------- +* keep as is. **Check** whether there are no changes in the handling of units between FMI2 and FMI3 + +variables.py +------------ +* `py_types`: FMI2 types `Real`and `Integer`are included. Can use `fmi_type_version()` to check whether type is allowed in FMI version used. +* `fmi_type_version()`: useful to whether type is allowed in FMI version used. +* `fmi_type`: ok +* `ModelVariable`: name of the class changed from ScalarVariable to ModelVariable. The signature is still compatible with both FMI2 and FMI3. Can probably live with the FMI3 name, making sure that **ScalarVariable** is used when generating the modelDescription in FMI2. See `to_xml()` and `to_str()` methods. +* `Start`: ok +* `Dimension`: does not exist in FMI2. Either make sure that it is **not used in FMI2** or **automatically translate** to a set of ScalarVariable, using the structured variableNamingConvention. +* `Arrayable`. See `Dimension`. +* `Float64 ...`: do not exist in FMI2. **Add** `Real` and `Integer` classes. We could choose to **automatically translate** `Float64` and `Int32` into `Real`and `Integer` classes when building FMI2. +* Clock: does not exist in FMI2. **Check** that it is not used when building FMI2. + +variable_types.py +----------------- +* the defined classes should be ok under FMI2 also. **Float64Type** shall not be used under FMI2. + + + + + + + diff --git a/README.md b/README.md index b295c8b..fcc9dde 100644 --- a/README.md +++ b/README.md @@ -12,12 +12,12 @@ This project is a fork of the original PythonFMU repository available at https://github.com/NTNU-IHB/PythonFMU, which was used as the basis for adding support for FMI 3.0. While we have made efforts to expand the functionality of this project, it currently has some limitations and does not support all the features of FMI 3.0. We would like to acknowledge and give credit to the original PythonFMU project for their contributions to this work. -### Support: +## Support: Please take a look at the examples to see the supported features. We currently support both the Model exchange and Cosimulation Interfaces. -### How do I build an FMU from python code? +## How do I build an FMU from python code? 1. Install `pythonfmu3` package: @@ -30,9 +30,9 @@ pip install pythonfmu3 ``` usage: pythonfmu3 build [-h] -f SCRIPT_FILE [-d DEST] [--doc DOCUMENTATION_FOLDER] [--terminals TERMINALS_FILE] [--no-external-tool] - [--no-variable-step] [--interpolate-inputs] [--only-one-per-process] [--handle-state] - [--serialize-state] [--use-memory-management] - [Project files [Project files ...]] + [--no-variable-step] [--interpolate-inputs] [--only-one-per-process] [--handle-state] + [--serialize-state] [--use-memory-management] + [Project files [Project files ...]] Build an FMU from a Python script. @@ -57,7 +57,7 @@ optional arguments: --serialize-state If given, canSerializeFMUstate=true ``` -### How do I build an FMU from python code with third-party dependencies? +## How do I build an FMU from python code with third-party dependencies? Often, Python scripts depends on non-builtin libraries like `numpy`, `scipy`, etc. _PythonFMU_ does not package a full environment within the FMU. @@ -89,17 +89,18 @@ optional arguments: Requirements or environment file. ``` -### Cosimulation Example: +## Cosimulation Example: -#### Write the script +### Write the script ```python - -from pythonfmu3 import Fmi3Causality, Fmi3Slave, Boolean, Int32, Float64, String +from pythonfmu3.enums import Fmi3Causality +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.model_returns import Fmi3StepResult +from pythonfmu3.variables import Boolean, Int32, Float64, String class PythonSlave(Fmi3Slave): - def __init__(self, **kwargs): super().__init__(**kwargs) @@ -116,17 +117,16 @@ class PythonSlave(Fmi3Slave): self.register_variable(Float64("realOut", causality=Fmi3Causality.output)) self.register_variable(Boolean("booleanVariable", causality=Fmi3Causality.local)) self.register_variable(String("stringVariable", causality=Fmi3Causality.local)) - + # Note: # it is also possible to explicitly define getters and setters as lambdas in case the variable is not backed by a Python field. # self.register_variable(Float64("myReal", causality=Fmi3Causality.output, getter=lambda: self.realOut, setter=lambda v: set_real_out(v)) def do_step(self, current_time, step_size): - return True - + return Fmi3StepResult() ``` -#### Create the FMU +### Create the FMU ``` pythonfmu3 build -f pythonslave.py myproject @@ -137,20 +137,21 @@ where `myproject` is an optional folder containing additional project files requ Project folders such as this will be recursively copied into the FMU. Multiple project files/folders may be added. -### Model Exchange Example +## Model Exchange Example To create a model exchange FMU you must inherit from `Fmi3SlaveBase` and one of (or both) mixin classes `ModelExchange` or `CoSimulation`. -#### Write the script +### Write the script ```python - -from pythonfmu3 import Fmi3Causality, Fmi3SlaveBase, Float64, ModelExchange +from pythonfmu3.enums import Fmi3Causality +from pythonfmu3.fmi3slave import Fmi3SlaveBase +from pythonfmu3.modelexchange import ModelExchange +from pythonfmu3.variables import Float64 from typing import List class PythonSlaveMX(Fmi3SlaveBase, ModelExchange): - def __init__(self, **kwargs): super().__init__(**kwargs) @@ -164,25 +165,64 @@ class PythonSlaveMX(Fmi3SlaveBase, ModelExchange): self.derx0 = 0.0 self.derx1 = 0.0 - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable(Float64("x0", causality=Fmi3Causality.output, start=2, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact)) - self.register_variable(Float64("x1", causality=Fmi3Causality.output, start=0, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact)) - self.register_variable(Float64("derx0", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=1)) - self.register_variable(Float64("derx1", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=2)) - self.register_variable(Float64("mu", causality=Fmi3Causality.parameter, variability=Fmi3Variability.fixed)) - + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + self.register_variable( + Float64( + "x0", + causality=Fmi3Causality.output, + start=2, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ) + ) + self.register_variable( + Float64( + "x1", + causality=Fmi3Causality.output, + start=0, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ) + ) + self.register_variable( + Float64( + "derx0", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=1, + ) + ) + self.register_variable( + Float64( + "derx1", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=2, + ) + ) + self.register_variable( + Float64( + "mu", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.fixed, + ) + ) def get_continuous_state_derivatives(self) -> List[float]: self.derx0 = self.x1 self.derx1 = self.mu * ((1 - self.x0**2) * self.x1) - self.x0 return [self.derx0, self.derx1] - - ``` Note: There is a hard requirement that we have a `self.time` member in the derived class. -#### Create the FMU +### Create the FMU ``` pythonfmu3 build -f pythonslaveMX.py diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..d0c3cbf --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = source +BUILDDIR = build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..7ecca52 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,35 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=source +set BUILDDIR=build + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.https://www.sphinx-doc.org/ + exit /b 1 +) + +if "%1" == "" goto help + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% -a -E +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/docs/source/CHANGELOG.md b/docs/source/CHANGELOG.md new file mode 100644 index 0000000..3139cd4 --- /dev/null +++ b/docs/source/CHANGELOG.md @@ -0,0 +1,2 @@ +```{include} ../../CHANGELOG.md +``` diff --git a/docs/source/README.md b/docs/source/README.md new file mode 100644 index 0000000..525dc25 --- /dev/null +++ b/docs/source/README.md @@ -0,0 +1,4 @@ +# README + +```{include} ../../README.md +``` diff --git a/docs/source/_autosummary/pythonfmu3.builder.FmuBuilder.rst b/docs/source/_autosummary/pythonfmu3.builder.FmuBuilder.rst new file mode 100644 index 0000000..7663c30 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.builder.FmuBuilder.rst @@ -0,0 +1,26 @@ +FmuBuilder +========== + +.. currentmodule:: pythonfmu3.builder + +.. autoclass:: FmuBuilder + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~FmuBuilder.__init__ + ~FmuBuilder.build_FMU + ~FmuBuilder.has_binary + + + + + + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.builder.rst b/docs/source/_autosummary/pythonfmu3.builder.rst new file mode 100644 index 0000000..482af85 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.builder.rst @@ -0,0 +1,24 @@ +pythonfmu3.builder +================== + +.. automodule:: pythonfmu3.builder + :members: + :exclude-members: FmuBuilder, + + + + + .. rubric:: Functions + .. autosummary:: + + create_command_parser + get_class_name + get_model_description + + .. rubric:: Classes + .. autosummary:: + :toctree: + :template: custom-class.rst + + FmuBuilder + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.enums.Fmi3Causality.rst b/docs/source/_autosummary/pythonfmu3.enums.Fmi3Causality.rst new file mode 100644 index 0000000..c4b42a0 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.enums.Fmi3Causality.rst @@ -0,0 +1,30 @@ +Fmi3Causality +============= + +.. currentmodule:: pythonfmu3.enums + +.. autoclass:: Fmi3Causality + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Fmi3Causality.parameter + ~Fmi3Causality.calculatedParameter + ~Fmi3Causality.input + ~Fmi3Causality.output + ~Fmi3Causality.local + ~Fmi3Causality.independent + ~Fmi3Causality.structuralParameter + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.enums.Fmi3Initial.rst b/docs/source/_autosummary/pythonfmu3.enums.Fmi3Initial.rst new file mode 100644 index 0000000..529fc27 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.enums.Fmi3Initial.rst @@ -0,0 +1,26 @@ +Fmi3Initial +=========== + +.. currentmodule:: pythonfmu3.enums + +.. autoclass:: Fmi3Initial + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Fmi3Initial.exact + ~Fmi3Initial.approx + ~Fmi3Initial.calculated + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.enums.Fmi3IntervalVariability.rst b/docs/source/_autosummary/pythonfmu3.enums.Fmi3IntervalVariability.rst new file mode 100644 index 0000000..9765294 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.enums.Fmi3IntervalVariability.rst @@ -0,0 +1,29 @@ +Fmi3IntervalVariability +======================= + +.. currentmodule:: pythonfmu3.enums + +.. autoclass:: Fmi3IntervalVariability + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Fmi3IntervalVariability.constant + ~Fmi3IntervalVariability.fixed + ~Fmi3IntervalVariability.tunable + ~Fmi3IntervalVariability.changing + ~Fmi3IntervalVariability.countdown + ~Fmi3IntervalVariability.triggered + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.enums.Fmi3Status.rst b/docs/source/_autosummary/pythonfmu3.enums.Fmi3Status.rst new file mode 100644 index 0000000..800600c --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.enums.Fmi3Status.rst @@ -0,0 +1,44 @@ +Fmi3Status +========== + +.. currentmodule:: pythonfmu3.enums + +.. autoclass:: Fmi3Status + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Fmi3Status.conjugate + ~Fmi3Status.bit_length + ~Fmi3Status.bit_count + ~Fmi3Status.to_bytes + ~Fmi3Status.from_bytes + ~Fmi3Status.as_integer_ratio + ~Fmi3Status.is_integer + ~Fmi3Status.__init__ + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Fmi3Status.real + ~Fmi3Status.imag + ~Fmi3Status.numerator + ~Fmi3Status.denominator + ~Fmi3Status.ok + ~Fmi3Status.warning + ~Fmi3Status.discard + ~Fmi3Status.error + ~Fmi3Status.fatal + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.enums.Fmi3Type.rst b/docs/source/_autosummary/pythonfmu3.enums.Fmi3Type.rst new file mode 100644 index 0000000..ba05cc0 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.enums.Fmi3Type.rst @@ -0,0 +1,28 @@ +Fmi3Type +======== + +.. currentmodule:: pythonfmu3.enums + +.. autoclass:: Fmi3Type + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Fmi3Type.integer + ~Fmi3Type.real + ~Fmi3Type.boolean + ~Fmi3Type.string + ~Fmi3Type.enumeration + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.enums.Fmi3Variability.rst b/docs/source/_autosummary/pythonfmu3.enums.Fmi3Variability.rst new file mode 100644 index 0000000..9f663f9 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.enums.Fmi3Variability.rst @@ -0,0 +1,28 @@ +Fmi3Variability +=============== + +.. currentmodule:: pythonfmu3.enums + +.. autoclass:: Fmi3Variability + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Fmi3Variability.constant + ~Fmi3Variability.fixed + ~Fmi3Variability.tunable + ~Fmi3Variability.discrete + ~Fmi3Variability.continuous + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.enums.PackageManager.rst b/docs/source/_autosummary/pythonfmu3.enums.PackageManager.rst new file mode 100644 index 0000000..3aca287 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.enums.PackageManager.rst @@ -0,0 +1,25 @@ +PackageManager +============== + +.. currentmodule:: pythonfmu3.enums + +.. autoclass:: PackageManager + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~PackageManager.pip + ~PackageManager.conda + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.enums.rst b/docs/source/_autosummary/pythonfmu3.enums.rst new file mode 100644 index 0000000..9314857 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.enums.rst @@ -0,0 +1,23 @@ +pythonfmu3.enums +================ + +.. automodule:: pythonfmu3.enums + :members: + :exclude-members: Fmi3Causality,Fmi3Initial,Fmi3IntervalVariability,Fmi3Status,Fmi3Type,Fmi3Variability,PackageManager, + + + + + .. rubric:: Classes + .. autosummary:: + :toctree: + :template: custom-class.rst + + Fmi3Causality + Fmi3Initial + Fmi3IntervalVariability + Fmi3Status + Fmi3Type + Fmi3Variability + PackageManager + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.fmi3slave.Fmi3Slave.rst b/docs/source/_autosummary/pythonfmu3.fmi3slave.Fmi3Slave.rst new file mode 100644 index 0000000..083864c --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.fmi3slave.Fmi3Slave.rst @@ -0,0 +1,66 @@ +Fmi3Slave +========= + +.. currentmodule:: pythonfmu3.fmi3slave + +.. autoclass:: Fmi3Slave + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Fmi3Slave.__init__ + ~Fmi3Slave.doStep + ~Fmi3Slave.do_step + ~Fmi3Slave.enterInitializationMode + ~Fmi3Slave.enter_initialization_mode + ~Fmi3Slave.exit_initialization_mode + ~Fmi3Slave.get_boolean + ~Fmi3Slave.get_continuous_states + ~Fmi3Slave.get_float32 + ~Fmi3Slave.get_float64 + ~Fmi3Slave.get_int16 + ~Fmi3Slave.get_int32 + ~Fmi3Slave.get_int64 + ~Fmi3Slave.get_int8 + ~Fmi3Slave.get_number_of_continuous_states + ~Fmi3Slave.get_number_of_event_indicators + ~Fmi3Slave.get_string + ~Fmi3Slave.get_uint + ~Fmi3Slave.get_uint16 + ~Fmi3Slave.get_uint32 + ~Fmi3Slave.get_uint64 + ~Fmi3Slave.get_uint8 + ~Fmi3Slave.log + ~Fmi3Slave.register_event_indicator + ~Fmi3Slave.register_units + ~Fmi3Slave.register_variable + ~Fmi3Slave.set_boolean + ~Fmi3Slave.set_continuous_states + ~Fmi3Slave.set_float64 + ~Fmi3Slave.set_int32 + ~Fmi3Slave.set_int64 + ~Fmi3Slave.set_string + ~Fmi3Slave.set_time + ~Fmi3Slave.set_uint64 + ~Fmi3Slave.setup_experiment + ~Fmi3Slave.terminate + ~Fmi3Slave.to_xml + ~Fmi3Slave.update_discrete_states + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Fmi3Slave.log_categories + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.fmi3slave.Fmi3SlaveBase.rst b/docs/source/_autosummary/pythonfmu3.fmi3slave.Fmi3SlaveBase.rst new file mode 100644 index 0000000..5feae23 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.fmi3slave.Fmi3SlaveBase.rst @@ -0,0 +1,66 @@ +Fmi3SlaveBase +============= + +.. currentmodule:: pythonfmu3.fmi3slave + +.. autoclass:: Fmi3SlaveBase + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Fmi3SlaveBase.__init__ + ~Fmi3SlaveBase.doStep + ~Fmi3SlaveBase.do_step + ~Fmi3SlaveBase.enterInitializationMode + ~Fmi3SlaveBase.enter_initialization_mode + ~Fmi3SlaveBase.exit_initialization_mode + ~Fmi3SlaveBase.get_boolean + ~Fmi3SlaveBase.get_continuous_states + ~Fmi3SlaveBase.get_float32 + ~Fmi3SlaveBase.get_float64 + ~Fmi3SlaveBase.get_int16 + ~Fmi3SlaveBase.get_int32 + ~Fmi3SlaveBase.get_int64 + ~Fmi3SlaveBase.get_int8 + ~Fmi3SlaveBase.get_number_of_continuous_states + ~Fmi3SlaveBase.get_number_of_event_indicators + ~Fmi3SlaveBase.get_string + ~Fmi3SlaveBase.get_uint + ~Fmi3SlaveBase.get_uint16 + ~Fmi3SlaveBase.get_uint32 + ~Fmi3SlaveBase.get_uint64 + ~Fmi3SlaveBase.get_uint8 + ~Fmi3SlaveBase.log + ~Fmi3SlaveBase.register_event_indicator + ~Fmi3SlaveBase.register_units + ~Fmi3SlaveBase.register_variable + ~Fmi3SlaveBase.set_boolean + ~Fmi3SlaveBase.set_continuous_states + ~Fmi3SlaveBase.set_float64 + ~Fmi3SlaveBase.set_int32 + ~Fmi3SlaveBase.set_int64 + ~Fmi3SlaveBase.set_string + ~Fmi3SlaveBase.set_time + ~Fmi3SlaveBase.set_uint64 + ~Fmi3SlaveBase.setup_experiment + ~Fmi3SlaveBase.terminate + ~Fmi3SlaveBase.to_xml + ~Fmi3SlaveBase.update_discrete_states + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Fmi3SlaveBase.log_categories + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.fmi3slave.rst b/docs/source/_autosummary/pythonfmu3.fmi3slave.rst new file mode 100644 index 0000000..8bda886 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.fmi3slave.rst @@ -0,0 +1,18 @@ +pythonfmu3.fmi3slave +==================== + +.. automodule:: pythonfmu3.fmi3slave + :members: + :exclude-members: Fmi3Slave,Fmi3SlaveBase, + + + + + .. rubric:: Classes + .. autosummary:: + :toctree: + :template: custom-class.rst + + Fmi3Slave + Fmi3SlaveBase + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.model_options.Fmi3ModelOptionsCS.rst b/docs/source/_autosummary/pythonfmu3.model_options.Fmi3ModelOptionsCS.rst new file mode 100644 index 0000000..ec9e983 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.model_options.Fmi3ModelOptionsCS.rst @@ -0,0 +1,45 @@ +Fmi3ModelOptionsCS +================== + +.. currentmodule:: pythonfmu3.model_options + +.. autoclass:: Fmi3ModelOptionsCS + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Fmi3ModelOptionsCS.__init__ + ~Fmi3ModelOptionsCS.to_dict + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Fmi3ModelOptionsCS.canHandleVariableCommunicationStepSize + ~Fmi3ModelOptionsCS.fixedInternalStepSize + ~Fmi3ModelOptionsCS.maxOutputDerivativeOrder + ~Fmi3ModelOptionsCS.recommendedIntermediateInputSmoothness + ~Fmi3ModelOptionsCS.providesIntermediateUpdate + ~Fmi3ModelOptionsCS.mightReturnEarlyFromDoStep + ~Fmi3ModelOptionsCS.canReturnEarlyAfterIntermediateUpdate + ~Fmi3ModelOptionsCS.hasEventMode + ~Fmi3ModelOptionsCS.canBeInstantiatedOnlyOncePerProcess + ~Fmi3ModelOptionsCS.canGetAndSetFMUState + ~Fmi3ModelOptionsCS.canSerializeFMUState + ~Fmi3ModelOptionsCS.needsExecutionTool + ~Fmi3ModelOptionsCS.providesAdjointDerivatives + ~Fmi3ModelOptionsCS.providesDirectionalDerivatives + ~Fmi3ModelOptionsCS.providesEvaluateDiscreteStates + ~Fmi3ModelOptionsCS.providesPerElementDependencies + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.model_options.Fmi3ModelOptionsCommon.rst b/docs/source/_autosummary/pythonfmu3.model_options.Fmi3ModelOptionsCommon.rst new file mode 100644 index 0000000..ce16567 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.model_options.Fmi3ModelOptionsCommon.rst @@ -0,0 +1,37 @@ +Fmi3ModelOptionsCommon +====================== + +.. currentmodule:: pythonfmu3.model_options + +.. autoclass:: Fmi3ModelOptionsCommon + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Fmi3ModelOptionsCommon.__init__ + ~Fmi3ModelOptionsCommon.to_dict + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Fmi3ModelOptionsCommon.needsExecutionTool + ~Fmi3ModelOptionsCommon.canBeInstantiatedOnlyOncePerProcess + ~Fmi3ModelOptionsCommon.canGetAndSetFMUState + ~Fmi3ModelOptionsCommon.canSerializeFMUState + ~Fmi3ModelOptionsCommon.providesDirectionalDerivatives + ~Fmi3ModelOptionsCommon.providesAdjointDerivatives + ~Fmi3ModelOptionsCommon.providesPerElementDependencies + ~Fmi3ModelOptionsCommon.providesEvaluateDiscreteStates + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.model_options.Fmi3ModelOptionsME.rst b/docs/source/_autosummary/pythonfmu3.model_options.Fmi3ModelOptionsME.rst new file mode 100644 index 0000000..b2dc4e5 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.model_options.Fmi3ModelOptionsME.rst @@ -0,0 +1,38 @@ +Fmi3ModelOptionsME +================== + +.. currentmodule:: pythonfmu3.model_options + +.. autoclass:: Fmi3ModelOptionsME + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Fmi3ModelOptionsME.__init__ + ~Fmi3ModelOptionsME.to_dict + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Fmi3ModelOptionsME.needsCompletedIntegratorStep + ~Fmi3ModelOptionsME.canBeInstantiatedOnlyOncePerProcess + ~Fmi3ModelOptionsME.canGetAndSetFMUState + ~Fmi3ModelOptionsME.canSerializeFMUState + ~Fmi3ModelOptionsME.needsExecutionTool + ~Fmi3ModelOptionsME.providesAdjointDerivatives + ~Fmi3ModelOptionsME.providesDirectionalDerivatives + ~Fmi3ModelOptionsME.providesEvaluateDiscreteStates + ~Fmi3ModelOptionsME.providesPerElementDependencies + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.model_options.rst b/docs/source/_autosummary/pythonfmu3.model_options.rst new file mode 100644 index 0000000..d1f4d6f --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.model_options.rst @@ -0,0 +1,19 @@ +pythonfmu3.model\_options +========================= + +.. automodule:: pythonfmu3.model_options + :members: + :exclude-members: Fmi3ModelOptionsCS,Fmi3ModelOptionsCommon,Fmi3ModelOptionsME, + + + + + .. rubric:: Classes + .. autosummary:: + :toctree: + :template: custom-class.rst + + Fmi3ModelOptionsCS + Fmi3ModelOptionsCommon + Fmi3ModelOptionsME + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.model_returns.Fmi3StepResult.rst b/docs/source/_autosummary/pythonfmu3.model_returns.Fmi3StepResult.rst new file mode 100644 index 0000000..91628a3 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.model_returns.Fmi3StepResult.rst @@ -0,0 +1,34 @@ +Fmi3StepResult +============== + +.. currentmodule:: pythonfmu3.model_returns + +.. autoclass:: Fmi3StepResult + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Fmi3StepResult.__init__ + ~Fmi3StepResult.count + ~Fmi3StepResult.index + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Fmi3StepResult.earlyReturn + ~Fmi3StepResult.eventHandlingNeeded + ~Fmi3StepResult.lastSuccessfullTime + ~Fmi3StepResult.terminateSimulation + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.model_returns.Fmi3UpdateDiscreteStatesResult.rst b/docs/source/_autosummary/pythonfmu3.model_returns.Fmi3UpdateDiscreteStatesResult.rst new file mode 100644 index 0000000..fc6dc78 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.model_returns.Fmi3UpdateDiscreteStatesResult.rst @@ -0,0 +1,36 @@ +Fmi3UpdateDiscreteStatesResult +============================== + +.. currentmodule:: pythonfmu3.model_returns + +.. autoclass:: Fmi3UpdateDiscreteStatesResult + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Fmi3UpdateDiscreteStatesResult.__init__ + ~Fmi3UpdateDiscreteStatesResult.count + ~Fmi3UpdateDiscreteStatesResult.index + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Fmi3UpdateDiscreteStatesResult.discreteStatesNeedUpdate + ~Fmi3UpdateDiscreteStatesResult.nextEventTime + ~Fmi3UpdateDiscreteStatesResult.nextEventTimeDefined + ~Fmi3UpdateDiscreteStatesResult.nominalContinuousStatesChanged + ~Fmi3UpdateDiscreteStatesResult.terminateSimulation + ~Fmi3UpdateDiscreteStatesResult.valuesOfContinuousStatesChanged + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.model_returns.StepResult.rst b/docs/source/_autosummary/pythonfmu3.model_returns.StepResult.rst new file mode 100644 index 0000000..cf10712 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.model_returns.StepResult.rst @@ -0,0 +1,34 @@ +StepResult +========== + +.. currentmodule:: pythonfmu3.model_returns + +.. autoclass:: StepResult + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~StepResult.__init__ + ~StepResult.count + ~StepResult.index + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~StepResult.early_return + ~StepResult.event_handling_needed + ~StepResult.last_successfull_time + ~StepResult.terminate_simulation + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.model_returns.UpdateDiscreteStatesResult.rst b/docs/source/_autosummary/pythonfmu3.model_returns.UpdateDiscreteStatesResult.rst new file mode 100644 index 0000000..093fd89 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.model_returns.UpdateDiscreteStatesResult.rst @@ -0,0 +1,36 @@ +UpdateDiscreteStatesResult +========================== + +.. currentmodule:: pythonfmu3.model_returns + +.. autoclass:: UpdateDiscreteStatesResult + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~UpdateDiscreteStatesResult.__init__ + ~UpdateDiscreteStatesResult.count + ~UpdateDiscreteStatesResult.index + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~UpdateDiscreteStatesResult.discrete_states_need_update + ~UpdateDiscreteStatesResult.next_event_time + ~UpdateDiscreteStatesResult.next_event_time_defined + ~UpdateDiscreteStatesResult.nominal_continuous_states_changed + ~UpdateDiscreteStatesResult.terminate_simulation + ~UpdateDiscreteStatesResult.values_of_continuous_states_changed + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.model_returns.rst b/docs/source/_autosummary/pythonfmu3.model_returns.rst new file mode 100644 index 0000000..9c1f6ac --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.model_returns.rst @@ -0,0 +1,20 @@ +pythonfmu3.model\_returns +========================= + +.. automodule:: pythonfmu3.model_returns + :members: + :exclude-members: Fmi3StepResult,Fmi3UpdateDiscreteStatesResult,StepResult,UpdateDiscreteStatesResult, + + + + + .. rubric:: Classes + .. autosummary:: + :toctree: + :template: custom-class.rst + + Fmi3StepResult + Fmi3UpdateDiscreteStatesResult + StepResult + UpdateDiscreteStatesResult + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.Arrayable.rst b/docs/source/_autosummary/pythonfmu3.variables.Arrayable.rst new file mode 100644 index 0000000..cfb2c94 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.Arrayable.rst @@ -0,0 +1,32 @@ +Arrayable +========= + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: Arrayable + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Arrayable.__init__ + ~Arrayable.dimensions_xml + ~Arrayable.get_start_str + ~Arrayable.size + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Arrayable.dimensions + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.Boolean.rst b/docs/source/_autosummary/pythonfmu3.variables.Boolean.rst new file mode 100644 index 0000000..0739c5c --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.Boolean.rst @@ -0,0 +1,43 @@ +Boolean +======= + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: Boolean + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Boolean.__init__ + ~Boolean.dimensions_xml + ~Boolean.get_start_str + ~Boolean.requires_start + ~Boolean.size + ~Boolean.to_str + ~Boolean.to_xml + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Boolean.causality + ~Boolean.declared_type + ~Boolean.description + ~Boolean.dimensions + ~Boolean.initial + ~Boolean.name + ~Boolean.start + ~Boolean.value_reference + ~Boolean.variability + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.Clock.rst b/docs/source/_autosummary/pythonfmu3.variables.Clock.rst new file mode 100644 index 0000000..4bdebe2 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.Clock.rst @@ -0,0 +1,38 @@ +Clock +===== + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: Clock + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Clock.__init__ + ~Clock.requires_start + ~Clock.to_str + ~Clock.to_xml + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Clock.causality + ~Clock.declared_type + ~Clock.description + ~Clock.initial + ~Clock.name + ~Clock.value_reference + ~Clock.variability + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.Dimension.rst b/docs/source/_autosummary/pythonfmu3.variables.Dimension.rst new file mode 100644 index 0000000..b1a4f3a --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.Dimension.rst @@ -0,0 +1,26 @@ +Dimension +========= + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: Dimension + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Dimension.__init__ + ~Dimension.size + ~Dimension.to_xml + + + + + + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.Enumeration.rst b/docs/source/_autosummary/pythonfmu3.variables.Enumeration.rst new file mode 100644 index 0000000..e98c227 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.Enumeration.rst @@ -0,0 +1,43 @@ +Enumeration +=========== + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: Enumeration + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Enumeration.__init__ + ~Enumeration.dimensions_xml + ~Enumeration.get_start_str + ~Enumeration.requires_start + ~Enumeration.size + ~Enumeration.to_str + ~Enumeration.to_xml + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Enumeration.causality + ~Enumeration.declared_type + ~Enumeration.description + ~Enumeration.dimensions + ~Enumeration.initial + ~Enumeration.name + ~Enumeration.start + ~Enumeration.value_reference + ~Enumeration.variability + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.Float32.rst b/docs/source/_autosummary/pythonfmu3.variables.Float32.rst new file mode 100644 index 0000000..b63fb19 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.Float32.rst @@ -0,0 +1,45 @@ +Float32 +======= + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: Float32 + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Float32.__init__ + ~Float32.dimensions_xml + ~Float32.get_start_str + ~Float32.requires_start + ~Float32.size + ~Float32.to_str + ~Float32.to_xml + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Float32.causality + ~Float32.declared_type + ~Float32.derivative + ~Float32.description + ~Float32.dimensions + ~Float32.initial + ~Float32.name + ~Float32.start + ~Float32.unit + ~Float32.value_reference + ~Float32.variability + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.Float64.rst b/docs/source/_autosummary/pythonfmu3.variables.Float64.rst new file mode 100644 index 0000000..e699507 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.Float64.rst @@ -0,0 +1,45 @@ +Float64 +======= + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: Float64 + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Float64.__init__ + ~Float64.dimensions_xml + ~Float64.get_start_str + ~Float64.requires_start + ~Float64.size + ~Float64.to_str + ~Float64.to_xml + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Float64.causality + ~Float64.declared_type + ~Float64.derivative + ~Float64.description + ~Float64.dimensions + ~Float64.initial + ~Float64.name + ~Float64.start + ~Float64.unit + ~Float64.value_reference + ~Float64.variability + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.Int16.rst b/docs/source/_autosummary/pythonfmu3.variables.Int16.rst new file mode 100644 index 0000000..36c9475 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.Int16.rst @@ -0,0 +1,43 @@ +Int16 +===== + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: Int16 + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Int16.__init__ + ~Int16.dimensions_xml + ~Int16.get_start_str + ~Int16.requires_start + ~Int16.size + ~Int16.to_str + ~Int16.to_xml + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Int16.causality + ~Int16.declared_type + ~Int16.description + ~Int16.dimensions + ~Int16.initial + ~Int16.name + ~Int16.start + ~Int16.value_reference + ~Int16.variability + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.Int32.rst b/docs/source/_autosummary/pythonfmu3.variables.Int32.rst new file mode 100644 index 0000000..0e5fea5 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.Int32.rst @@ -0,0 +1,43 @@ +Int32 +===== + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: Int32 + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Int32.__init__ + ~Int32.dimensions_xml + ~Int32.get_start_str + ~Int32.requires_start + ~Int32.size + ~Int32.to_str + ~Int32.to_xml + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Int32.causality + ~Int32.declared_type + ~Int32.description + ~Int32.dimensions + ~Int32.initial + ~Int32.name + ~Int32.start + ~Int32.value_reference + ~Int32.variability + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.Int64.rst b/docs/source/_autosummary/pythonfmu3.variables.Int64.rst new file mode 100644 index 0000000..8fea6fa --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.Int64.rst @@ -0,0 +1,43 @@ +Int64 +===== + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: Int64 + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Int64.__init__ + ~Int64.dimensions_xml + ~Int64.get_start_str + ~Int64.requires_start + ~Int64.size + ~Int64.to_str + ~Int64.to_xml + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Int64.causality + ~Int64.declared_type + ~Int64.description + ~Int64.dimensions + ~Int64.initial + ~Int64.name + ~Int64.start + ~Int64.value_reference + ~Int64.variability + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.Int8.rst b/docs/source/_autosummary/pythonfmu3.variables.Int8.rst new file mode 100644 index 0000000..ef101d6 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.Int8.rst @@ -0,0 +1,43 @@ +Int8 +==== + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: Int8 + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Int8.__init__ + ~Int8.dimensions_xml + ~Int8.get_start_str + ~Int8.requires_start + ~Int8.size + ~Int8.to_str + ~Int8.to_xml + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~Int8.causality + ~Int8.declared_type + ~Int8.description + ~Int8.dimensions + ~Int8.initial + ~Int8.name + ~Int8.start + ~Int8.value_reference + ~Int8.variability + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.ModelVariable.rst b/docs/source/_autosummary/pythonfmu3.variables.ModelVariable.rst new file mode 100644 index 0000000..13979e7 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.ModelVariable.rst @@ -0,0 +1,38 @@ +ModelVariable +============= + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: ModelVariable + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~ModelVariable.__init__ + ~ModelVariable.requires_start + ~ModelVariable.to_str + ~ModelVariable.to_xml + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~ModelVariable.causality + ~ModelVariable.declared_type + ~ModelVariable.description + ~ModelVariable.initial + ~ModelVariable.name + ~ModelVariable.value_reference + ~ModelVariable.variability + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.Start.rst b/docs/source/_autosummary/pythonfmu3.variables.Start.rst new file mode 100644 index 0000000..09d9cb3 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.Start.rst @@ -0,0 +1,25 @@ +Start +===== + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: Start + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~Start.__init__ + ~Start.to_xml + + + + + + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.String.rst b/docs/source/_autosummary/pythonfmu3.variables.String.rst new file mode 100644 index 0000000..de52b46 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.String.rst @@ -0,0 +1,39 @@ +String +====== + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: String + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~String.__init__ + ~String.requires_start + ~String.to_str + ~String.to_xml + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~String.causality + ~String.declared_type + ~String.description + ~String.initial + ~String.name + ~String.start + ~String.value_reference + ~String.variability + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.UInt16.rst b/docs/source/_autosummary/pythonfmu3.variables.UInt16.rst new file mode 100644 index 0000000..c633f09 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.UInt16.rst @@ -0,0 +1,43 @@ +UInt16 +====== + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: UInt16 + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~UInt16.__init__ + ~UInt16.dimensions_xml + ~UInt16.get_start_str + ~UInt16.requires_start + ~UInt16.size + ~UInt16.to_str + ~UInt16.to_xml + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~UInt16.causality + ~UInt16.declared_type + ~UInt16.description + ~UInt16.dimensions + ~UInt16.initial + ~UInt16.name + ~UInt16.start + ~UInt16.value_reference + ~UInt16.variability + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.UInt32.rst b/docs/source/_autosummary/pythonfmu3.variables.UInt32.rst new file mode 100644 index 0000000..1f30d85 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.UInt32.rst @@ -0,0 +1,43 @@ +UInt32 +====== + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: UInt32 + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~UInt32.__init__ + ~UInt32.dimensions_xml + ~UInt32.get_start_str + ~UInt32.requires_start + ~UInt32.size + ~UInt32.to_str + ~UInt32.to_xml + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~UInt32.causality + ~UInt32.declared_type + ~UInt32.description + ~UInt32.dimensions + ~UInt32.initial + ~UInt32.name + ~UInt32.start + ~UInt32.value_reference + ~UInt32.variability + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.UInt64.rst b/docs/source/_autosummary/pythonfmu3.variables.UInt64.rst new file mode 100644 index 0000000..160692a --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.UInt64.rst @@ -0,0 +1,43 @@ +UInt64 +====== + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: UInt64 + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~UInt64.__init__ + ~UInt64.dimensions_xml + ~UInt64.get_start_str + ~UInt64.requires_start + ~UInt64.size + ~UInt64.to_str + ~UInt64.to_xml + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~UInt64.causality + ~UInt64.declared_type + ~UInt64.description + ~UInt64.dimensions + ~UInt64.initial + ~UInt64.name + ~UInt64.start + ~UInt64.value_reference + ~UInt64.variability + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.UInt8.rst b/docs/source/_autosummary/pythonfmu3.variables.UInt8.rst new file mode 100644 index 0000000..a3d836d --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.UInt8.rst @@ -0,0 +1,43 @@ +UInt8 +===== + +.. currentmodule:: pythonfmu3.variables + +.. autoclass:: UInt8 + :members: + :show-inheritance: + + + + .. automethod:: __init__ + + .. rubric:: Methods + .. autosummary:: + + ~UInt8.__init__ + ~UInt8.dimensions_xml + ~UInt8.get_start_str + ~UInt8.requires_start + ~UInt8.size + ~UInt8.to_str + ~UInt8.to_xml + + + + + + + .. rubric:: Attributes + .. autosummary:: + + ~UInt8.causality + ~UInt8.declared_type + ~UInt8.description + ~UInt8.dimensions + ~UInt8.initial + ~UInt8.name + ~UInt8.start + ~UInt8.value_reference + ~UInt8.variability + + \ No newline at end of file diff --git a/docs/source/_autosummary/pythonfmu3.variables.rst b/docs/source/_autosummary/pythonfmu3.variables.rst new file mode 100644 index 0000000..f3b1fc4 --- /dev/null +++ b/docs/source/_autosummary/pythonfmu3.variables.rst @@ -0,0 +1,42 @@ +pythonfmu3.variables +==================== + +.. automodule:: pythonfmu3.variables + :members: + :exclude-members: Arrayable,Boolean,Clock,Dimension,Enumeration,Float32,Float64,Int16,Int32,Int64,Int8,ModelVariable,Start,String,UInt16,UInt32,UInt64,UInt8, + + + + + .. rubric:: Functions + .. autosummary:: + + check_numpy + flatten + fmi_type + fmi_type_version + + .. rubric:: Classes + .. autosummary:: + :toctree: + :template: custom-class.rst + + Arrayable + Boolean + Clock + Dimension + Enumeration + Float32 + Float64 + Int16 + Int32 + Int64 + Int8 + ModelVariable + Start + String + UInt16 + UInt32 + UInt64 + UInt8 + \ No newline at end of file diff --git a/docs/source/_static/PythonFMU3.svg b/docs/source/_static/PythonFMU3.svg new file mode 100644 index 0000000..44c0465 --- /dev/null +++ b/docs/source/_static/PythonFMU3.svg @@ -0,0 +1,56 @@ + +PythonFMU3 diff --git a/docs/source/_templates/custom-class.rst b/docs/source/_templates/custom-class.rst new file mode 100644 index 0000000..a58baba --- /dev/null +++ b/docs/source/_templates/custom-class.rst @@ -0,0 +1,30 @@ +{{ name | escape | underline}} + +.. currentmodule:: {{ module }} + +.. autoclass:: {{ objname }} + :members: + :show-inheritance: + + + {% block methods %} + .. automethod:: __init__ + {% if methods %} + .. rubric:: {{ _('Methods') }} + .. autosummary:: + {% for item in methods %} + ~{{ name }}.{{ item }} + {%- endfor %} + {% endif %} + {% endblock %} + + + {% block attributes %} + {% if attributes %} + .. rubric:: {{ _('Attributes') }} + .. autosummary:: + {% for item in attributes %} + ~{{ name }}.{{ item }} + {%- endfor %} + {% endif %} + {% endblock %} diff --git a/docs/source/_templates/custom-module.rst b/docs/source/_templates/custom-module.rst new file mode 100644 index 0000000..1640853 --- /dev/null +++ b/docs/source/_templates/custom-module.rst @@ -0,0 +1,67 @@ +{{ fullname | escape | underline}} + +.. automodule:: {{ fullname }} + :members: + {%- if classes %} + :exclude-members: {% for item in classes %}{{ item }}{{','}}{%- endfor %} + {% endif %} + + + {% block attributes %} + {%- if attributes %} + .. rubric:: {{ _('Module Attributes') }} + .. autosummary:: + {% for item in attributes %} + {{ item }} + {%- endfor %} + {% endif %} + {%- endblock %} + + + {%- block functions %} + {%- if functions %} + .. rubric:: {{ _('Functions') }} + .. autosummary:: + {% for item in functions %} + {{ item }} + {%- endfor %} + {% endif %} + {%- endblock %} + + + {%- block classes %} + {%- if classes %} + .. rubric:: {{ _('Classes') }} + .. autosummary:: + :toctree: + :template: custom-class.rst + {% for item in classes %} + {{ item }} + {%- endfor %} + {% endif %} + {%- endblock %} + + + {%- block exceptions %} + {%- if exceptions %} + .. rubric:: {{ _('Exceptions') }} + .. autosummary:: + {% for item in exceptions %} + {{ item }} + {%- endfor %} + {% endif %} + {%- endblock %} + + +{%- block modules %} +{%- if modules %} +.. rubric:: Modules +.. autosummary:: + :toctree: + :template: custom-module.rst + :recursive: +{% for item in modules %} + {{ item }} +{%- endfor %} +{% endif %} +{%- endblock %} diff --git a/docs/source/conf.py b/docs/source/conf.py new file mode 100644 index 0000000..a9767c0 --- /dev/null +++ b/docs/source/conf.py @@ -0,0 +1,84 @@ +# mypy: ignore-errors + +# Configuration file for the Sphinx documentation builder. +# +# For the full list of built-in configuration values, see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import sys +from pathlib import Path + +sys.path.insert(0, str(Path("../../src").absolute())) + +root_doc = "overview" + +# -- Project information ----------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information + +project = "PythonFMU3" +author = "Lars Hatledal, Stephen Smith and Siegfried Eisinger" + +# The full version, including alpha/beta/rc tags +release = "0.4.0" + +# -- General configuration --------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration + +extensions = [ + "myst_parser", + "sphinx.ext.autodoc", + "sphinx.ext.napoleon", + "sphinx_argparse_cli", + "sphinx.ext.mathjax", + "sphinx.ext.autosummary", + "sphinx.ext.todo", + "sphinxcontrib.mermaid", +] + +# Extenstion for myst_parser +myst_enable_extensions = [ + "dollarmath", + "attrs_inline", +] + +# The file extensions of source files. +source_suffix = { + ".rst": "restructuredtext", + ".md": "markdown", +} + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [] + + +# -- Options for HTML output ------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output + +html_title = f"PythonFMU3 {release}" +html_theme = "furo" #"sphinx_rtd_theme" +html_static_path = ["_static"] +html_logo = "_static/PythonFMU3.svg" +autodoc_default_options = { + "member-order": "groupwise", + "undoc-members": True, + "exclude-members": "__weakref__", +} +autodoc_preserve_defaults = True + +myst_heading_anchors = 3 + +todo_include_todos = False + +# add markdown mermaid support +myst_fence_as_directive = ["mermaid"] diff --git a/docs/dependencies.md b/docs/source/dependencies.md similarity index 98% rename from docs/dependencies.md rename to docs/source/dependencies.md index 23f33fb..170b41a 100644 --- a/docs/dependencies.md +++ b/docs/source/dependencies.md @@ -1,4 +1,4 @@ -## FMU Dependencies +# FMU Dependencies Often, Python scripts depends on non-builtin libraries like `numpy`, `scipy`, etc. _PythonFMU3_ does not package a full environment within the FMU. diff --git a/docs/source/index.rst b/docs/source/index.rst new file mode 100644 index 0000000..6df26fa --- /dev/null +++ b/docs/source/index.rst @@ -0,0 +1,27 @@ +.. PythonFMU3 documentation master file. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +PythonFMU3 Documentation +======================== + +.. toctree:: + :maxdepth: 4 + :caption: Contents: + + ../../README + overview + install + usage + usageMX + dependencies + ../../CHANGELOG + ../../STYLEGUIDE + ../../LICENSE + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` \ No newline at end of file diff --git a/docs/install.md b/docs/source/install.md similarity index 100% rename from docs/install.md rename to docs/source/install.md diff --git a/docs/index.md b/docs/source/overview.md similarity index 95% rename from docs/index.md rename to docs/source/overview.md index 5adf2f9..a31e395 100644 --- a/docs/index.md +++ b/docs/source/overview.md @@ -9,6 +9,19 @@ [![PyPI](https://img.shields.io/pypi/v/pythonfmu3)](https://pypi.org/project/pythonfmu3/) [![Read the Docs](https://readthedocs.org/projects/pythonfmu3/badge/?version=latest)](https://pythonfmu3.readthedocs.io/) +```{toctree} +:maxdepth: 2 +:caption: Contents: + +README +install +usage +usageMX +dependencies +CHANGELOG +pythonfmu3 +``` + ## Overview PythonFMU3 bridges the gap between Python's rich ecosystem and the Functional Mock-up Interface (FMI) 3.0 standard, enabling seamless integration of Python models into multi-domain simulation environments. Whether you're developing control systems, signal processing algorithms, or complex system models, PythonFMU3 makes it easy to package your Python code as industry-standard FMUs. @@ -56,18 +69,19 @@ pip install pythonfmu3 ```python from pythonfmu3 import Fmi3Slave, Fmi3Causality, Float64 + class MyModel(Fmi3Slave): def __init__(self, **kwargs): super().__init__(**kwargs) - + # Register variables self.register_variable(Float64("input", causality=Fmi3Causality.input)) self.register_variable(Float64("output", causality=Fmi3Causality.output)) - + # Initialize values self.input = 0.0 self.output = 0.0 - + def do_step(self, current_time, step_size): # Your model logic here self.output = 2.0 * self.input @@ -82,7 +96,8 @@ pythonfmu3 build -f my_model.py **3. Use in simulation:** ```python import fmpy -result = fmpy.simulate_fmu('MyModel.fmu', stop_time=10.0) + +result = fmpy.simulate_fmu("MyModel.fmu", stop_time=10.0) ``` ## Architecture @@ -129,7 +144,7 @@ Explore comprehensive examples and documentation: - **[Co-simulation Examples](usage.md)**: PID controllers, filters, state machines - **[Model Exchange Examples](usageMX.md)**: Van der Pol oscillator, Robertson problem -- **[API Reference](api.md)**: Complete class and method documentation +- **[API Reference](pythonfmu3.rst)**: Complete class and method documentation - **[Installation Guide](install.md)**: Setup instructions for all platforms ## Community and Support diff --git a/docs/source/pythonfmu3.rst b/docs/source/pythonfmu3.rst new file mode 100644 index 0000000..db65ee3 --- /dev/null +++ b/docs/source/pythonfmu3.rst @@ -0,0 +1,26 @@ +PythonFMU3 package +================== + +Subpackages +----------- + +.. autosummary:: + :toctree: _autosummary + :template: custom-module.rst + :recursive: + + +Modules +------- + +.. autosummary:: + :toctree: _autosummary + :template: custom-module.rst + :recursive: + + pythonfmu3.fmi3slave + pythonfmu3.variables + pythonfmu3.builder + pythonfmu3.enums + pythonfmu3.model_options + pythonfmu3.model_returns diff --git a/docs/requirements.txt b/docs/source/requirements.txt similarity index 100% rename from docs/requirements.txt rename to docs/source/requirements.txt diff --git a/docs/usage.md b/docs/source/usage.md similarity index 63% rename from docs/usage.md rename to docs/source/usage.md index fb758c7..8f1d0c5 100644 --- a/docs/usage.md +++ b/docs/source/usage.md @@ -35,14 +35,23 @@ self.register_variable(Float64("input_signal", causality=Fmi3Causality.input, st self.register_variable(Float64("output_signal", causality=Fmi3Causality.output)) # Parameters (configurable, usually fixed during simulation) -self.register_variable(Float64("gain", causality=Fmi3Causality.parameter, - variability=Fmi3Variability.tunable, start=1.0)) +self.register_variable( + Float64( + "gain", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.tunable, + start=1.0, + ) +) ``` ### PID Controller Example ```python -from pythonfmu3 import Fmi3Causality, Fmi3Slave, Float64 +from pythonfmu3.enums import Fmi3Causality +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.model_returns import Fmi3StepResult +from pythonfmu3.variables import Float64 class PIDController(Fmi3Slave): """PID Controller implementation""" @@ -56,9 +65,9 @@ class PIDController(Fmi3Slave): # Inputs self.setpoint = 0.0 self.measurement = 0.0 - + # Outputs - self.control_output = 0.0 + self.output = 0.0 # Parameters self.kp = 1.0 # Proportional gain @@ -71,14 +80,19 @@ class PIDController(Fmi3Slave): self.first_step = True # Register variables + self.register_variable(Float64("time", causality=Fmi3Causality.independent)) self.register_variable(Float64("setpoint", causality=Fmi3Causality.input, start=0.0)) self.register_variable(Float64("measurement", causality=Fmi3Causality.input, start=0.0)) self.register_variable(Float64("output", causality=Fmi3Causality.output)) - self.register_variable(Float64("Kp", causality=Fmi3Causality.parameter, start=1.0)) - self.register_variable(Float64("Ki", causality=Fmi3Causality.parameter, start=0.1)) - self.register_variable(Float64("Kd", causality=Fmi3Causality.parameter, start=0.01)) - - def do_step(self, current_time, step_size): + self.register_variable(Float64("kp", causality=Fmi3Causality.parameter, start=1.0)) + self.register_variable(Float64("ki", causality=Fmi3Causality.parameter, start=0.1)) + self.register_variable(Float64("kd", causality=Fmi3Causality.parameter, start=0.01)) + + def do_step(self, + current_communication_point : float, + communication_step_size : float, + no_set_fmu_state_prior_to_current_point:bool, + ) -> Fmi3StepResult: # Calculate error error = self.setpoint - self.measurement @@ -86,7 +100,7 @@ class PIDController(Fmi3Slave): p_term = self.kp * error # Integral term - self.integral_error += error * step_size + self.integral_error += error * communication_step_size i_term = self.ki * self.integral_error # Derivative term @@ -94,16 +108,15 @@ class PIDController(Fmi3Slave): d_term = 0.0 self.first_step = False else: - d_term = self.kd * (error - self.previous_error) / step_size + d_term = self.kd * (error - self.previous_error) / communication_step_size # PID output - self.control_output = p_term + i_term + d_term + self.output = p_term + i_term + d_term # Store error for next iteration self.previous_error = error return True - ``` ### Units @@ -112,7 +125,8 @@ Units can be added to this example through the `Unit` class along with `register ```python -from pythonfmu3 import Unit +from pythonfmu3.unit import Unit + velocity_unit = Unit(name="m/s", m=1, s=-1) ``` which can now be utilized in the register variables call, @@ -127,19 +141,22 @@ self.register_variable(Float64("v", causality=Fmi3Causality.output, start=0, var If numpy is installed, arrays may be used with, ```python -from pythonfmu3 import Fmi3Causality, Fmi3Variability, Fmi3Slave, Float64, UInt64, Fmi3Initial, Dimension import numpy as np +from pythonfmu3.variables import Dimension, Float64 +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.enums import Fmi3Causality, Fmi3Variability -class LinearTransform(Fmi3Slave): +class LinearTransform2x2(Fmi3Slave): def __init__(self, **kwargs): super().__init__(**kwargs) self.author = "..." - self.description = "LinearTransform" + self.description = "Linear transform with fixed size matrix/vector" self.time = 0.0 + self.m = 2 self.n = 2 @@ -148,19 +165,49 @@ class LinearTransform(Fmi3Slave): self.u = np.array([1.0, 2.0]).reshape((self.m, 1)) self.offset = np.array([1.0, 2.0]).reshape((self.m, 1)) self.A = np.array([1.0, 1.0, 2.0, 1.0]).reshape((self.m, self.n)) - self.y = np.array([0.0, 0.0]).reshape((self.m, 1)) - - - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable(UInt64("m", causality=Fmi3Causality.structuralParameter, variability=Fmi3Variability.tunable, start=2)) - self.register_variable(Float64("scalar", causality=Fmi3Causality.input, start=2.0)) - self.register_variable(Float64("u", causality=Fmi3Causality.input, dimensions=[Dimension(start=f"{self.n}")])) - self.register_variable(Float64("offset", causality=Fmi3Causality.input, dimensions=[Dimension(start=f"{self.m}")])) - self.register_variable(Float64("A", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable, dimensions=[Dimension(start=f"{self.m}"), Dimension(start=f"{self.n}")])) - self.register_variable(Float64("y", causality=Fmi3Causality.output, dimensions=[Dimension(valueReference="1")])) - - def do_step(self, current_time, step_size): - self.y = self.scalar*self.A.dot(self.u) + self.offset + self.y = np.array([0.0, 0.0]).reshape((self.n, 1)) + + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + self.register_variable( + Float64("scalar", causality=Fmi3Causality.input, start=2.0) + ) + self.register_variable( + Float64( + "u", causality=Fmi3Causality.input, dimensions=[Dimension(start="2")] + ) + ) + self.register_variable( + Float64( + "offset", + causality=Fmi3Causality.input, + dimensions=[Dimension(start="2")], + ) + ) + self.register_variable( + Float64( + "A", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.tunable, + dimensions=[Dimension(start="2"), Dimension(start="2")], + ) + ) + self.register_variable( + Float64( + "y", causality=Fmi3Causality.output, dimensions=[Dimension(start="2")] + ) + ) + + def do_step(self, + current_communication_point : float, + communication_step_size : float, + no_set_fmu_state_prior_to_current_point : bool): + self.y = self.scalar * self.A.dot(self.u) + self.offset return True ``` @@ -168,7 +215,9 @@ The `do_step` function can also return a tuple of flags, corresponding to those ```python -from pythonfmu3 import Fmi3Status, Fmi3StepResult +from pythonfmu3.enums import Fmi3Status +from pythonfmu3.model_returns import Fmi3StepResult + def do_step(self, current_time, step_size): self.y = 1 + 2 + 3 + 4 + ... @@ -199,34 +248,27 @@ import matplotlib.pyplot as plt # Simulate the PID controller FMU result = simulate_fmu( - filename='PIDController.fmu', + filename="PIDController.fmu", start_time=0.0, stop_time=10.0, step_size=0.01, - start_values={ - 'Kp': 2.0, - 'Ki': 0.5, - 'Kd': 0.1, - 'setpoint': 1.0 - }, - input={ - 'measurement': [(0.0, 0.0), (1.0, 0.3), (5.0, 0.8), (10.0, 1.0)] - } + start_values={"Kp": 2.0, "Ki": 0.5, "Kd": 0.1, "setpoint": 1.0}, + input={"measurement": [(0.0, 0.0), (1.0, 0.3), (5.0, 0.8), (10.0, 1.0)]}, ) # Plot results plt.figure(figsize=(12, 6)) plt.subplot(2, 1, 1) -plt.plot(result['time'], result['setpoint'], label='Setpoint') -plt.plot(result['time'], result['measurement'], label='Measurement') -plt.ylabel('Value') +plt.plot(result["time"], result["setpoint"], label="Setpoint") +plt.plot(result["time"], result["measurement"], label="Measurement") +plt.ylabel("Value") plt.legend() plt.grid(True) plt.subplot(2, 1, 2) -plt.plot(result['time'], result['output'], label='Control Output') -plt.xlabel('Time [s]') -plt.ylabel('Control Signal') +plt.plot(result["time"], result["output"], label="Control Output") +plt.xlabel("Time [s]") +plt.ylabel("Control Signal") plt.legend() plt.grid(True) plt.show() diff --git a/docs/source/usageMX.md b/docs/source/usageMX.md new file mode 100644 index 0000000..f878c20 --- /dev/null +++ b/docs/source/usageMX.md @@ -0,0 +1,364 @@ +# Model Exchange Examples + +Model Exchange FMUs are used for continuous-time simulation where an external solver integrates the system of differential equations. The FMU provides the derivative function and state information, while the master algorithm handles time stepping and numerical integration. + +## Key Concepts + +### Model Exchange vs Co-Simulation +- **Model Exchange**: External solver calls your derivative function at each integration step +- **Co-Simulation**: Your FMU manages its own time stepping with `do_step()` + +### Required Methods +For Model Exchange FMUs, you must implement: +- `get_continuous_state_derivatives()`: Returns derivatives of continuous states +- `get_nominals_of_continuous_states()`: Returns nominal values for scaling +- Optional: `get_event_indicators()`, `update_discrete_states()` + + + +## Key Implementation Details + +### Variable Registration +Model Exchange FMUs require specific variable declarations: + + +```python +# Independent variable (time) +self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) +) + +# States with initial values +self.register_variable( + Float64( + "x0", + causality=Fmi3Causality.output, + start=2.0, # Initial value + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ) +) # Must be exact + +# Derivatives (local variables) +self.register_variable( + Float64( + "derx0", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=1, + ) +) # Derivative of variable 1 (x0) +``` + + +### Derivative Function +The core of Model Exchange is the derivative function: + +```python +def get_continuous_state_derivatives(self): + """Calculate derivatives of continuous states""" + # Van der Pol oscillator equations: + # dx0/dt = x1 + # dx1/dt = μ(1-x0²)x1 - x0 + + self.derx0 = self.x1 + self.derx1 = self.mu * ((1 - self.x0**2) * self.x1) - self.x0 + + return [self.derx0, self.derx1] +``` + +## Example + +```python +from pythonfmu3.enums import Fmi3Causality, Fmi3Initial, Fmi3Status, Fmi3Variability +from pythonfmu3.fmi3slave import Fmi3SlaveBase +from pythonfmu3.modelexchange import ModelExchange +from pythonfmu3.model_returns import Fmi3StepResult +from pythonfmu3.unit import Unit +from pythonfmu3.variables import Float64 +from pythonfmu3.variable_types import Float64Type + +from typing import List + + +class VanDerPol(Fmi3SlaveBase, ModelExchange): + def __init__(self, **kwargs): + super().__init__(**kwargs) + + self.author = "" + self.description = "Van Der Pol oscillator problem for model exchange FMUs" + + self.time = 0.0 + self.mu = 1.0 + self.x0 = 2 + self.x1 = 0 + self.derx0 = 0.0 + self.derx1 = 0.0 + + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + self.register_variable( + Float64( + "x0", + causality=Fmi3Causality.output, + start=2, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ) + ) + self.register_variable( + Float64( + "x1", + causality=Fmi3Causality.output, + start=0, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ) + ) + self.register_variable( + Float64( + "derx0", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=1, + ) + ) + self.register_variable( + Float64( + "derx1", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=2, + ) + ) + self.register_variable( + Float64( + "mu", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.fixed, + ) + ) + + def get_continuous_state_derivatives(self) -> List[float]: + self.derx0 = self.x1 + self.derx1 = self.mu * ((1 - self.x0**2) * self.x1) - self.x0 + return [self.derx0, self.derx1] + + def get_nominals_of_continuous_states(self, nStates: int) -> List[float]: + return [1.0, 1.0] +``` + + +## Build the FMU + +Once your Python script is ready, build the FMU: + +```bash +# Using the CLI +pythonfmu3 build -f van_der_pol.py +``` + +## Usage Example + +The generated FMU can be used with any FMI-compatible tool: + + +```python +# Example with FMPy +import fmpy + +# Load and simulate the FMU +fmu_filename = "VanDerPol.fmu" +result = fmpy.simulate_fmu( + fmu_filename, + stop_time=20.0, + step_size=0.01, + start_values={"mu": 1.0, "x0": 2.0, "x1": 0.0}, +) + +# Plot results +import matplotlib.pyplot as plt + +plt.plot(result["time"], result["x0"], label="x0") +plt.plot(result["time"], result["x1"], label="x1") +plt.xlabel("Time") +plt.ylabel("State Values") +plt.legend() +plt.grid(True) +plt.show() +``` + + +## Advanced Features + +### Event Handling +For systems with discrete events. Firstly, mark the event indicators in register variable with `has_event_indicator`, + + +```python +self.register_variable( + Float64( + "h", + causality=Fmi3Causality.output, + start=1, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ), + has_event_indicator=True, +) +``` + + +Then define the event methods, `get_event_indicators()` and `update_discrete_states`. + + +```python +def get_event_indicators(self): + return [0.2] + + +def update_discrete_states(self): + """Handle discrete state updates after events""" + fdsr = Fmi3UpdateDiscreteStatesResult() + fdsr.valuesOfContinuousStatesChanged = True +``` + + + +### Example + +```python +from pythonfmu3.enums import Fmi3Causality, Fmi3Initial, Fmi3Variability +from pythonfmu3.fmi3slave import Fmi3SlaveBase +from pythonfmu3.modelexchange import ModelExchange +from pythonfmu3.model_returns import Fmi3UpdateDiscreteStatesResult +from pythonfmu3.variables import Float64 + +from typing import List + +import sys + +EVENT_EPS = 1e-12 + + +class BouncingBall(Fmi3SlaveBase, ModelExchange): + def __init__(self, **kwargs): + super().__init__(**kwargs) + + self.author = "..." + self.description = "Bouncing Ball" + + self.time = 0.0 + self.h = 1.0 + self.v = 0.0 + self.derh = 0.0 + self.derv = 0.0 + self.g = -9.81 + self.e = 0.7 + self.v_min = 0.1 + + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + + self.register_variable( + Float64( + "h", + causality=Fmi3Causality.output, + start=1, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ), + has_event_indicator=True, + ) + self.register_variable( + Float64( + "derh", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=1, + ) + ) + self.register_variable( + Float64( + "v", + causality=Fmi3Causality.output, + start=0, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ) + ) + self.register_variable( + Float64( + "derv", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=3, + ) + ) + + self.register_variable( + Float64( + "g", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.fixed, + ) + ) + self.register_variable( + Float64( + "e", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.tunable, + ) + ) + self.register_variable(Float64("v_min", variability=Fmi3Variability.constant, start=0.1)) + + def get_continuous_state_derivatives(self) -> List[float]: + self.derh = self.v + self.derv = self.g + return [self.derh, self.derv] + + def get_event_indicators(self) -> List[float]: + z = [self.h] + if self.h > -EVENT_EPS and self.h <= 0 and self.v > 0: + z[0] = -EVENT_EPS + + return z + + def update_discrete_states(self): + fdsr = Fmi3UpdateDiscreteStatesResult() + + if self.h <= 0 and self.v < 0: + self.h = sys.float_info.min + self.v = -self.v * self.e + + if self.v < self.v_min: + self.v = 0.0 + self.g = 0.0 + + fdsr.valuesOfContinuousStatesChanged = True + + return fdsr +``` + +## Build the FMU + +Once your Python script is ready, build the FMU: + +```bash +# Using the CLI +pythonfmu3 build -f bouncing_ball.py +``` \ No newline at end of file diff --git a/docs/usageMX.md b/docs/usageMX.md deleted file mode 100644 index f91f090..0000000 --- a/docs/usageMX.md +++ /dev/null @@ -1,250 +0,0 @@ -# Model Exchange Examples - -Model Exchange FMUs are used for continuous-time simulation where an external solver integrates the system of differential equations. The FMU provides the derivative function and state information, while the master algorithm handles time stepping and numerical integration. - -## Key Concepts - -### Model Exchange vs Co-Simulation -- **Model Exchange**: External solver calls your derivative function at each integration step -- **Co-Simulation**: Your FMU manages its own time stepping with `do_step()` - -### Required Methods -For Model Exchange FMUs, you must implement: -- `get_continuous_state_derivatives()`: Returns derivatives of continuous states -- `get_nominals_of_continuous_states()`: Returns nominal values for scaling -- Optional: `get_event_indicators()`, `update_discrete_states()` - - - -## Key Implementation Details - -### Variable Registration -Model Exchange FMUs require specific variable declarations: - - -```python -# Independent variable (time) -self.register_variable(Float64("time", - causality=Fmi3Causality.independent, - variability=Fmi3Variability.continuous)) - -# States with initial values -self.register_variable(Float64("x0", - causality=Fmi3Causality.output, - start=2.0, # Initial value - variability=Fmi3Variability.continuous, - initial=Fmi3Initial.exact)) # Must be exact - -# Derivatives (local variables) -self.register_variable(Float64("derx0", - causality=Fmi3Causality.local, - variability=Fmi3Variability.continuous, - derivative=1)) # Derivative of variable 1 (x0) -``` - - -### Derivative Function -The core of Model Exchange is the derivative function: - -```python -def get_continuous_state_derivatives(self): - """Calculate derivatives of continuous states""" - # Van der Pol oscillator equations: - # dx0/dt = x1 - # dx1/dt = μ(1-x0²)x1 - x0 - - self.derx0 = self.x1 - self.derx1 = self.mu * ((1 - self.x0**2) * self.x1) - self.x0 - - return [self.derx0, self.derx1] -``` - -## Example - -```python - -from pythonfmu3 import Fmi3Causality, ModelExchange, Fmi3Variability, Fmi3SlaveBase, Fmi3Status, Float64, Fmi3Initial, Unit, Float64Type, Fmi3StepResult - -from typing import List - -class VanDerPol(Fmi3SlaveBase, ModelExchange): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - - self.author = "" - self.description = "Van Der Pol oscillator problem for model exchange FMUs" - - self.time = 0.0 - self.mu = 1.0 - self.x0 = 2 - self.x1 = 0 - self.derx0 = 0.0 - self.derx1 = 0.0 - - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable(Float64("x0", causality=Fmi3Causality.output, start=2, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact)) - self.register_variable(Float64("x1", causality=Fmi3Causality.output, start=0, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact)) - self.register_variable(Float64("derx0", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=1)) - self.register_variable(Float64("derx1", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=2)) - self.register_variable(Float64("mu", causality=Fmi3Causality.parameter, variability=Fmi3Variability.fixed)) - - - def get_continuous_state_derivatives(self) -> List[float]: - self.derx0 = self.x1 - self.derx1 = self.mu * ((1 - self.x0**2) * self.x1) - self.x0 - return [self.derx0, self.derx1] - - def get_nominals_of_continuous_states(self, nStates: int) -> List[float]: - return [1.0, 1.0] - -``` - - -## Build the FMU - -Once your Python script is ready, build the FMU: - -```bash -# Using the CLI -pythonfmu3 build -f van_der_pol.py -``` - -## Usage Example - -The generated FMU can be used with any FMI-compatible tool: - - -```python -# Example with FMPy -import fmpy - -# Load and simulate the FMU -fmu_filename = "VanDerPol.fmu" -result = fmpy.simulate_fmu( - fmu_filename, - stop_time=20.0, - step_size=0.01, - start_values={'mu': 1.0, 'x0': 2.0, 'x1': 0.0} -) - -# Plot results -import matplotlib.pyplot as plt -plt.plot(result['time'], result['x0'], label='x0') -plt.plot(result['time'], result['x1'], label='x1') -plt.xlabel('Time') -plt.ylabel('State Values') -plt.legend() -plt.grid(True) -plt.show() -``` - - -## Advanced Features - -### Event Handling -For systems with discrete events. Firstly, mark the event indicators in register variable with `has_event_indicator`, - - -```python -self.register_variable(Float64("h", causality=Fmi3Causality.output, start=1, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact), has_event_indicator=True) -``` - - -Then define the event methods, `get_event_indicators()` and `update_discrete_states`. - - -```python -def get_event_indicators(self): - return [0.2] - -def update_discrete_states(self): - """Handle discrete state updates after events""" - fdsr = Fmi3UpdateDiscreteStatesResult() - fdsr.valuesOfContinuousStatesChanged = True -``` - - - -### Example - -```python -from pythonfmu3 import Fmi3Causality, Fmi3Variability, Fmi3SlaveBase, ModelExchange, Float64, Fmi3Initial, Fmi3UpdateDiscreteStatesResult - -from typing import List - -import sys - -EVENT_EPS = 1e-12 - -class BouncingBall(Fmi3SlaveBase, ModelExchange): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - - self.author = "..." - self.description = "Bouncing Ball" - - self.time = 0.0 - self.h = 1.0 - self.v = 0.0 - self.derh = 0.0 - self.derv = 0.0 - self.g = -9.81 - self.e = 0.7 - self.v_min = 0.1 - - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - - self.register_variable(Float64("h", causality=Fmi3Causality.output, start=1, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact), - has_event_indicator=True) - self.register_variable(Float64("derh", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=1)) - self.register_variable(Float64("v", causality=Fmi3Causality.output, start=0, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact)) - self.register_variable(Float64("derv", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=3)) - - self.register_variable(Float64("g", causality=Fmi3Causality.parameter, variability=Fmi3Variability.fixed)) - self.register_variable(Float64("e", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable)) - self.register_variable(Float64("v_min", variability=Fmi3Variability.constant, start=0.1)) - - - - def get_continuous_state_derivatives(self) -> List[float]: - self.derh = self.v - self.derv = self.g - return [self.derh, self.derv] - - def get_event_indicators(self) -> List[float]: - z = [self.h] - if self.h > -EVENT_EPS and self.h <=0 and self.v > 0: - z[0] = -EVENT_EPS - - return z - - def update_discrete_states(self): - fdsr = Fmi3UpdateDiscreteStatesResult() - - if self.h <= 0 and self.v < 0: - self.h = sys.float_info.min - self.v = -self.v * self.e - - if self.v < self.v_min: - self.v = 0.0; - self.g = 0.0; - - fdsr.valuesOfContinuousStatesChanged = True - - return fdsr - - - - -``` - -## Build the FMU - -Once your Python script is ready, build the FMU: - -```bash -# Using the CLI -pythonfmu3 build -f bouncing_ball.py -``` \ No newline at end of file diff --git a/examples/BouncingBall.fmu b/examples/BouncingBall.fmu new file mode 100644 index 0000000..e3721f6 Binary files /dev/null and b/examples/BouncingBall.fmu differ diff --git a/examples/DrivingForce.fmu b/examples/DrivingForce.fmu new file mode 100644 index 0000000..aabfd1b Binary files /dev/null and b/examples/DrivingForce.fmu differ diff --git a/examples/Enum.py b/examples/Enum.py index 967a212..9ec15b4 100644 --- a/examples/Enum.py +++ b/examples/Enum.py @@ -1,10 +1,11 @@ -from pythonfmu3 import Fmi3Causality, Fmi3Variability, Fmi3Slave, Float64, Enumeration, Fmi3Initial, EnumerationType - import enum +from pythonfmu3.enums import Fmi3Causality, Fmi3Initial, Fmi3Variability +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.variables import Enumeration, Float64 +from pythonfmu3.variable_types import EnumerationType class Enum(Fmi3Slave): - def __init__(self, **kwargs): super().__init__(**kwargs) @@ -14,15 +15,32 @@ def __init__(self, **kwargs): self.time = 0.0 self.x = 0.0 - Options = enum.Enum('Options', {'Option_1': 1, 'Option_2': 2}) + Options = enum.Enum("Options", {"Option_1": 1, "Option_2": 2}) enum_type = EnumerationType(name="Option", values=Options) self.option = Options.Option_1 - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable(Float64("x", causality=Fmi3Causality.output, initial=Fmi3Initial.calculated)) - self.register_variable(Enumeration("option", declared_type="Option", start=1, causality=Fmi3Causality.input, - getter=lambda: self.option.value, setter=lambda v: setattr(self, "option", Options(v))), var_type=enum_type) - - def do_step(self, current_time, step_size): + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + self.register_variable( + Float64("x", causality=Fmi3Causality.output, initial=Fmi3Initial.calculated) + ) + self.register_variable( + Enumeration( + "option", + declared_type="Option", + start=1, + causality=Fmi3Causality.input, + getter=lambda: self.option.value, + setter=lambda v: setattr(self, "option", Options(v)), + ), + var_type=enum_type, + ) + + def do_step(self, current_communication_point, communication_step_size): self.x += 1.0 return True diff --git a/examples/Function.fmu b/examples/Function.fmu new file mode 100644 index 0000000..770f0ad Binary files /dev/null and b/examples/Function.fmu differ diff --git a/examples/LinearTransform.fmu b/examples/LinearTransform.fmu new file mode 100644 index 0000000..ff27dc7 Binary files /dev/null and b/examples/LinearTransform.fmu differ diff --git a/examples/LinearTransform2x2.fmu b/examples/LinearTransform2x2.fmu new file mode 100644 index 0000000..581c888 Binary files /dev/null and b/examples/LinearTransform2x2.fmu differ diff --git a/examples/Oscillator.fmu b/examples/Oscillator.fmu new file mode 100644 index 0000000..1eb9a4e Binary files /dev/null and b/examples/Oscillator.fmu differ diff --git a/examples/PIDController.fmu b/examples/PIDController.fmu new file mode 100644 index 0000000..6e56a93 Binary files /dev/null and b/examples/PIDController.fmu differ diff --git a/examples/Table.fmu b/examples/Table.fmu new file mode 100644 index 0000000..7d1675c Binary files /dev/null and b/examples/Table.fmu differ diff --git a/examples/TwoState.fmu b/examples/TwoState.fmu new file mode 100644 index 0000000..7f3eadd Binary files /dev/null and b/examples/TwoState.fmu differ diff --git a/examples/Variables3.fmu b/examples/Variables3.fmu new file mode 100644 index 0000000..577603e Binary files /dev/null and b/examples/Variables3.fmu differ diff --git a/examples/alltypes.py b/examples/alltypes.py index 5bad6b9..be9afc0 100644 --- a/examples/alltypes.py +++ b/examples/alltypes.py @@ -1,52 +1,59 @@ -from pythonfmu3 import Fmi3Causality, Fmi3Variability, Dimension, Fmi3Slave, Fmi3Status, Float64, Int32, Int64, UInt64, String, Boolean - +from pythonfmu3.variables import Boolean, Float64, Int32, Int64, UInt64 +from pythonfmu3.enums import Fmi3Causality, Fmi3Variability, Fmi3Status +from pythonfmu3.fmi3slave import Fmi3Slave TYPES = [UInt64, Float64, Boolean, Int32, Int64] CAUSALITY = [Fmi3Causality.output, Fmi3Causality.input] -type_map = { - UInt64: int, - Float64: float, - Int32: int, - Int64: int, - Boolean: bool -} +type_map = {UInt64: int, Float64: float, Int32: int, Int64: int, Boolean: bool} + def var_names(var_type, causality): return f"{var_type.__name__.lower()}_{causality.name.lower()}" - + + def init_var(var_type, causality): return type_map[var_type]() - + + def create_vars(self): for var_type in TYPES: - for causality in CAUSALITY: - name = var_names(var_type, causality) - if var_type == Float64: - var = var_type(name, causality=causality, variability=Fmi3Variability.continuous) - else: - var = var_type(name, causality=causality, variability=Fmi3Variability.discrete) - setattr(self, name, init_var(var_type, causality)) - self.register_variable(var) + for causality in CAUSALITY: + name = var_names(var_type, causality) + if var_type == Float64: + var = var_type( + name, causality=causality, variability=Fmi3Variability.continuous + ) + else: + var = var_type( + name, causality=causality, variability=Fmi3Variability.discrete + ) + setattr(self, name, init_var(var_type, causality)) + self.register_variable(var) + class AllTypes(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + + self.author = "Stephen Smith" + self.description = "All types example" - def __init__(self, **kwargs): - super().__init__(**kwargs) + self.time = 0.0 - self.author = "Stephen Smith" - self.description = "All types example" - - self.time = 0.0 + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) + create_vars(self) - create_vars(self) - + def do_step(self, current_communication_point: float, communication_step_size: float) -> Fmi3Status: + # feedthrough + for var_type in TYPES: + input_var = getattr(self, var_names(var_type, Fmi3Causality.input)) + setattr(self, var_names(var_type, Fmi3Causality.output), input_var) - def do_step(self, current_time: float, step_size: float) -> Fmi3Status: - # feedthrough - for var_type in TYPES: - input_var = getattr(self, var_names(var_type, Fmi3Causality.input)) - setattr(self, var_names(var_type, Fmi3Causality.output), input_var) - - return True + return True diff --git a/examples/arraytypes.py b/examples/arraytypes.py index b04b4ff..b428d1a 100644 --- a/examples/arraytypes.py +++ b/examples/arraytypes.py @@ -1,8 +1,10 @@ - -from pythonfmu3 import Fmi3Causality, Fmi3Variability, Dimension, Fmi3Slave, Fmi3Status, Float64, Int32, Int64, UInt64, String, Boolean - import numpy as np +from pythonfmu3.variables import Boolean, Dimension, Float64, Int32, Int64, UInt64 +from pythonfmu3.enums import Fmi3Causality, Fmi3Variability, Fmi3Status +from pythonfmu3.fmi3slave import Fmi3Slave + + SIZE = 10 TYPES = [UInt64, Float64, Boolean, Int32, Int64] @@ -13,9 +15,10 @@ Float64: np.float64, Int32: np.int32, Int64: np.int64, - Boolean: bool + Boolean: bool, } + def var_names(var_type, causality): return f"{var_type.__name__.lower()}_{causality.name.lower()}" @@ -30,45 +33,64 @@ def init_var(var_type, causality, array=True): def create_vars(self): dimensions = [Dimension(start=str(SIZE))] for var_type in TYPES: - for causality in CAUSALITY: - name = var_names(var_type, causality) - if var_type == Float64: - var = var_type(name, causality=causality, variability=Fmi3Variability.continuous, dimensions=dimensions) - else: - var = var_type(name, causality=causality, variability=Fmi3Variability.discrete, dimensions=dimensions) - setattr(self, name, init_var(var_type, causality)) - self.register_variable(var) + for causality in CAUSALITY: + name = var_names(var_type, causality) + if var_type == Float64: + var = var_type( + name, + causality=causality, + variability=Fmi3Variability.continuous, + dimensions=dimensions, + ) + else: + var = var_type( + name, + causality=causality, + variability=Fmi3Variability.discrete, + dimensions=dimensions, + ) + setattr(self, name, init_var(var_type, causality)) + self.register_variable(var) def generate_random_data(self): for var_type in TYPES: - causality = Fmi3Causality.output - name = var_names(var_type, causality) - var = getattr(self, name) - if var_type == Boolean: - setattr(self, name, np.random.choice(a=[False, True], size=SIZE).astype(bool)) - elif var_type == Int32 or var_type == Int64 or var_type == UInt64: - setattr(self, name, np.random.randint(0, 100, size=SIZE).astype(TYPE_MAP[var_type])) - else: - setattr(self, name, np.random.rand(SIZE).astype(TYPE_MAP[var_type])) + causality = Fmi3Causality.output + name = var_names(var_type, causality) + var = getattr(self, name) + if var_type == Boolean: + setattr( + self, name, np.random.choice(a=[False, True], size=SIZE).astype(bool) + ) + elif var_type == Int32 or var_type == Int64 or var_type == UInt64: + setattr( + self, + name, + np.random.randint(0, 100, size=SIZE).astype(TYPE_MAP[var_type]), + ) + else: + setattr(self, name, np.random.rand(SIZE).astype(TYPE_MAP[var_type])) -class ArrayTypes(Fmi3Slave): - def __init__(self, **kwargs): - super().__init__(**kwargs) +class ArrayTypes(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) - self.author = "Stephen Smith" - self.description = "All types example" + self.author = "Stephen Smith" + self.description = "All types example" - self.time = 0.0 + self.time = 0.0 - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - - create_vars(self) - + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) - def do_step(self, current_time: float, step_size: float) -> Fmi3Status: - generate_random_data(self) - return True + create_vars(self) - + def do_step(self, current_communication_point: float, communication_step_size: float) -> Fmi3Status: + generate_random_data(self) + return True diff --git a/examples/bouncingBall.py b/examples/bouncingBall.py index d95ed60..c20dcf7 100644 --- a/examples/bouncingBall.py +++ b/examples/bouncingBall.py @@ -1,12 +1,30 @@ -from pythonfmu3 import Fmi3Causality, Fmi3Variability, Fmi3Slave, Fmi3Status, Float64, Fmi3Initial, Unit, Float64Type, Fmi3StepResult +import logging -class BouncingBall(Fmi3Slave): +import numpy as np - def __init__(self, **kwargs): - super().__init__(**kwargs) +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.cosimulation import Fmi3StepResult +from pythonfmu3.enums import Fmi3Causality, Fmi3Initial, Fmi3Variability +from pythonfmu3.model_options import Fmi3ModelOptionsCS +from pythonfmu3.model_returns import Fmi3UpdateDiscreteStatesResult +from pythonfmu3.unit import Unit +from pythonfmu3.variables import Float64 + +LOGGER = logging.getLogger(__name__) + +EPS = 1e-13 +class BouncingBall(Fmi3Slave): + def __init__(self, + model_options_cs = Fmi3ModelOptionsCS(**{'canHandleVariableCommunicationStepSize':True, + 'mightReturnEarlyFromDoStep':True, + 'hasEventMode':True}), + **kwargs): + kwargs.update({'model_options_cs' : model_options_cs}) + super().__init__(**kwargs) + self.log(f"FMU Function instantiating: visible:{self.visible}, use events?{self.event_mode_used}") self.author = "..." - self.description = "Bouncing Ball" + self.description = "Bouncing Ball as FMI3 component with event handling" self.time = 0.0 self.h = 1.0 @@ -16,6 +34,8 @@ def __init__(self, **kwargs): self.g = -9.81 self.e = 0.7 self.v_min = 0.1 + self.next_bounce: float + self.energy_min: float # define units unit1 = Unit(name="m", m=1) @@ -23,33 +43,129 @@ def __init__(self, **kwargs): unit3 = Unit(name="m/s2", m=1, s=-2) self.register_units([unit1, unit2, unit3]) + self.register_variable( + Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous) + ) - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) + self.register_variable( + Float64("h", + causality=Fmi3Causality.output, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + unit=unit1.name, + start=1, + )) + self.register_variable( + Float64("derh", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=1, + unit=unit2.name, + )) + self.register_variable( + Float64("v", + causality=Fmi3Causality.output, + start=0, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + unit=unit2.name, + )) + self.register_variable( + Float64("derv", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=3, + unit=unit3.name, + )) - self.register_variable(Float64("ball.h", causality=Fmi3Causality.output, start=1, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact, unit=unit1.name), - nested=False) - self.register_variable(Float64("ball.derh", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=1, unit=unit2.name), - nested=False) - self.register_variable(Float64("ball.v", causality=Fmi3Causality.output, start=0, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact, unit=unit2.name), - nested=False) - self.register_variable(Float64("ball.derv", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=3, unit=unit3.name), - nested=False) + self.register_variable( + Float64("g", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.fixed, + unit=unit3.name, + start="-9.81" + )) + self.register_variable( + Float64("e", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.tunable, + start="0.7" + )) + self.register_variable( + Float64("v_min", causality=Fmi3Causality.parameter, + variability=Fmi3Variability.fixed, + start=0.1) + ) + + def calc_next_bounce(self): + """Calculate the next bounce time as interval from current time.""" + if self.h == 0.0 and self.v == 0.0: # bouncing stopped + return float('inf') + return -self.v/self.g + np.sqrt((self.v/self.g)**2 - 2*self.h/self.g) + + def exit_initialization_mode(self): + self.derv = self.g # constant + self.next_bounce = self.time + self.calc_next_bounce() + self.energy_min = 0.5* self.v_min* self.v_min - self.register_variable(Float64("g", causality=Fmi3Causality.parameter, variability=Fmi3Variability.fixed, unit=unit3.name)) - self.register_variable(Float64("e", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable)) - self.register_variable(Float64("v_min", variability=Fmi3Variability.constant, start=0.1)) - - def do_step(self, current_time, step_size): - self.derv = self.g + def do_step(self, + current_communication_point:float, + communication_step_size:float, + no_set_fmu_state_prior_to_current_point:bool): + self.time = current_communication_point + communication_step_size + assert not self.event_mode_used or self.time < self.next_bounce + EPS, ( + f"Time {self.time} > {self.next_bounce}" + ) self.derh = self.v - self.h += self.derh * step_size - self.v += self.derv * step_size - - if self.h <= 0 and self.v < 0: + self.h += (self.derh + 0.5*self.derv* communication_step_size)*communication_step_size + self.v += self.derv * communication_step_size + + eventHandlingNeeded: bool = False + if self.event_mode_used and abs(self.time - self.next_bounce) < EPS: + eventHandlingNeeded = True # calculate the next bounce + + elif self.h <= 0 and self.v < 0: # when eventMode is not used self.h = 1e-12 - self.v = -self.v*self.e - if self.v < self.v_min: - self.v = 0 - self.g = 0 - - return Fmi3StepResult(status=Fmi3Status.ok) + self.v = -self.v * self.e + + if not self.event_mode_used and 0.5*self.v**2 - self.g*self.h < self.energy_min: # stop the bouncing + self.v = 0 + self.derv = 0 + ret = Fmi3StepResult(eventHandlingNeeded = eventHandlingNeeded, + lastSuccessfullTime = self.time) + return ret + + def update_discrete_states(self): + """Call by Orchestrator to update discrete states in super-dense time instant, + returning info to the Orchestrator on e.g. nextEventTime + + Returns: see definition of Fmi3UpdateDiscreteStatesResult + """ + if self.time > 0.0: + self.h = 0.0 # avoid numerical issues. Bounce always at ground + if abs(self.v) < self.v_min: + self.v = 0.0 + self.derv = 0.0 + else: + self.v = -self.v * self.e + + self.next_bounce = self.time + self.calc_next_bounce() + return Fmi3UpdateDiscreteStatesResult(nextEventTimeDefined=True, + nextEventTime=self.next_bounce) + +if __name__ == "__main__": + from pathlib import Path + + from fmpy import read_model_description + + from pythonfmu3.builder import FmuBuilder + + dest = FmuBuilder.build_FMU( + script_file = Path(__file__), + dest = Path(__file__).parent.resolve(), + #project_files: Iterable[FilePath] = set(), + #documentation_folder: Optional[FilePath] = None, + #terminals : Optional[FilePath] = None, + ) + read_model_description(dest, True, True, True) + print(f"Generated {dest}. Validated modelDescription.") \ No newline at end of file diff --git a/examples/bouncingBall_me.py b/examples/bouncingBall_me.py index e98e7c7..972458f 100644 --- a/examples/bouncingBall_me.py +++ b/examples/bouncingBall_me.py @@ -1,13 +1,17 @@ -from pythonfmu3 import Fmi3Causality, Fmi3Variability, Fmi3SlaveBase, ModelExchange, Fmi3Status, Float64, Fmi3Initial, Unit, Fmi3UpdateDiscreteStatesResult +import sys -from typing import List +from pythonfmu3.variables import Float64 +from pythonfmu3.enums import Fmi3Causality, Fmi3Initial, Fmi3Variability +from pythonfmu3.fmi3slave import Fmi3SlaveBase +from pythonfmu3.model_returns import Fmi3UpdateDiscreteStatesResult +from pythonfmu3.modelexchange import ModelExchange +from pythonfmu3.unit import Unit -import sys EVENT_EPS = 1e-12 -class BouncingBall(Fmi3SlaveBase, ModelExchange): +class BouncingBall(Fmi3SlaveBase, ModelExchange): def __init__(self, **kwargs): super().__init__(**kwargs) @@ -29,47 +33,100 @@ def __init__(self, **kwargs): unit3 = Unit(name="m/s2", m=1, s=-2) self.register_units([unit1, unit2, unit3]) - - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - - self.register_variable(Float64("ball.h", causality=Fmi3Causality.output, start=1, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact, unit=unit1.name), - nested=False, has_event_indicator=True) - self.register_variable(Float64("ball.derh", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=1, unit=unit2.name), - nested=False) - self.register_variable(Float64("ball.v", causality=Fmi3Causality.output, start=0, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact, unit=unit2.name), - nested=False) - self.register_variable(Float64("ball.derv", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=3, unit=unit3.name), - nested=False) - - self.register_variable(Float64("g", causality=Fmi3Causality.parameter, variability=Fmi3Variability.fixed, unit=unit3.name)) - self.register_variable(Float64("e", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable)) - self.register_variable(Float64("v_min", variability=Fmi3Variability.constant, start=0.1)) - - - - def get_continuous_state_derivatives(self) -> List[float]: + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + + self.register_variable( + Float64( + "ball.h", + causality=Fmi3Causality.output, + start=1, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + unit=unit1.name, + ), + nested=False, + has_event_indicator=True, + ) + self.register_variable( + Float64( + "ball.derh", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=1, + unit=unit2.name, + ), + nested=False, + ) + self.register_variable( + Float64( + "ball.v", + causality=Fmi3Causality.output, + start=0, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + unit=unit2.name, + ), + nested=False, + ) + self.register_variable( + Float64( + "ball.derv", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=3, + unit=unit3.name, + ), + nested=False, + ) + + self.register_variable( + Float64( + "g", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.fixed, + unit=unit3.name, + ) + ) + self.register_variable( + Float64( + "e", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.tunable, + ) + ) + self.register_variable( + Float64("v_min", variability=Fmi3Variability.constant, start=0.1) + ) + + def get_continuous_state_derivatives(self) -> list[float]: self.derh = self.v self.derv = self.g return [self.derh, self.derv] - - def get_event_indicators(self) -> List[float]: + + def get_event_indicators(self) -> list[float]: z = [self.h] - if self.h > -EVENT_EPS and self.h <=0 and self.v > 0: + if self.h > -EVENT_EPS and self.h <= 0 and self.v > 0: z[0] = -EVENT_EPS return z - + def update_discrete_states(self): fdsr = Fmi3UpdateDiscreteStatesResult() if self.h <= 0 and self.v < 0: self.h = sys.float_info.min self.v = -self.v * self.e - + if self.v < self.v_min: - self.v = 0.0; - self.g = 0.0; - + self.v = 0.0 + self.g = 0.0 + fdsr.valuesOfContinuousStatesChanged = True return fdsr diff --git a/examples/dahlquist_me.py b/examples/dahlquist_me.py index 763127a..68c117a 100644 --- a/examples/dahlquist_me.py +++ b/examples/dahlquist_me.py @@ -1,9 +1,10 @@ -from pythonfmu3 import Fmi3Causality, ModelExchange, Fmi3Variability, Fmi3SlaveBase, Fmi3Status, Float64, Fmi3Initial, Unit, Float64Type, Fmi3StepResult +from pythonfmu3.variables import Float64 +from pythonfmu3.enums import Fmi3Causality, Fmi3Initial, Fmi3Variability +from pythonfmu3.fmi3slave import Fmi3SlaveBase +from pythonfmu3.modelexchange import ModelExchange -from typing import List class Dahlquist(Fmi3SlaveBase, ModelExchange): - def __init__(self, **kwargs): super().__init__(**kwargs) @@ -15,13 +16,38 @@ def __init__(self, **kwargs): self.x = 1.0 self.derx = 0.0 - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable(Float64("x", causality=Fmi3Causality.output, start=1, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact)) - self.register_variable(Float64("derx", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=1)) - self.register_variable(Float64("k", causality=Fmi3Causality.parameter, variability=Fmi3Variability.fixed)) - - - def get_continuous_state_derivatives(self) -> List[float]: + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + self.register_variable( + Float64( + "x", + causality=Fmi3Causality.output, + start=1, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ) + ) + self.register_variable( + Float64( + "derx", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=1, + ) + ) + self.register_variable( + Float64( + "k", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.fixed, + ) + ) + + def get_continuous_state_derivatives(self) -> list[float]: self.derx = -self.k * self.x return [self.derx] - \ No newline at end of file diff --git a/examples/dahlquist_me_cs.py b/examples/dahlquist_me_cs.py index 01d20f8..bf43cb3 100644 --- a/examples/dahlquist_me_cs.py +++ b/examples/dahlquist_me_cs.py @@ -1,9 +1,12 @@ -from pythonfmu3 import Fmi3Causality, CoSimulation, ModelExchange, Fmi3Variability, Fmi3SlaveBase, Fmi3Status, Float64, Fmi3Initial, Unit, Float64Type, Fmi3StepResult +from pythonfmu3.cosimulation import CoSimulation +from pythonfmu3.variables import Float64 +from pythonfmu3.enums import Fmi3Causality, Fmi3Initial, Fmi3Variability +from pythonfmu3.fmi3slave import Fmi3SlaveBase +from pythonfmu3.model_returns import Fmi3StepResult +from pythonfmu3.modelexchange import ModelExchange -from typing import List class Dahlquist(Fmi3SlaveBase, ModelExchange, CoSimulation): - def __init__(self, **kwargs): super().__init__(**kwargs) @@ -15,17 +18,43 @@ def __init__(self, **kwargs): self.x = 1.0 self.derx = 0.0 - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable(Float64("x", causality=Fmi3Causality.output, start=1, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact)) - self.register_variable(Float64("derx", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=1)) - self.register_variable(Float64("k", causality=Fmi3Causality.parameter, variability=Fmi3Variability.fixed)) - - - def get_continuous_state_derivatives(self) -> List[float]: + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + self.register_variable( + Float64( + "x", + causality=Fmi3Causality.output, + start=1, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ) + ) + self.register_variable( + Float64( + "derx", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=1, + ) + ) + self.register_variable( + Float64( + "k", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.fixed, + ) + ) + + def get_continuous_state_derivatives(self) -> list[float]: self.derx = -self.k * self.x return [self.derx] - - def do_step(self, current_time: float, step_size: float) -> Fmi3StepResult: + + def do_step(self, current_communication_point: float, communication_step_size: float) -> Fmi3StepResult: self.derx = -self.k * self.x - self.x += self.derx * step_size - return True \ No newline at end of file + self.x += self.derx * communication_step_size + return True diff --git a/examples/demoslave.py b/examples/demoslave.py index 7744801..33b2ddc 100644 --- a/examples/demoslave.py +++ b/examples/demoslave.py @@ -1,9 +1,9 @@ -from pythonfmu3 import Fmi3Causality, Fmi3Variability, Fmi3Slave, Float64, String +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.variables import Float64, String +from pythonfmu3.enums import Fmi3Causality, Fmi3Variability class Resistor(Fmi3Slave): - - def __init__(self, **kwargs): super().__init__(**kwargs) @@ -12,29 +12,47 @@ def __init__(self, **kwargs): self.time = 0.0 - self.positive_pin_v = 20. + self.positive_pin_v = 20.0 self.positive_pin_i = 0.001 - self.negative_pin_v = 10. + self.negative_pin_v = 10.0 self.negative_pin_i = 0.001 - self.delta_v = 10. + self.delta_v = 10.0 self.i = 0.001 - self.R = 10000. + self.R = 10000.0 self.stringVariable = "mine" - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable(Float64("R", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable)) + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + self.register_variable( + Float64( + "R", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.tunable, + ) + ) self.register_variable(Float64("positive_pin_v", causality=Fmi3Causality.input)) - self.register_variable(Float64("positive_pin_i", causality=Fmi3Causality.output)) + self.register_variable( + Float64("positive_pin_i", causality=Fmi3Causality.output) + ) self.register_variable(Float64("negative_pin_v", causality=Fmi3Causality.input)) - self.register_variable(Float64("negative_pin_i", causality=Fmi3Causality.output)) + self.register_variable( + Float64("negative_pin_i", causality=Fmi3Causality.output) + ) self.register_variable(Float64("delta_v", causality=Fmi3Causality.local)) self.register_variable(Float64("i", causality=Fmi3Causality.local)) - self.register_variable(String("stringVariable", causality=Fmi3Causality.parameter)) + self.register_variable( + String("stringVariable", causality=Fmi3Causality.parameter) + ) - def do_step(self, current_time, step_size): + def do_step(self, current_communication_point, communication_step_size): self.delta_v = self.positive_pin_v - self.negative_pin_v self.i = i = self.delta_v / self.R self.positive_pin_i = i diff --git a/examples/driving_force3.py b/examples/driving_force3.py new file mode 100644 index 0000000..3ea4305 --- /dev/null +++ b/examples/driving_force3.py @@ -0,0 +1,124 @@ +import logging +from functools import partial +from typing import Any, Callable +import numpy as np +import numpy.typing as npt +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.cosimulation import Fmi3StepResult +from pythonfmu3.enums import Fmi3Variability, Fmi3Causality, Fmi3Initial, Fmi3Status +from pythonfmu3.variables import Boolean, Float64, Int32, UInt64, Dimension +from pythonfmu3.model_returns import Fmi3UpdateDiscreteStatesResult +from pythonfmu3.model_options import Fmi3ModelOptionsCS + +LOGGER = logging.getLogger(__name__) + + +# Note: PythonFMU (which component-model is built on) works on files and thus only one Model class allowed per file + + +def func(time: float, ampl: npt.NDArray[np.float64], omega: npt.NDArray[np.float64], d_omega: float = 0.0): + """Generate a harmonic oscillating force function. + Optionally it is possible to linearly change the angular frequency as omega + d_omega*time. + The function is intended to be initialized through partial, so that only 'time' is left as variable. + """ + if d_omega == 0.0: + return ampl * np.sin(omega * time) + else: + _omega = omega + np.ones_like(omega)* d_omega* time + return ampl * np.sin(_omega * time) + + +class DrivingForce(Fmi3Slave): + """A driving force in 3 dimensions which produces an ouput per time and can be connected to the oscillator.""" + + def __init__(self, **kwargs: Any): + kwargs.update({'model_options_cs' : Fmi3ModelOptionsCS(**{'canHandleVariableCommunicationStepSize':True, + 'mightReturnEarlyFromDoStep':False, + 'hasEventMode':False}), + }) + super().__init__(**kwargs) + self.log(f"FMU instantiating: visible:{self.visible}, use events?{self.event_mode_used}") + self.author = "Siegfried Eisinger" + self.description = "FMI3 version of the oscillator component model" + + self.time = 0.0 + self.ampl = np.array((1.0,) * 3, np.float64) + self.dim = len(self.ampl) + self.freq = np.array( (1.0,) * self.dim, np.float64) + self.d_freq = 0.0 + + self.function = func + self.func: Callable + self.f = np.array((0.0,) * self.dim, np.float64) + self.v_osc = np.array((0.0,) * self.dim, np.float64) + + self.register_variable(Float64("time", causality=Fmi3Causality.independent)) + self._dim = UInt64("dim", + variability=Fmi3Variability.fixed, + causality=Fmi3Causality.structuralParameter, + initial=Fmi3Initial.exact, + start=self.dim) + self.register_variable(self._dim) + self.register_variable(Float64("ampl", + variability=Fmi3Variability.fixed, + causality=Fmi3Causality.parameter, + initial=Fmi3Initial.exact, + dimensions=[Dimension(valueReference=self._dim.value_reference)], + start="1.0 1.0 1.0")) + self.register_variable(Float64("freq", + variability=Fmi3Variability.fixed, + causality=Fmi3Causality.parameter, + initial=Fmi3Initial.exact, + dimensions=[Dimension(valueReference=self._dim.value_reference)], + start="1.0 1.0 1.0")) + self.register_variable(Float64("d_freq", + variability=Fmi3Variability.fixed, + causality=Fmi3Causality.parameter, + initial=Fmi3Initial.exact, + start="0.0")) + self.register_variable(Float64("f", + causality=Fmi3Causality.output, + dimensions=[Dimension(valueReference=self._dim.value_reference)])) + self.register_variable(Float64("v_osc", + causality=Fmi3Causality.input, + dimensions=[Dimension(valueReference=self._dim.value_reference)], + start="0.0 0.0 0.0")) + + def do_step(self, + current_communication_point: float, + communication_step_size: float, + no_set_fmu_state_prior_to_current_point:bool=True) -> Fmi3StepResult: + self.time = current_communication_point + communication_step_size + self.f = self.func(self.time) + ret = Fmi3StepResult(eventHandlingNeeded = False, + lastSuccessfullTime = self.time) + return ret + + def exit_initialization_mode(self): + """Set internal state after initial variables are set.""" + assert isinstance(self.ampl, np.ndarray) + assert isinstance(self.freq, np.ndarray) + assert isinstance(self.d_freq, float) + self.func = partial( + self.function, + ampl=np.array(self.ampl, np.float64), + omega=np.array(2 * np.pi * self.freq, np.float64), + d_omega=2 * np.pi * self.d_freq + ) + self.f = self.func(self.time) + +if __name__ == "__main__": + from pathlib import Path + from pythonfmu3.builder import FmuBuilder + from fmpy import read_model_description + + dest = FmuBuilder.build_FMU( + script_file = Path(__file__), + dest = Path(__file__).parent.resolve(), + #project_files: Iterable[FilePath] = set(), + #documentation_folder: Optional[FilePath] = None, + #terminals : Optional[FilePath] = None, + ) + read_model_description(dest, True, True, True) + print(f"Generated {dest}. Validated modelDescription.") + diff --git a/examples/function.py b/examples/function.py new file mode 100644 index 0000000..44462dc --- /dev/null +++ b/examples/function.py @@ -0,0 +1,148 @@ +"""Implements a function component with n scalar inputs and one output. + The function name can be specified. + + The function triggers only on input events and calculates its output, + i.e. it triggers on update_discrete_states, updating the output, not setting new event times. + do_step only keeps track of time. +""" +import numpy as np +from collections import namedtuple +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.enums import ( + Fmi3IntervalVariability, + Fmi3Causality, + Fmi3Variability, + Fmi3Initial, + Fmi3Status) +from pythonfmu3.variables import Float64, UInt64, String, Dimension +from pythonfmu3.model_returns import Fmi3StepResult, Fmi3UpdateDiscreteStatesResult +from pythonfmu3.model_options import Fmi3ModelOptionsCS + + +EPS = 1e-14 + +class Function(Fmi3Slave): + """Discrete event Function implementation.""" + + def __init__(self, + model_options_cs = Fmi3ModelOptionsCS(**{'canHandleVariableCommunicationStepSize':True, + 'hasEventMode':True}), + **kwargs): + kwargs.update({'model_options_cs' : model_options_cs}) + super().__init__(**kwargs) + self.log(f"FMU Function instantiating: visible:{self.visible}, use events?{self.event_mode_used}") + self.author = "Siegfried Eisinger" + self.description = "Function of its inputs, updating the output" + + # Parameters + self.n_inputs : int = 2 + self.func_name : str = "sum" + self.par : float = 1.0 + + # Inputs + self.inputs: np.ndarray = np.array([0.0]*self.n_inputs, float) + # Outputs + self.output: float = 0.0 + + # Internal states + self.time = 0.0 + self.histogram : list[ tuple[float,int]] = [] + + # Register variables + self.register_variable(Float64("time", causality=Fmi3Causality.independent)) + self._n_inputs = UInt64("n_inputs", + variability=Fmi3Variability.fixed, + causality=Fmi3Causality.structuralParameter, + initial=Fmi3Initial.exact, + start=2) + self.register_variable(self._n_inputs) + self.register_variable(String("func_name", causality=Fmi3Causality.parameter, start="sum")) + self.register_variable(Float64("par", causality=Fmi3Causality.parameter, start=1.0)) + self.register_variable(Float64("inputs", + variability=Fmi3Variability.continuous, + causality=Fmi3Causality.input, + dimensions=[Dimension(valueReference=self._n_inputs.value_reference)], + start=(1.0, 1.0) )) + self.register_variable(Float64("output", causality=Fmi3Causality.output)) + + + def calc(self)-> float: + """Re-calculate the function.""" + if self.func_name == "sum": + if self.par == 1.0: + return sum( x for x in self.inputs) + else: + return self.par* sum( x for x in self.inputs) + elif self.func_name == "and": + res = True + for x in self.inputs: + if not x: + return 0.0 + return 1.0 + elif self.func_name == "or": + res = False + for x in self.inputs: + if x: + return 1.0 + return 0.0 + elif self.func_name == "min": + return min(self.inputs) + elif self.func_name == "max": + return max(self.inputs) + raise NotImplementedError(f"The function {self.func_name} is so far not included.") from None + + def enter_event_mode(self): + """Signal from orchestrator that an event has occured.""" + # print(f"EnterEventMode @{self.time}") + pass + + def enter_step_mode(self): + """Signal from orchestrator that events are dealt with and switching back to step mode.""" + # print(f"EnterStepMode @{self.time}") + pass + + def exit_initialization_mode(self): + # print(f"Initialization finished") + self.output = float('nan') # no inputs that, therefore output is initially undefined + pass + + def do_step(self, + current_communication_point:float, + communication_step_size:float, + no_set_fmu_state_prior_to_current_point:bool): + self.time = current_communication_point + communication_step_size + if not self.event_mode_used: + self.histogram.append( (current_communication_point, self.output)) + self.output = self.calc() + return Fmi3StepResult(eventHandlingNeeded = False, lastSuccessfullTime = self.time) + + def update_discrete_states(self): + """Call by Orchestrator to update discrete states in super-dense time instant, + returning info to the Orchestrator + + Returns: see definition of Fmi3UpdateDiscreteStatesResult + """ + before_update = self.output + after_update = self.calc() + #self.log(f"Update {self.instance_name}(Function): Inputs:{self.inputs}. {before_update} -> {after_update}") + if before_update != after_update: + self.output = after_update + # make sure that all inputs are updated and loops are managed. + return Fmi3UpdateDiscreteStatesResult() + else: + return Fmi3UpdateDiscreteStatesResult() + +if __name__ == "__main__": + from pathlib import Path + from pythonfmu3.builder import FmuBuilder + from fmpy import read_model_description + + dest = FmuBuilder.build_FMU( + script_file = Path(__file__), + dest = Path(__file__).parent.resolve(), + #project_files: Iterable[FilePath] = set(), + #documentation_folder: Optional[FilePath] = None, + #terminals : Optional[FilePath] = None, + ) + read_model_description(dest, True, True, True) + print(f"Generated {dest}. Validated modelDescription.") \ No newline at end of file diff --git a/examples/linearTransform.py b/examples/linearTransform.py deleted file mode 100644 index bd1b837..0000000 --- a/examples/linearTransform.py +++ /dev/null @@ -1,36 +0,0 @@ -from pythonfmu3 import Fmi3Causality, Fmi3Variability, Fmi3Slave, Float64, UInt64, Fmi3Initial, Dimension -import numpy as np - - -class LinearTransformFixed(Fmi3Slave): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - - self.author = "..." - self.description = "Linear transform with fixed size matrix/vector" - - self.time = 0.0 - - self.m = 2 - self.n = 2 - - self.scalar = 2.00 - - self.u = np.array([1.0, 2.0]).reshape((self.m, 1)) - self.offset = np.array([1.0, 2.0]).reshape((self.m, 1)) - self.A = np.array([1.0, 1.0, 2.0, 1.0]).reshape((self.m, self.n)) - self.y = np.array([0.0, 0.0]).reshape((self.n, 1)) - - - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable(Float64("scalar", causality=Fmi3Causality.input, start=2.0)) - self.register_variable(Float64("u", causality=Fmi3Causality.input, dimensions=[Dimension(start="2")])) - self.register_variable(Float64("offset", causality=Fmi3Causality.input, dimensions=[Dimension(start="2")])) - self.register_variable(Float64("A", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable, dimensions=[Dimension(start="2"), Dimension(start="2")])) - self.register_variable(Float64("y", causality=Fmi3Causality.output, dimensions=[Dimension(start="2")])) - - - def do_step(self, current_time, step_size): - self.y = self.scalar*self.A.dot(self.u) + self.offset - return True diff --git a/examples/linearTransform2x2.py b/examples/linearTransform2x2.py new file mode 100644 index 0000000..6794555 --- /dev/null +++ b/examples/linearTransform2x2.py @@ -0,0 +1,83 @@ +import numpy as np + +from pythonfmu3.variables import Dimension, Float64 +from pythonfmu3.enums import Fmi3Causality, Fmi3Variability +from pythonfmu3.fmi3slave import Fmi3Slave + + +class LinearTransform2x2(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + + self.author = "..." + self.description = "Linear transform with fixed size matrix/vector" + + self.time = 0.0 + + self.m = 2 + self.n = 2 + + self.scalar = 2.00 + + self.u = np.array([1.0, 2.0]).reshape((self.m, 1)) + self.offset = np.array([1.0, 2.0]).reshape((self.m, 1)) + self.A = np.array([1.0, 1.0, 2.0, 1.0]).reshape((self.m, self.n)) + self.y = np.array([0.0, 0.0]).reshape((self.n, 1)) + + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + self.register_variable( + Float64("scalar", causality=Fmi3Causality.input, start=2.0) + ) + self.register_variable( + Float64( + "u", causality=Fmi3Causality.input, dimensions=[Dimension(start="2")] + ) + ) + self.register_variable( + Float64( + "offset", + causality=Fmi3Causality.input, + dimensions=[Dimension(start="2")], + ) + ) + self.register_variable( + Float64( + "A", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.tunable, + dimensions=[Dimension(start="2"), Dimension(start="2")], + ) + ) + self.register_variable( + Float64( + "y", causality=Fmi3Causality.output, dimensions=[Dimension(start="2")] + ) + ) + + def do_step(self, + current_communication_point : float, + communication_step_size : float, + no_set_fmu_state_prior_to_current_point : bool): + self.y = self.scalar * self.A.dot(self.u) + self.offset + return True + +if __name__ == "__main__": + from pathlib import Path + from pythonfmu3.builder import FmuBuilder + from fmpy import read_model_description + + dest = FmuBuilder.build_FMU( + script_file = Path(__file__), + dest = Path(__file__).parent.resolve(), + #project_files: Iterable[FilePath] = set(), + #documentation_folder: Optional[FilePath] = None, + #terminals : Optional[FilePath] = None, + ) + read_model_description(dest, True, True, True) + print(f"Generated {dest}. Validated modelDescription.") diff --git a/examples/linear_transform.py b/examples/linear_transform.py new file mode 100644 index 0000000..6f3621a --- /dev/null +++ b/examples/linear_transform.py @@ -0,0 +1,101 @@ +"""Implements a function component with n scalar inputs and one output. + The function name can be specified. + + The function triggers only on input events and calculates its output, + i.e. it triggers on update_discrete_states, updating the output, not setting new event times. + do_step only keeps track of time. +""" +import numpy as np +from collections import namedtuple +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.enums import ( + Fmi3IntervalVariability, + Fmi3Causality, + Fmi3Variability, + Fmi3Status) +from pythonfmu3.variables import Float64, UInt64, String, Dimension +from pythonfmu3.model_returns import Fmi3StepResult, Fmi3UpdateDiscreteStatesResult +from pythonfmu3.model_options import Fmi3ModelOptionsCS + +EPS = 1e-14 + +class LinearTransform(Fmi3Slave): + """Linear transformation of a scalar input value.""" + + def __init__(self, + model_options_cs = Fmi3ModelOptionsCS(**{'canHandleVariableCommunicationStepSize':True, + 'hasEventMode':True}), + **kwargs): + kwargs.update({'model_options_cs' : model_options_cs}) + super().__init__(**kwargs) + self.author = "Siegfried Eisinger" + self.description = "Linear transformation of a scalar input value: y = a + b*x" + + # Internal states + self.time = 0.0 # actually independent of time + + # Parameters + self.a : float = 0.0 # intercept + self.b : float = 1.0 # slope + + # Inputs + self.x: float = 0.0 + # Outputs + self.y: float = self.transform(self.x) + + # Register variables + self.register_variable(Float64("time", causality=Fmi3Causality.independent)) + self.register_variable(Float64("a", causality=Fmi3Causality.parameter, start=0.0)) + self.register_variable(Float64("b", causality=Fmi3Causality.parameter, start=1.0)) + + self.register_variable(Float64("x", causality=Fmi3Causality.input, start=0.0)) + self.register_variable(Float64("y", causality=Fmi3Causality.output)) + + def enter_event_mode(self): + """Signal from orchestrator that an event has occured.""" + # print(f"EnterEventMode @{self.time}") + pass + + def enter_step_mode(self): + """Signal from orchestrator that events are dealt with and switching back to step mode.""" + # print(f"EnterStepMode @{self.time}") + pass + + def exit_initialization_mode(self): + # print(f"Initialization finished") + pass + + def do_step(self, + current_communication_point:float, + communication_step_size:float, + no_set_fmu_state_prior_to_current_point:bool): + self.time = current_communication_point + communication_step_size + self.y = self.transform(self.x) + return Fmi3StepResult(eventHandlingNeeded = False, lastSuccessfullTime = self.time) + + def update_discrete_states(self): + """Call by Orchestrator to update discrete states in super-dense time instant, + returning info to the Orchestrator + + Returns: see definition of Fmi3UpdateDiscreteStatesResult + """ + self.y = self.transform(self.x) + return Fmi3UpdateDiscreteStatesResult() + + def transform(self, x:float): + return self.a + self.b* x + +if __name__ == "__main__": + from pathlib import Path + from pythonfmu3.builder import FmuBuilder + from fmpy import read_model_description + + dest = FmuBuilder.build_FMU( + script_file = Path(__file__), + dest = Path(__file__).parent.resolve(), + #project_files: Iterable[FilePath] = set(), + #documentation_folder: Optional[FilePath] = None, + #terminals : Optional[FilePath] = None, + ) + read_model_description(dest, True, True, True) + print(f"Generated {dest}. Validated modelDescription.") \ No newline at end of file diff --git a/examples/mldemo.py b/examples/mldemo.py index 7cdc2f9..8acda95 100644 --- a/examples/mldemo.py +++ b/examples/mldemo.py @@ -1,16 +1,19 @@ -from pythonfmu3 import Fmi3Causality, Fmi3Slave, Float64 - import pathlib # pathlib is included in the Python Standard Library +from pythonfmu3.variables import Float64 +from pythonfmu3.enums import Fmi3Causality +from pythonfmu3.fmi3slave import Fmi3Slave + try: - import tensorflow as tf import numpy as np -except ImportError: # Trick to be able to generate the FMU without TensorFlow and NumPy installed + import tensorflow as tf +except ( + ImportError +): # Trick to be able to generate the FMU without TensorFlow and NumPy installed np, tf = None, None class MLDemo(Fmi3Slave): - def __init__(self, **kwargs): super().__init__(**kwargs) @@ -28,22 +31,32 @@ def __init__(self, **kwargs): # Fetch saved model from directory included in the FMU self.model = tf.keras.models.load_model(model_dir_path) except AttributeError: - print("Unable to load model from directory. Has TensorFlow been included in the environment?") + print( + "Unable to load model from directory. Has TensorFlow been included in the environment?" + ) except OSError: - print("Unable to load model from directory. Has the correct directory been specified?") + print( + "Unable to load model from directory. Has the correct directory been specified?" + ) else: - print("No model directory found. Has the directory been included in the FMU when building?") + print( + "No model directory found. Has the directory been included in the FMU when building?" + ) - self.sin_input = 0. - self.sin_output_tf = 0. - self.sin_output_ref = 0. + self.sin_input = 0.0 + self.sin_output_tf = 0.0 + self.sin_output_ref = 0.0 self.register_variable(Float64("sin_input", causality=Fmi3Causality.input)) self.register_variable(Float64("sin_output_tf", causality=Fmi3Causality.output)) - self.register_variable(Float64("sin_output_ref", causality=Fmi3Causality.output)) + self.register_variable( + Float64("sin_output_ref", causality=Fmi3Causality.output) + ) - def do_step(self, current_time, step_size): + def do_step(self, current_communication_point, communication_step_size): # Similar to model.predict() with less performance overhead - self.sin_output_tf = self.model(np.array([self.sin_input]), training=False).numpy()[0][0] + self.sin_output_tf = self.model( + np.array([self.sin_input]), training=False + ).numpy()[0][0] self.sin_output_ref = np.sin([self.sin_input])[0] return True diff --git a/examples/oscillator3.py b/examples/oscillator3.py new file mode 100644 index 0000000..32a262d --- /dev/null +++ b/examples/oscillator3.py @@ -0,0 +1,159 @@ +import logging +import numpy as np +import numpy.typing as npt +from scipy import integrate +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.cosimulation import Fmi3StepResult +from pythonfmu3.enums import Fmi3Variability, Fmi3Causality, Fmi3Initial, Fmi3Status +from pythonfmu3.variables import Boolean, Float64, Int32, UInt64, Dimension +from pythonfmu3.model_returns import Fmi3UpdateDiscreteStatesResult +from pythonfmu3.model_options import Fmi3ModelOptionsCS + +LOGGER = logging.getLogger(__name__) + + +class Oscillator(Fmi3Slave): + """Construct a simple model of a general harmonic oscillator, potentially driven by a force. + + The system obeys the equation F(t) - k*x - c*dx/dt = m*d^2x/dt^2 + See also `Wikipedia `_ + + where x shall be a 3D vector with an initial position. F(t)=0 as long as there is not external driving force. + + We use the scipy.integrate.solve_ivp algorithm for the integration (see do_step) + + Args: + k (tuple)=(1.0, 1.0, 1.0): spring constant in N/m. May vary in 3D + c (tuple)=(0.0, 0.0, 0.0): Viscous damping coefficient in N.s/m. May vary in 3D + m (float | tuple)=1.0: Mass of the spring load (spring mass negligible) in kg. Same in all dim. if float + tolerance (float)=1e-5: Optional tolerance in m, i.e. maximum uncertainty in displacement x. + """ + + def __init__(self, **kwargs): + kwargs.update({'model_options_cs' : Fmi3ModelOptionsCS(**{'canHandleVariableCommunicationStepSize' : True, + 'mightReturnEarlyFromDoStep' : False, + 'hasEventMode' :False}), + }) + super().__init__(**kwargs) + self.log(f"FMU instantiating: visible:{self.visible}, use events?{self.event_mode_used}") + self.author = "Siegfried Eisinger" + self.description = "FMI3 version of the oscillator component model" + + self.time = 0.0 + self.k = np.array((1.0, 1.0, 1.0), np.float64) + self.dim = len(self.k) # internal variable + self.c = np.array((0.0, 0.0, 0.0), np.float64) + self.m = np.array((1.0,) * self.dim, np.float64) + self.tolerance = 1e-5 + self.x = np.array((0,) * self.dim, np.float64) + self.v = np.array((0,) * self.dim, np.float64) + self.f = np.array((0,) * self.dim, np.float64) + self.ode : npt.NDArray[np.float64] # Defined after initialization: + + # Register variables + self.register_variable(Float64("time", causality=Fmi3Causality.independent)) + self._dim = UInt64("dim", + variability=Fmi3Variability.fixed, + causality=Fmi3Causality.structuralParameter, + initial=Fmi3Initial.exact, + start=self.dim) + self.register_variable(self._dim) + self.register_variable(Float64("k", + variability=Fmi3Variability.fixed, + causality=Fmi3Causality.parameter, + initial=Fmi3Initial.exact, + dimensions=[Dimension(valueReference=self._dim.value_reference)], + start="1.0 1.0 1.0")) + self.register_variable(Float64("c", + variability=Fmi3Variability.fixed, + causality=Fmi3Causality.parameter, + initial=Fmi3Initial.exact, + dimensions=[Dimension(valueReference=self._dim.value_reference)], + start="0.0 0.0 0.0")) + self.register_variable(Float64("x", + causality=Fmi3Causality.output, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + dimensions=[Dimension(valueReference=self._dim.value_reference)], + start="1.0 0.0 0.0")) + self.register_variable(Float64("v", + causality=Fmi3Causality.output, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + dimensions=[Dimension(valueReference=self._dim.value_reference)], + start="0.0 0.0 0.0")) + self.register_variable(Float64("f", + causality=Fmi3Causality.input, + dimensions=[Dimension(valueReference=self._dim.value_reference)])) + + + def exit_initialization_mode(self): + self.ode = [ # standard ODE matrix (homogeneous system). + np.array(((-self.c[i] / self.m[i], -self.k[i] / self.m[i]), (1, 0)), float) for i in range(self.dim) + ] + + + def ode_func( + self, + t: float, # scalar time + y: np.ndarray, # combined array of position and speed for component i + i: int, # dimension + f: float, + ) -> np.ndarray: # force for component i + res = self.ode[i].dot(y) + if f != 0: + res += np.array((f, 0), float) + return res + + def do_step(self, + current_communication_point: float, + communication_step_size: float, + no_set_fmu_state_prior_to_current_point:bool + ) -> Fmi3StepResult: + """Do one simulation step of size dt. + + We implement a very simplistic algoritm based on difference calculus. + """ + self.time = current_communication_point + communication_step_size + for i in range(self.dim): # this is a xD oscillator + if self.x[i] != 0 or self.v[i] != 0 or self.f[i] != 0: + y0 = np.array([self.v[i], self.x[i]], float) + sol = integrate.solve_ivp( + fun=self.ode_func, + t_span=[current_communication_point, current_communication_point + communication_step_size], + y0=y0, + args=(i, self.f[i]), # axis and force as extra arguments to fun + atol=self.tolerance, + ) + self.x[i] = sol.y[1][-1] + self.v[i] = sol.y[0][-1] + ret = Fmi3StepResult(eventHandlingNeeded = False, + lastSuccessfullTime = self.time) + return ret + + @property + def period(self): + """Calculate the natural period of the oscillator (without damping an).""" + w2 = [] + for i in range(self.dim): + w2i = self.k[i] / self.m[i] - (self.c[i] / 2 / self.m[i]) ** 2 + if w2i > 0: + w2.append(2 * np.pi / np.sqrt(w2i)) + else: + w2.append(float("nan")) # critically or over-damped. There is no period + return w2 + +if __name__ == "__main__": + from pathlib import Path + from pythonfmu3.builder import FmuBuilder + from fmpy import read_model_description + + dest = FmuBuilder.build_FMU( + script_file = Path(__file__), + dest = Path(__file__).parent.resolve(), + #project_files: Iterable[FilePath] = set(), + #documentation_folder: Optional[FilePath] = None, + #terminals : Optional[FilePath] = None, + ) + read_model_description(dest, True, True, True) + print(f"Generated {dest}. Validated modelDescription.") diff --git a/examples/pid_fmu.py b/examples/pid_fmu.py new file mode 100644 index 0000000..317c74f --- /dev/null +++ b/examples/pid_fmu.py @@ -0,0 +1,84 @@ +from pythonfmu3.enums import Fmi3Causality +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.variables import Float64 +from pythonfmu3.model_returns import Fmi3StepResult + +class PIDController(Fmi3Slave): + """PID Controller implementation""" + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + self.author = "PythonFMU3 Team" + self.description = "PID Controller" + + # Inputs + self.setpoint = 0.0 + self.measurement = 0.0 + + # Outputs + self.output = 0.0 + + # Parameters + self.kp = 1.0 # Proportional gain + self.ki = 0.1 # Integral gain + self.kd = 0.01 # Derivative gain + + # Internal states + self.integral_error = 0.0 + self.previous_error = 0.0 + self.first_step = True + + # Register variables + self.register_variable(Float64("time", causality=Fmi3Causality.independent)) + self.register_variable(Float64("setpoint", causality=Fmi3Causality.input, start=0.0)) + self.register_variable(Float64("measurement", causality=Fmi3Causality.input, start=0.0)) + self.register_variable(Float64("output", causality=Fmi3Causality.output)) + self.register_variable(Float64("kp", causality=Fmi3Causality.parameter, start=1.0)) + self.register_variable(Float64("ki", causality=Fmi3Causality.parameter, start=0.1)) + self.register_variable(Float64("kd", causality=Fmi3Causality.parameter, start=0.01)) + + def do_step(self, + current_communication_point : float, + communication_step_size : float, + no_set_fmu_state_prior_to_current_point:bool, + ) -> Fmi3StepResult: + # Calculate error + error = self.setpoint - self.measurement + + # Proportional term + p_term = self.kp * error + + # Integral term + self.integral_error += error * communication_step_size + i_term = self.ki * self.integral_error + + # Derivative term + if self.first_step: + d_term = 0.0 + self.first_step = False + else: + d_term = self.kd * (error - self.previous_error) / communication_step_size + + # PID output + self.output = p_term + i_term + d_term + + # Store error for next iteration + self.previous_error = error + + return True + +if __name__ == "__main__": + from pathlib import Path + from pythonfmu3.builder import FmuBuilder + from fmpy import read_model_description + + dest = FmuBuilder.build_FMU( + script_file = Path(__file__), + dest = Path(__file__).parent.resolve(), + #project_files: Iterable[FilePath] = set(), + #documentation_folder: Optional[FilePath] = None, + #terminals : Optional[FilePath] = None, + ) + read_model_description(dest, True, True, True) + print(f"Generated {dest}. Validated modelDescription.") \ No newline at end of file diff --git a/examples/robertson_me.py b/examples/robertson_me.py index 5f1766d..4ac4659 100644 --- a/examples/robertson_me.py +++ b/examples/robertson_me.py @@ -1,9 +1,10 @@ -from pythonfmu3 import Fmi3Causality, ModelExchange, Fmi3Variability, Fmi3SlaveBase, Fmi3Status, Float64, Fmi3Initial, Unit, Float64Type, Fmi3StepResult +from pythonfmu3.variables import Float64 +from pythonfmu3.enums import Fmi3Causality, Fmi3Initial, Fmi3Variability +from pythonfmu3.fmi3slave import Fmi3SlaveBase +from pythonfmu3.modelexchange import ModelExchange -from typing import List class Robertson(Fmi3SlaveBase, ModelExchange): - def __init__(self, **kwargs): super().__init__(**kwargs) @@ -18,17 +19,67 @@ def __init__(self, **kwargs): self.dery2 = 0.04 self.dery3 = 0.0 - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable(Float64("y1", causality=Fmi3Causality.output, start=1, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact)) - self.register_variable(Float64("y2", causality=Fmi3Causality.output, start=0, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact)) - self.register_variable(Float64("y3", causality=Fmi3Causality.output, start=0, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact)) - self.register_variable(Float64("dery1", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=1)) - self.register_variable(Float64("dery2", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=2)) - self.register_variable(Float64("dery3", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=3)) - + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + self.register_variable( + Float64( + "y1", + causality=Fmi3Causality.output, + start=1, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ) + ) + self.register_variable( + Float64( + "y2", + causality=Fmi3Causality.output, + start=0, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ) + ) + self.register_variable( + Float64( + "y3", + causality=Fmi3Causality.output, + start=0, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ) + ) + self.register_variable( + Float64( + "dery1", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=1, + ) + ) + self.register_variable( + Float64( + "dery2", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=2, + ) + ) + self.register_variable( + Float64( + "dery3", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=3, + ) + ) - def get_continuous_state_derivatives(self) -> List[float]: + def get_continuous_state_derivatives(self) -> list[float]: self.dery1 = -0.04 * self.y1 + 1e4 * self.y2 * self.y3 self.dery2 = 0.04 * self.y1 - 1e4 * self.y2 * self.y3 - 3e7 * self.y2**2 self.dery3 = 3e7 * self.y2**2 - return [self.dery1, self.dery2, self.dery3] \ No newline at end of file + return [self.dery1, self.dery2, self.dery3] diff --git a/examples/sympyslave.py b/examples/sympyslave.py index 3b4b3e1..ac74173 100644 --- a/examples/sympyslave.py +++ b/examples/sympyslave.py @@ -1,13 +1,16 @@ -from pythonfmu3.fmi3slave import Fmi3Slave, Fmi3Causality, Fmi3Variability, Float64 +from pythonfmu3.variables import Float64 +from pythonfmu3.enums import Fmi3Causality, Fmi3Variability +from pythonfmu3.fmi3slave import Fmi3Slave + try: - from sympy import symbols, exp + from sympy import exp, symbols except ImportError: # Trick to be able to generate the FMU without sympy installed symbols, exp = None, None class SympySlave(Fmi3Slave): """This class is an example to demonstrate installing new Python dependencies. - + The code is not efficient. """ @@ -16,15 +19,29 @@ def __init__(self, **kwargs): self.realIn = 22.0 self.realOut = 0.0 - self.tau = 2. - self.a = 5. + self.tau = 2.0 + self.a = 5.0 self.register_variable(Float64("realIn", causality=Fmi3Causality.input)) - self.register_variable(Float64("a", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable)) - self.register_variable(Float64("tau", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable)) + self.register_variable( + Float64( + "a", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.tunable, + ) + ) + self.register_variable( + Float64( + "tau", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.tunable, + ) + ) self.register_variable(Float64("realOut", causality=Fmi3Causality.output)) - def do_step(self, current_time, step_size): + def do_step(self, current_communication_point, communication_step_size): i, a, t, tau = symbols("i, a, t, tau") expr = i * a * (1 - exp(-1 * t / tau)) - self.realOut = expr.evalf(subs={i: self.realIn, a: self.a, t: current_time + step_size, tau: self.tau}) + self.realOut = expr.evalf( + subs={i: self.realIn, a: self.a, t: current_communication_point + communication_step_size, tau: self.tau} + ) return True diff --git a/examples/table.py b/examples/table.py new file mode 100644 index 0000000..dbb8056 --- /dev/null +++ b/examples/table.py @@ -0,0 +1,152 @@ +"""Implements a function component with n scalar inputs and one output. + The function name can be specified. + + The function triggers only on input events and calculates its output, + i.e. it triggers on update_discrete_states, updating the output, not setting new event times. + do_step only keeps track of time. +""" +import numpy as np +from collections import namedtuple +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.enums import ( + Fmi3IntervalVariability, + Fmi3Causality, + Fmi3Variability, + Fmi3Initial, + Fmi3Status) +from pythonfmu3.variables import Float64, UInt64, String, Dimension +from pythonfmu3.model_returns import Fmi3StepResult, Fmi3UpdateDiscreteStatesResult +from pythonfmu3.model_options import Fmi3ModelOptionsCS + +EPS = 1e-14 + +class Table(Fmi3Slave): + """Input table changing values with time.""" + + def __init__(self, + model_options_cs = Fmi3ModelOptionsCS(**{'canHandleVariableCommunicationStepSize':True, + 'hasEventMode':True}), + **kwargs + ): + kwargs.update({'model_options_cs' : model_options_cs}) + super().__init__(**kwargs) + self.log(f"FMU instantiating: visible:{self.visible}, use events?{self.event_mode_used}") + self.author = "Siegfried Eisinger" + self.description = "Table with time values in first column changing row with time." + + # Parameters + self.times = np.array([t for t in np.arange(0,10, 0.9)], float) + self.values = np.array([[t,t**2] for t in self.times], float) + self.n_rows : int = len(self.times) + self.n_cols : int = len(self.values[0]) + + # Inputs + # Outputs + self.outputs: np.ndarray = np.array([0.0]*self.n_cols, float) + + # Internal states + self.time = 0.0 + self.row: int = -1 + self.next_time = self.times[0] + + # Register variables + self.register_variable(Float64("time", causality=Fmi3Causality.independent)) + self._n_rows = UInt64("n_rows", + variability=Fmi3Variability.fixed, + causality=Fmi3Causality.structuralParameter, + initial=Fmi3Initial.exact, + start=self.n_rows) + self.register_variable(self._n_rows) + self._n_cols = UInt64("n_cols", + variability=Fmi3Variability.fixed, + causality=Fmi3Causality.structuralParameter, + initial=Fmi3Initial.exact, + start=self.n_cols) + self.register_variable(self._n_cols) + self.register_variable(Float64("times", + variability=Fmi3Variability.fixed, + causality=Fmi3Causality.parameter, + initial=Fmi3Initial.exact, + dimensions=[Dimension(valueReference=self._n_rows.value_reference)], + #start = str(self.times.flatten()).strip('[').strip(']') + )) + self.register_variable(Float64("values", + variability=Fmi3Variability.fixed, + causality=Fmi3Causality.parameter, + initial=Fmi3Initial.exact, + dimensions=[Dimension(valueReference=self._n_rows.value_reference), + Dimension(valueReference=self._n_cols.value_reference)], + start = str(self.values.flatten()).strip('[').strip(']') + )) + self.register_variable(Float64("outputs", + causality=Fmi3Causality.output, + dimensions=[Dimension(valueReference=self._n_cols.value_reference)])) + + def enter_event_mode(self): + """Signal from orchestrator that an event has occured.""" + # print(f"EnterEventMode @{self.time}") + pass + + def enter_step_mode(self): + """Signal from orchestrator that events are dealt with and switching back to step mode.""" + # print(f"EnterStepMode @{self.time}") + pass + + def exit_initialization_mode(self): + self.row = -1 + # print(f"Initialization finished") + pass + + def enter_configuration_mode(self): + print(f"Start configuration mode") + + def exit_configuration_mode(self): + print(f"Start configuration mode") + + def do_step(self, + current_communication_point:float, + communication_step_size:float, + no_set_fmu_state_prior_to_current_point:bool): + """Do a step and signal the results to the Orchestrator.""" + self.time = current_communication_point + communication_step_size + if self.time >= self.next_time: + if not self.event_mode_used: + _ = self.update_discrete_states() + return Fmi3StepResult(eventHandlingNeeded = False, lastSuccessfullTime = self.time) + else: + return Fmi3StepResult(eventHandlingNeeded = True, lastSuccessfullTime = self.next_time) + else: + return Fmi3StepResult(eventHandlingNeeded = False, lastSuccessfullTime = self.time) + + def update_discrete_states(self): + """Call by Orchestrator to update discrete states in super-dense time instant, + returning info to the Orchestrator + + Returns: see definition of Fmi3UpdateDiscreteStatesResult() + """ + self.row += 1 + if self.row < len(self.values): + if self.row+1 < len(self.values): + self.next_time = self.times[self.row+1] + else: + self.next_time = float('inf') + self.outputs = self.values[self.row] + return Fmi3UpdateDiscreteStatesResult(nextEventTimeDefined = (self.next_time is not None), + nextEventTime = self.next_time) + else: + return Fmi3UpdateDiscreteStatesResult() + +if __name__ == "__main__": + from pathlib import Path + from pythonfmu3.builder import FmuBuilder + from fmpy import read_model_description + + dest = FmuBuilder.build_FMU( + script_file = Path(__file__), + dest = Path(__file__).parent.resolve(), + #project_files: Iterable[FilePath] = set(), + #documentation_folder: Optional[FilePath] = None, + #terminals : Optional[FilePath] = None, + ) + read_model_description(dest, True, True, True) + print(f"Generated {dest}. Validated modelDescription.") \ No newline at end of file diff --git a/examples/tensorflow-model-export/sin-approximation.ipynb b/examples/tensorflow-model-export/sin-approximation.ipynb index 3dedcf4..fe7e08b 100644 --- a/examples/tensorflow-model-export/sin-approximation.ipynb +++ b/examples/tensorflow-model-export/sin-approximation.ipynb @@ -8,51 +8,63 @@ }, "outputs": [], "source": [ + "import matplotlib.pyplot as plt\n", "import numpy as np\n", - "import tensorflow as tf\n", - "import matplotlib.pyplot as plt" + "import tensorflow as tf" ] }, { "cell_type": "code", "execution_count": 4, + "metadata": { + "collapsed": false, + "pycharm": { + "name": "#%%\n" + } + }, "outputs": [], "source": [ "# Parameters\n", "BATCH_SIZE = 32\n", "SAMPLES_PER_BATCH = 1000" - ], + ] + }, + { + "cell_type": "code", + "execution_count": 5, "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } - } - }, - { - "cell_type": "code", - "execution_count": 5, + }, "outputs": [], "source": [ "# Generate training and output data\n", - "x_train = tf.random.uniform(shape=[BATCH_SIZE*SAMPLES_PER_BATCH,], minval=-2.0 * np.pi, maxval=2.0 * np.pi)\n", + "x_train = tf.random.uniform(\n", + " shape=[\n", + " BATCH_SIZE * SAMPLES_PER_BATCH,\n", + " ],\n", + " minval=-2.0 * np.pi,\n", + " maxval=2.0 * np.pi,\n", + ")\n", "y_train = tf.math.sin(x_train)" - ], + ] + }, + { + "cell_type": "code", + "execution_count": 6, "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } - } - }, - { - "cell_type": "code", - "execution_count": 6, + }, "outputs": [ { "data": { - "text/plain": "
", - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYIAAAD4CAYAAADhNOGaAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/MnkTPAAAACXBIWXMAAAsTAAALEwEAmpwYAAAc60lEQVR4nO3df5Bd5X3f8fdHC2rBcSooC0aCRiSjuBGpTdwNtsdtYozkAeJYdqedgQGHcZvRIIzH9qQ/lHia5k/GbeImDYhRbFo8EDNubILGlo2RmtZ1M9i6cjFIEIxK7aIfNWtH2GlhKiR9+8eetS+7995z7j2/z/m8Znb23vPjnu/dfc75Ps9zfjyKCMzMrL/W1B2AmZnVy4nAzKznnAjMzHrOicDMrOecCMzMeu6cugOYxUUXXRQbN26sOwwzs1Y5ePDg9yJifuX0ViaCjRs3MhgM6g7DzKxVJH1n1HR3DZmZ9ZwTgZlZzzkRmJn1nBOBmVnPORGYmfVcIYlA0r2SXpB0aMx8SfoDSUckPSHpTUPzrpP0TDJvZxHxtMHtt4M0+ccsD5cvy6qoy0f/A/CHwKfGzL8e2JT8vBnYBbxZ0hxwF7AVOAockLQnIp4qKK7GmWYHXF7WD4i1aWQtYy5ftqyQFkFEfAX4ywmLbAM+FUseA9ZJuhS4GjgSEc9FxCngwWTZTpq1Fubam2Uxa03fLQSr6hzBBuD5ofdHk2njpq8iabukgaTB4uJiaYGWJe+O5h3VJimifLiM9VdViWBUEYsJ01dPjNgdEQsRsTA/v+oO6UYragfzjmqjFFkuXMb6qapEcBS4fOj9ZcDxCdM7o+gdyzuqDSujPFx5ZfGfac1WVSLYA/xacvXQW4Af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bE/wOIiDaOmvZx4J8zw5CgTRARX07GsQB4jKVR7ZruauBIRDwXEaeAB1mqULRCRJyIiG8kr/+KpQPQhslrNYuky4BfAT5RdyyzkPSTwC8BnwSIiFMR8WIV23YiWO1ngb8v6WuS/oukX6w7oGlIejdwLCK+WXcsBfnHwBfrDiKDDcDzQ++P0rID6TJJG4FfAL5WcyjT+rcsVYDO1hzHrH4aWAT+fdK99QlJr6liw6ljFneRpH3A60bM+ihLf5MLWGoe/yLwGUk/HQ26zjYl/t8C3lltRNOb9B0i4uFkmY+y1GXxQJWxzWjU6MqNKTNZSfoJ4LPAhyPih3XHk5WkdwEvRMRBSW+vOZxZnQO8CfhgRHxN0u8DO4F/WcWGeycitoybJ2kH8LnkwP91SWdZegDUYlXxpRkXv6S/A1wBfFNLo75fBnxD0tUR8b8rDDHVpP8BgKRbgXcB1zYpCU9wFLh86P1lwPGaYpmJpHNZSgIPRMTn6o5nSm8D3i3pBuCvAz8p6f6IuKXmuKZxFDgaEcstsT9hKRGUzl1Dq/0p8A4AST8LrKUlTzKMiCcj4uKI2BgRG1kqWG9qWhJII+k64F8A746Il+qOJ6MDwCZJV0haC9wI7Kk5psy0VHP4JPB0RPxe3fFMKyJ+MyIuS8r9jcB/alkSINlPn5f0+mTStcBTVWy7ly2CFPcC90o6BJwCbm1JjbRL/hD4a8CjScvmsYi4rd6QJouI05LuAB4B5oB7I+JwzWFN423A+4AnJT2eTPutiNhbX0i99EHggaQy8Rzw/io26kdMmJn1nLuGzMx6zonAzKznnAjMzHrOicDMrOecCMzMes6JwMys55wIzMx67v8DgS0ORozq4egAAAAASUVORK5CYII=\n", + "text/plain": "
" }, "metadata": { "needs_background": "light" @@ -62,54 +74,55 @@ ], "source": [ "# Create visualization of the training data\n", - "plt.plot(x_train, y_train, 'bo')\n", + "plt.plot(x_train, y_train, \"bo\")\n", "plt.show()" - ], - "metadata": { - "collapsed": false, - "pycharm": { - "name": "#%%\n" - } - } + ] }, { "cell_type": "code", "execution_count": 7, - "outputs": [], - "source": [ - "# Create model\n", - "model = tf.keras.models.Sequential([\n", - " tf.keras.layers.Dense(16, activation='relu', input_shape=(1,)),\n", - " tf.keras.layers.Dense(16, activation='relu'),\n", - " tf.keras.layers.Dense(1)\n", - "])" - ], "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } - } + }, + "outputs": [], + "source": [ + "# Create model\n", + "model = tf.keras.models.Sequential(\n", + " [\n", + " tf.keras.layers.Dense(16, activation=\"relu\", input_shape=(1,)),\n", + " tf.keras.layers.Dense(16, activation=\"relu\"),\n", + " tf.keras.layers.Dense(1),\n", + " ]\n", + ")" + ] }, { "cell_type": "code", "execution_count": 8, - "outputs": [], - "source": [ - "# Compile model\n", - "model.compile(optimizer='adam',\n", - " loss='mse')" - ], "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } - } + }, + "outputs": [], + "source": [ + "# Compile model\n", + "model.compile(optimizer=\"adam\", loss=\"mse\")" + ] }, { "cell_type": "code", "execution_count": 9, + "metadata": { + "collapsed": false, + "pycharm": { + "name": "#%%\n" + } + }, "outputs": [ { "name": "stdout", @@ -169,17 +182,17 @@ "source": [ "# Train the model\n", "model.fit(x_train, y_train, batch_size=BATCH_SIZE, epochs=20)" - ], + ] + }, + { + "cell_type": "code", + "execution_count": 10, "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } - } - }, - { - "cell_type": "code", - "execution_count": 10, + }, "outputs": [ { "name": "stdout", @@ -190,8 +203,8 @@ }, { "data": { - "text/plain": "
", - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXwAAAD4CAYAAADvsV2wAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/MnkTPAAAACXBIWXMAAAsTAAALEwEAmpwYAAAnF0lEQVR4nO3df5Cc9X3Y8ffn7iSbRXZtreTG6Lhn5RknLXYTY18AG5rimsY2zZgmM+lYXgjgDjdIlazEzZQfN820n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WpoTnOkrr/gAAAAASUVORK5CYII=\n", + "text/plain": "
" }, "metadata": { "needs_background": "light" @@ -205,20 +218,20 @@ "test_outputs = model.predict(test_inputs)\n", "reference = tf.math.sin(test_inputs)\n", "\n", - "plt.plot(test_inputs, test_outputs, 'bo')\n", - "plt.plot(test_inputs, reference, 'ro')\n", + "plt.plot(test_inputs, test_outputs, \"bo\")\n", + "plt.plot(test_inputs, reference, \"ro\")\n", "plt.show()" - ], + ] + }, + { + "cell_type": "code", + "execution_count": 11, "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } - } - }, - { - "cell_type": "code", - "execution_count": 11, + }, "outputs": [ { "name": "stderr", @@ -245,32 +258,32 @@ "source": [ "# Export model\n", "model.save(\"stored-model\")" - ], + ] + }, + { + "cell_type": "code", + "execution_count": 12, "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } - } - }, - { - "cell_type": "code", - "execution_count": 12, + }, "outputs": [], "source": [ "# Load in the saved model\n", "loaded_model = tf.keras.models.load_model(\"stored-model\")" - ], + ] + }, + { + "cell_type": "code", + "execution_count": 13, "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } - } - }, - { - "cell_type": "code", - "execution_count": 13, + }, "outputs": [ { "name": "stdout", @@ -295,13 +308,7 @@ "print(model.predict(np.array([loaded_test_input]), verbose=0)[0][0])\n", "print(\"Reference:\")\n", "print(np.sin([loaded_test_input])[0])" - ], - "metadata": { - "collapsed": false, - "pycharm": { - "name": "#%%\n" - } - } + ] } ], "metadata": { diff --git a/examples/two_state.py b/examples/two_state.py new file mode 100644 index 0000000..a51d787 --- /dev/null +++ b/examples/two_state.py @@ -0,0 +1,158 @@ +"""Implements a two-state discrete event component with states `working=1` and 'failed=0` + The MTTF and MTTR are fixed parameters and the actual TTF is exponentially distributed, + while TTR is modelled as constant time interval. + + When `update_discrete_states` is called, the state changes and a new time interval is calculated, + which is transmitted to the orchestrator as one of its return values. + Clocks are not used in this version. +""" +import logging +import numpy as np +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.enums import Fmi3IntervalVariability, Fmi3Causality, Fmi3Status +from pythonfmu3.variables import Boolean, Float64, Int32, Clock +from pythonfmu3.model_returns import Fmi3StepResult, Fmi3UpdateDiscreteStatesResult +from pythonfmu3.model_options import Fmi3ModelOptionsCS + +LOGGER = logging.getLogger(__name__) + +EPS = 1e-14 + +class TwoState(Fmi3Slave): + """Two-state discrete event implementation""" + + def __init__(self, + model_options_cs = Fmi3ModelOptionsCS(**{'canHandleVariableCommunicationStepSize':True, + 'mightReturnEarlyFromDoStep':True, + 'hasEventMode':True}), + **kwargs + ): + kwargs.update({'model_options_cs' : model_options_cs}) + super().__init__(**kwargs) + self.log(f"FMU instantiating: visible:{self.visible}, use events?{self.event_mode_used}") + self.author = "Siegfried Eisinger" + self.description = "Two-state discrete event system." + + # Parameters + self.mttf = 0.1 # Mean time to failure (ttf exponentially distributed) + self.mttr = 0.01 # Mean time to repair (ttr constant) + self.seed = 1 + self.rng = np.random.default_rng(self.seed) + self.deterministic = False + + # Inputs + + # Outputs + self.state = 1 + + # Internal states + self.next_interval = self.get_next_interval() + self.time = 0.0 + self.next_time = 0.0 + self.histogram : list[ tuple[float,int]] = [] + + # Register variables + self.register_variable(Float64("time", causality=Fmi3Causality.independent)) + self.register_variable(Float64("mttf", causality=Fmi3Causality.parameter, start=1.0)) + self.register_variable(Float64("mttr", causality=Fmi3Causality.parameter, start=0.01)) + self.register_variable(Int32("seed", causality=Fmi3Causality.parameter, start=1)) + self.register_variable(Boolean("deterministic", causality=Fmi3Causality.parameter, start=False)) + self.register_variable(Int32("state", causality=Fmi3Causality.output)) + self.register_variable(Clock("next_interval", + interval_variability=Fmi3IntervalVariability.triggered, + interval_decimal=self.next_interval, + )) + + def get_next_interval(self): + if self.state==0: + return self.mttr + elif self.state==1: + if self.deterministic: + return self.mttf + else: + return self.rng.exponential(self.mttf) + else: + raise ValueError(f"Unallowed state {self.state}") from None + + def enter_event_mode(self): + """Signal from orchestrator that an event has occured.""" + # print(f"EnterEventMode @{self.time}") + pass + + def enter_step_mode(self): + """Signal from orchestrator that events are dealt with and switching back to step mode.""" + # print(f"EnterStepMode @{self.time}") + pass + + def enter_initialization_mode( + self, tolerance: float | None = None, start_time: float = 0.0, stop_time: float | None = None + ) -> None: + self.log(f"enter_initialization_mode(tolerance={tolerance}, start_time={start_time}, stop_time={stop_time}") + + def exit_initialization_mode(self): + txt = f"Initialization finished. hasEventMode:{self.model_options_cs['hasEventMode']}." + txt += f"UseEvents? {getattr(self, 'event_mode_used', False)}" + self.log(txt) + self.rng = np.random.default_rng(self.seed) + + + def do_step(self, + current_communication_point:float, + communication_step_size:float, + no_set_fmu_state_prior_to_current_point:bool + ) -> Fmi3StepResult: + self.time = current_communication_point + communication_step_size + self.histogram.append( (current_communication_point, self.state)) + if self.time >= self.next_time-EPS: + if not self.event_mode_used: + _ = self.update_discrete_states() + ret = Fmi3StepResult(eventHandlingNeeded = False, lastSuccessfullTime = self.time) + else: + ret = Fmi3StepResult(eventHandlingNeeded = True, lastSuccessfullTime = self.next_time) + else: + ret = Fmi3StepResult(eventHandlingNeeded = False, lastSuccessfullTime = self.time) + # self.log(f"DoStep@{current_communication_point}: {ret}") + return ret + + def update_discrete_states(self): + """Call by Orchestrator to update discrete states in super-dense time instant, + returning info to the Orchestrator on e.g. nextEventTime + + Returns: + discreteStatesNeedUpdate: True; the Orchestrator must stay in Event Mode for another event iteration, + starting a new super-dense time instant. Never only return with 'True'! + terminateSimulation: True; the FMU requests to stop the simulation. + nominalsOfContinuousStatesChanged: True; use only for ME! + valuesOfContinuousStatesChanged: False; use only for configuration changes + nextEventTimeDefined: True; the next time event is known and nextEventTime has a valid value. + nextEventTime: contains the absolute time of the next time event if nextEventTimeDefined = True. + The importer must compute up to nextEventTime (or if needed slightly further) + and then enter Event Mode using EnterEventMode. + The FMU must handle this time event during the Event Mode that is entered + by the first call to EnterEventMode, at or after nextEventTime. + If another (e.g. state event) event happens before that nextEventTime, + the previous definition of nextEventTime becomes obsolete. + """ + self.state = 1 if self.time == 0.0 else 1 - self.state + self.next_interval = self.get_next_interval() + self.next_time = self.time + self.next_interval + # self.log(f"Update {self.instance_name}(TwoState) @{self.time} => {self.state}. NextT:{self.next_time}") + return Fmi3UpdateDiscreteStatesResult(discreteStatesNeedUpdate=False, + nextEventTimeDefined=True, + nextEventTime=self.next_time) + + +if __name__ == "__main__": + from pathlib import Path + from pythonfmu3.builder import FmuBuilder + from fmpy import read_model_description + + dest = FmuBuilder.build_FMU( + script_file = Path(__file__), + dest = Path(__file__).parent.resolve(), + #project_files: Iterable[FilePath] = set(), + #documentation_folder: Optional[FilePath] = None, + #terminals : Optional[FilePath] = None, + ) + read_model_description(dest, True, True, True) + print(f"Generated {dest}. Validated modelDescription.") \ No newline at end of file diff --git a/examples/vanderpol_me.py b/examples/vanderpol_me.py index 1aa52f6..f353d8e 100644 --- a/examples/vanderpol_me.py +++ b/examples/vanderpol_me.py @@ -1,9 +1,10 @@ -from pythonfmu3 import Fmi3Causality, ModelExchange, Fmi3Variability, Fmi3SlaveBase, Fmi3Status, Float64, Fmi3Initial, Unit, Float64Type, Fmi3StepResult +from pythonfmu3.variables import Float64 +from pythonfmu3.enums import Fmi3Causality, Fmi3Initial, Fmi3Variability +from pythonfmu3.fmi3slave import Fmi3SlaveBase +from pythonfmu3.modelexchange import ModelExchange -from typing import List class VanDerPol(Fmi3SlaveBase, ModelExchange): - def __init__(self, **kwargs): super().__init__(**kwargs) @@ -17,18 +18,59 @@ def __init__(self, **kwargs): self.derx0 = 0.0 self.derx1 = 0.0 - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable(Float64("x0", causality=Fmi3Causality.output, start=2, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact)) - self.register_variable(Float64("x1", causality=Fmi3Causality.output, start=0, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact)) - self.register_variable(Float64("derx0", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=1)) - self.register_variable(Float64("derx1", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=2)) - self.register_variable(Float64("mu", causality=Fmi3Causality.parameter, variability=Fmi3Variability.fixed)) - + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + self.register_variable( + Float64( + "x0", + causality=Fmi3Causality.output, + start=2, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ) + ) + self.register_variable( + Float64( + "x1", + causality=Fmi3Causality.output, + start=0, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ) + ) + self.register_variable( + Float64( + "derx0", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=1, + ) + ) + self.register_variable( + Float64( + "derx1", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=2, + ) + ) + self.register_variable( + Float64( + "mu", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.fixed, + ) + ) - def get_continuous_state_derivatives(self) -> List[float]: + def get_continuous_state_derivatives(self) -> list[float]: self.derx0 = self.x1 self.derx1 = self.mu * ((1 - self.x0**2) * self.x1) - self.x0 return [self.derx0, self.derx1] - - def get_nominals_of_continuous_states(self, nStates: int) -> List[float]: - return [1.0, 1.0] \ No newline at end of file + + def get_nominals_of_continuous_states(self, nStates: int) -> list[float]: + return [1.0, 1.0] diff --git a/examples/variables.py b/examples/variables.py new file mode 100644 index 0000000..9a3b1e0 --- /dev/null +++ b/examples/variables.py @@ -0,0 +1,182 @@ +"""Defines various variable types and shapes and exports them.""" +import numpy as np +import numpy.typing as npt +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.enums import ( + Fmi3IntervalVariability, + Fmi3Causality, + Fmi3Variability, + Fmi3Initial, + Fmi3Status) +from pythonfmu3.variables import Boolean, Dimension, Enumeration, String +from pythonfmu3.variables import Float64, Float32 +from pythonfmu3.variables import Int64, Int32, Int16, Int8 +from pythonfmu3.variables import UInt64, UInt32, UInt16, UInt8 +from pythonfmu3.model_returns import Fmi3StepResult, Fmi3UpdateDiscreteStatesResult +from pythonfmu3.model_options import Fmi3ModelOptionsCS + +EPS = 1e-14 + +class Variables3(Fmi3Slave): + """Various variables and shapes, always defined as input-output pair.""" + + def __init__(self, + model_options_cs = Fmi3ModelOptionsCS(**{'canHandleVariableCommunicationStepSize':True, + 'hasEventMode':True}), + **kwargs + ): + kwargs.update({'model_options_cs' : model_options_cs}) + super().__init__(**kwargs) + self.log(f"FMU instantiating: visible:{self.visible}, use events?{self.event_mode_used}") + self.author = "Siegfried Eisinger" + self.description = "Defines variaous variable types and shapes as input/output pairs, for testing purposes." + + # Parameters + + # Inputs + self.bool_in: bool = True + self.str_in: str = "Hello World" + self.float32_in: np.float32 = 3.2 + self.float64_in: np.float64 = 6.4 + self.int8_in: np.int8 = -8 + self.uint8_in: np.uint8 = 8 + self.int16_in: np.int16 = -16 + self.uint16_in: np.uint16 = 16 + self.int32_in: np.int32 = -32 + self.uint32_in: np.uint32 = 32 + self.int64_in: np.int64 = -64 + self.uint64_in: np.uint64 = 64 + self.enumeration_in: np_int32 = 99 + self.arr_float64_in: npt.NDArray[np.float64] = np.array( (0,1,2,3,4,5,6,7,8,9), np.float64) + self.arr_int32_in: npt.NDArray[np.int32] = np.array( (0,1,2,3,4,5,6,7,8,9), np.int32) + # self.clock_in: bool + + # Outputs + self.bool_out: bool + self.str_out: str + self.float32_out: np.float32 + self.float64_out: np.float64 + self.int8_out: np.int8 + self.uint8_out: np.uint8 + self.int16_out: np.int16 + self.uint16_out: np.uint16 + self.int32_out: np.int32 + self.uint32_out: np.uint32 + self.int64_out: np.int64 + self.uint64_out: np.uint64 + self.enumeration_out: int + self.arr_float64_out: npt.NDArray[np.float64] + self.arr_int32_out: npt.NDArray[np.int32] + # self.clock_out: bool + + self.update_out() + + # Internal states + self.time = 0.0 + + # Register variables + self.register_variable(Float64("time", causality=Fmi3Causality.independent)) + + _discrete = Fmi3Variability.discrete + _continuous = Fmi3Variability.continuous + _input = Fmi3Causality.input + _output = Fmi3Causality.output + self.register_variable(Boolean("bool_in", variability=_discrete, causality=_input, start=True)) + self.register_variable(String("str_in", variability=_discrete, causality=_input, start="Hello World")) + self.register_variable(Float64("float64_in", variability=_continuous, causality=_input, start="6.4")) + self.register_variable(Float32("float32_in", variability=_continuous, causality=_input, start="3.2")) + self.register_variable(Int64("int64_in", variability=_discrete, causality=_input, start="-64")) + self.register_variable(Int32("int32_in", variability=_discrete, causality=_input, start="-32")) + self.register_variable(Int16("int16_in", variability=_discrete, causality=_input, start="-16")) + self.register_variable(Int8("int8_in", variability=_discrete, causality=_input, start="-8")) + self.register_variable(UInt64("uint64_in", variability=_discrete, causality=_input, start="64")) + self.register_variable(UInt32("uint32_in", variability=_discrete, causality=_input, start="32")) + self.register_variable(UInt16("uint16_in", variability=_discrete, causality=_input, start="16")) + self.register_variable(UInt8("uint8_in", variability=_discrete, causality=_input, start="8")) + #??self.register_variable(Enumeration("enumeration_in", variability=_discrete, causality=_input, start="99")) + self.register_variable(Float64("arr_float64_in", variability=_continuous, causality=_input, + dimensions=[Dimension(start=10)], start="0 1 2 3 4 5 6 7 8 9")) + self.register_variable(Int32("arr_int32_in", variability=_discrete, causality=_input, + dimensions=[Dimension(start=5), Dimension(start=2)], start="0 1 2 3 4 5 6 7 8 9")) + + #self.register_variable(Boolean("bool_out", variability=_discrete, causality=_input))#, start=True)) + self.register_variable(String("str_out", variability=_discrete, causality=_input, start="Hello World")) + self.register_variable(Float64("float64_out", variability=_continuous, causality=_input, start="6.4")) + self.register_variable(Float32("float32_out", variability=_continuous, causality=_input, start="3.2")) + self.register_variable(Int64("int64_out", variability=_discrete, causality=_input, start="-64")) + self.register_variable(Int32("int32_out", variability=_discrete, causality=_input, start="-32")) + self.register_variable(Int16("int16_out", variability=_discrete, causality=_input, start="-16")) + self.register_variable(Int8("int8_out", variability=_discrete, causality=_input, start="-8")) + self.register_variable(UInt64("uint64_out", variability=_discrete, causality=_input, start="64")) + self.register_variable(UInt32("uint32_out", variability=_discrete, causality=_input, start="32")) + self.register_variable(UInt16("uint16_out", variability=_discrete, causality=_input, start="16")) + self.register_variable(UInt8("uint8_out", variability=_discrete, causality=_input, start="8")) + self.register_variable(Float64("arr_float64_out", variability=_continuous, causality=_output, + dimensions=[Dimension(start=10)])) + self.register_variable(Int32("arr_int32_out", variability=_discrete, causality=_output, + dimensions=[Dimension(start=5), Dimension(start=2)])) + + + def update_out(self): + self.bool_out = self.bool_in + self.str_out = self.str_in + self.float32_out = self.float32_in + self.float64_out = self.float64_in + self.int8_out = self.int8_in + self.uint8_out = self.uint8_in + self.int16_out = self.int16_in + self.uint16_out = self.uint16_in + self.int32_out = self.int32_in + self.uint32_out = self.uint32_in + self.int64_out = self.int64_in + self.uint64_out = self.uint64_in + self.enumeration_out = self.enumeration_in + self.arr_float64_out = self.arr_float64_in + self.arr_int32_out = self.arr_int32_in + + # self.clock_out = self.clock_in + + def do_step(self, + current_communication_point:float, + communication_step_size:float, + no_set_fmu_state_prior_to_current_point:bool): + self.time = current_communication_point + communication_step_size + self.update_out() + return Fmi3StepResult(eventHandlingNeeded = False, lastSuccessfullTime = self.time) + + def update_discrete_states(self): + """Call by Orchestrator to update discrete states in super-dense time instant, + returning info to the Orchestrator + + Returns: + discreteStatesNeedUpdate: True; the Orchestrator must stay in Event Mode for another event iteration, + starting a new super-dense time instant. + terminateSimulation: True; the FMU requests to stop the simulation. + nominalsOfContinuousStatesChanged: True; use only for ME! + valuesOfContinuousStatesChanged: False; use only for configuration changes + nextEventTimeDefined: True; the next time event is known and nextEventTime has a valid value. + nextEventTime: contains the absolute time of the next time event if nextEventTimeDefined = True. + The importer must compute up to nextEventTime (or if needed slightly further) + and then enter Event Mode using EnterEventMode. + The FMU must handle this time event during the Event Mode that is entered + by the first call to EnterEventMode, at or after nextEventTime. + If another (e.g. state event) event happens before that nextEventTime, + the previous definition of nextEventTime becomes obsolete. + """ + self.update_out() + return Fmi3UpdateDiscreteStatesResult() + +if __name__ == "__main__": + from pathlib import Path + from pythonfmu3.builder import FmuBuilder + from fmpy import read_model_description + + dest = FmuBuilder.build_FMU( + script_file = Path(__file__), + dest = Path(__file__).parent.resolve(), + #project_files: Iterable[FilePath] = set(), + #documentation_folder: Optional[FilePath] = None, + #terminals : Optional[FilePath] = None, + ) + read_model_description(dest, True, True, True) + print(f"Generated {dest}. Validated modelDescription.") \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 612f1a6..9a0b3d8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,23 +2,47 @@ requires = ["hatchling"] build-backend = "hatchling.build" +[tool.hatch.build.targets.sdist] +include = [ + "src/pythonfmu3", + "resources/*.dll", + "resources/*.dylib", + "resources/*.so", + "examples/*.fmu", + "examples/*.py", + "pyproject.toml", + "pytest.ini", + "ruff.toml", + "uv.lock", +] + +[tool.hatch.build.targets.wheel] +packages = [ + "src/pythonfmu3", +] + +[tool.hatch.metadata] +allow-direct-references = true + [project] name = "pythonfmu3" -version = "0.3.4" +version = "0.4.0" description = "A lightweight framework that enables the packaging of Python3.x code as co-simulation FMUs with (partial) FMI3 features support." readme = "README.md" +requires-python = ">= 3.12" license = { file = "LICENSE" } authors = [ + { name = "Lars Ivar Hatledal"}, { name = "Stephen Smith" }, + { name = "Siegfried Eisinger", email = "siegfried.eisinger@dnv.com" }, ] keywords = [ - "FMI", "simulation" + "FMI", "simulation", "co-simulation", "FMI3" ] classifiers = [ "Development Status :: 3 - Alpha", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", @@ -35,27 +59,23 @@ classifiers = [ "License :: OSI Approved :: MIT License", "Natural Language :: English", ] +dependencies = [ + "fmpy>=0.3.21", +# "pyqt6>=6.10", + "xmlschema>=4.3", +] + [project.optional-dependencies] tests = [ "fmpy", "pytest", + "scipy", ] [project.scripts] pythonfmu3 = "pythonfmu3.__main__:cli_main" -[tool.hatch.version] -path = "pythonfmu3/__init__.py" - -[tool.hatch.build.targets.sdist] -include = [ - "/pythonfmu3", - "resources/*.dll", - "resources/*.dylib", - "resources/*.so", -] - [project.urls] Homepage = "https://github.com/stephensmith25/PythonFMU3" Documentation = "https://github.com/stephensmith25/PythonFMU3/README.html" @@ -78,6 +98,7 @@ dev = [ "furo>=2025.12", "scipy-stubs>=1.17.1", "matplotlib>=3.10", + "rope>=1.15.0", ] [tool.uv] @@ -92,5 +113,69 @@ required-environments = [ # "sys_platform == 'darwin'", ] +[tool.mypy] +plugins = [] +mypy_path = "stubs" +files = [ + "src", + "tests", + "examples", +] + +[tool.pytest] +# addopts = ["--strict-markers"] +markers = [ + "integration: marks integration tests", + "doc: marks documentation tests" +] +[tool.pyright] +stubPath = "stubs" +include = [ + "src", + "tests", + "examples", +] +exclude = [ + "**/node_modules", + "**/__pycache__", + "**/.*", + ".venv", + "examples", # python code here comes from other sources + "tests/test_working_directory", +] +typeCheckingMode = "basic" +useLibraryCodeForTypes = true +reportMissingParameterType = "error" +reportUnknownParameterType = "warning" +reportUnknownMemberType = "warning" # consider to set to `false` if you work a lot with matplotlib and pandas, which are both not properly typed and known to trigger this warning +reportMissingTypeArgument = "error" +reportPropertyTypeMismatch = "error" +reportFunctionMemberAccess = "warning" +reportPrivateUsage = "warning" +reportTypeCommentUsage = "warning" +reportIncompatibleMethodOverride = "warning" +reportIncompatibleVariableOverride = "error" +reportInconsistentConstructor = "error" +reportOverlappingOverload = "warning" +reportUninitializedInstanceVariable = "warning" +reportCallInDefaultInitializer = "warning" +reportUnnecessaryIsInstance = "information" +reportUnnecessaryCast = "warning" +reportUnnecessaryComparison = "warning" +reportUnnecessaryContains = "warning" +reportUnusedCallResult = "warning" +reportUnusedExpression = "warning" +reportMatchNotExhaustive = "warning" +reportUntypedFunctionDecorator = "warning" +reportUntypedClassDecorator = "warning" +reportUntypedBaseClass = "error" +reportUntypedNamedTuple = "warning" +reportUnnecessaryTypeIgnoreComment = "information" +# Activate the following rules only locally and temporary, i.e. for a QA session. +# (For server side CI they are considered too strict.) +# reportMissingTypeStubs = true +# reportConstantRedefinition = "warning" +# reportImportCycles = "warning" +# reportImplicitStringConcatenation = "warning" diff --git a/pythonfmu3/__init__.py b/pythonfmu3/__init__.py deleted file mode 100644 index d5e7048..0000000 --- a/pythonfmu3/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -from ._version import __version__ -from .builder import FmuBuilder -from .cosimulation import CoSimulation -from .modelexchange import ModelExchange, Fmi3UpdateDiscreteStatesResult -from .enums import Fmi3Causality, Fmi3Initial, Fmi3Status, Fmi3Variability -from .fmi3slave import Fmi3Slave, Fmi3SlaveBase, Fmi3StepResult -from .variables import Boolean, Enumeration, Int32, Int64, UInt64, Float64, String, Dimension -from .default_experiment import DefaultExperiment -from .variable_types import Float64Type, EnumerationType -from .unit import BaseUnit, Unit diff --git a/pythonfmu3/_version.py b/pythonfmu3/_version.py deleted file mode 100644 index 334b899..0000000 --- a/pythonfmu3/_version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "0.3.4" diff --git a/pythonfmu3/builder.py b/pythonfmu3/builder.py deleted file mode 100644 index 58be085..0000000 --- a/pythonfmu3/builder.py +++ /dev/null @@ -1,289 +0,0 @@ -"""Python FMU builder""" -import argparse -import importlib -import itertools -import logging -import re -import shutil -import sys -import tempfile -import zipfile -from pathlib import Path -from typing import Iterable, Optional, Tuple, Union -from xml.dom.minidom import parseString -from xml.etree.ElementTree import Element, SubElement, tostring -from .osutil import get_lib_extension, get_platform -from .fmi3slave import FMI3_MODEL_OPTIONS_COMMON, FMI3_MODEL_OPTIONS_COSIM, FMI3_MODEL_OPTIONS_MX, Fmi3Slave, Fmi3SlaveBase - -FilePath = Union[str, Path] -HERE = Path(__file__).parent - -logger = logging.getLogger(__name__) - - -def get_class_name(file_name: Path) -> str: - with open(str(file_name), 'r') as file: - data = file.read() - return re.search(r'class (\w+)\(([^)]*\bFmi3Slave(?:Base)?\b[^)]*)\)\s*:', data).group(1) - - -def get_model_description(filepath: Path, module_name: str) -> Tuple[str, Element]: - """Extract the FMU model description as XML. - - Args: - filepath (pathlib.Path) : script file path - module_name (str) : python module to load - - Returns: - Tuple[str, xml.etree.TreeElement.Element] : FMU model name, model description - """ - # Add current folder to handle local dependencies - sys.path.insert(0, str(filepath.parent)) - try: - # Import the user interface - spec = importlib.util.spec_from_file_location(module_name, filepath) - fmu_interface = importlib.util.module_from_spec(spec) - spec.loader.exec_module(fmu_interface) - # Instantiate the interface - class_name = get_class_name(filepath) - instance = getattr(fmu_interface, class_name)(instance_name="dummyInstance", resources=str(filepath.parent)) - finally: - sys.path.remove(str(filepath.parent)) # remove inserted temporary path - - if not isinstance(instance, Fmi3SlaveBase): - raise TypeError( - f"The provided class '{class_name}' does not inherit from {Fmi3SlaveBase.__qualname__}" - ) - # Produce the xml - return instance.modelName, instance.to_xml() - - -class FmuBuilder: - - @staticmethod - def build_FMU( - script_file: FilePath, - dest: FilePath = ".", - project_files: Iterable[FilePath] = set(), - documentation_folder: Optional[FilePath] = None, - terminals : Optional[FilePath] = None, - **options, - ) -> Path: - script_file = Path(script_file) - if not script_file.exists(): - raise ValueError(f"No such file {script_file!s}") - if not script_file.suffix.endswith(".py"): - raise ValueError(f"File {script_file!s} must have extension '.py'!") - - dest = Path(dest) - if not dest.exists(): - dest.mkdir(parents=True) - project_files = set(map(Path, project_files)) - - if documentation_folder is not None: - documentation_folder = Path(documentation_folder) - if not documentation_folder.exists(): - raise ValueError( - f"The documentation folder does not exists {documentation_folder!s}" - ) - - if terminals is not None: - terminals = Path(terminals) - if not terminals.exists(): - raise ValueError( - f"The specified terminalsAndIcons file does not exists {terminals!s}" - ) - if not terminals.name == "terminalsAndIcons.xml": - raise ValueError( - f"Incorrect terminal name {terminals!s}. Terminal file must be named terminalsAndIcons.xml" - ) - - module_name = script_file.stem - - with tempfile.TemporaryDirectory(prefix="pythonfmu_") as tempd: - temp_dir = Path(tempd) - shutil.copy2(script_file, temp_dir) - - # Embed pythonfmu in the FMU so it does not need to be included - dep_folder = temp_dir / "pythonfmu3" - dep_folder.mkdir() - for dep in HERE.glob('*.py'): # Find all python files at the same level as this one - shutil.copy2(dep, dep_folder) - for file_ in project_files: - if file_ == script_file.parent: - new_folder = temp_dir / file_.name - new_folder.mkdir() - for f in file_.iterdir(): - if f.is_dir(): - temp_dest = new_folder / f.name - shutil.copytree(f, temp_dest) - elif f.name != script_file.name: - shutil.copy2(f, new_folder) - else: - logger.debug( - "Skip file with the same name as the script found in project file." - ) - else: - if file_.is_dir(): - temp_dest = temp_dir / file_.name - shutil.copytree(file_, temp_dest) - else: - shutil.copy2(file_, temp_dir) - - model_identifier, xml = get_model_description( - temp_dir.absolute() / script_file.name, module_name - ) - - dest_file = dest / f"{model_identifier}.fmu" - - type_node = xml.find("CoSimulation") - option_names = [opt.name for opt in FMI3_MODEL_OPTIONS_COMMON] - cosim_option_names = option_names.copy() - cosim_option_names.extend(opt.name for opt in FMI3_MODEL_OPTIONS_COSIM) - if type_node is not None: - for option, value in options.items(): - if option in cosim_option_names: - type_node.set(option, str(value).lower()) - - type_node = xml.find("ModelExchange") - mx_option_names = option_names.copy() - mx_option_names.extend(opt.name for opt in FMI3_MODEL_OPTIONS_MX) - if type_node is not None: - for option, value in options.items(): - if option in mx_option_names: - type_node.set(option, str(value).lower()) - - with zipfile.ZipFile(dest_file, "w") as zip_fmu: - - resource = Path("resources") - - # Add files copied in temporary directory - for f in temp_dir.rglob("*"): - if f.is_file() and f.parent.name != "__pycache__": - relative_f = f.relative_to(temp_dir) - zip_fmu.write(f, arcname=(resource / relative_f)) - - # Add information for the Python loader - zip_fmu.writestr(str(resource.joinpath("slavemodule.txt")), module_name) - - # Add FMI API wrapping Python class source - sources = Path("sources") - src = HERE / "pythonfmu-export" - for f in itertools.chain( - src.rglob("*.hpp"), src.rglob("*.cpp"), src.rglob("CMakeLists.txt") - ): - relative_f = f.relative_to(src) - if "build" in relative_f.parts: - continue; - zip_fmu.write(f, arcname=(sources / relative_f)) - - # Add FMI API wrapping Python class library - binaries = Path("binaries") - src_binaries = HERE / "resources" / "binaries" - for f in itertools.chain( - src_binaries.rglob("*.dll"), - src_binaries.rglob("*.so"), - src_binaries.rglob("*.dylib"), - ): - relative_f = f.relative_to(src_binaries) - arcname = ( - binaries - / relative_f.parent - / f"{model_identifier}{relative_f.suffix}" - ) - zip_fmu.write(f, arcname=arcname) - - # Add the documentation folder - if documentation_folder is not None: - documentation = Path("documentation") - for f in documentation_folder.rglob("*"): - if f.is_file(): - relative_f = f.relative_to(documentation_folder) - zip_fmu.write(f, arcname=(documentation / relative_f)) - - if terminals is not None: - terminalsFolder = Path("terminalsAndIcons") - relative_f = terminals.relative_to(terminals.parent) - zip_fmu.write(f, arcname=(terminalsFolder / relative_f)) - - - # Add the model description - xml_str = parseString(tostring(xml, "UTF-8")) - zip_fmu.writestr( - "modelDescription.xml", xml_str.toprettyxml(encoding="UTF-8") - ) - - return dest_file - - @staticmethod - def has_binary() -> bool: - """Does the binary for this platform exits?""" - binary_folder = get_platform() - lib_ext = get_lib_extension() or "*" # if library extension is unknown, it will look for '*.*' in src_binaries - src_binaries = HERE / "resources" / "binaries" / binary_folder - return src_binaries.exists() and len(list(src_binaries.glob(f"*.{lib_ext}"))) >= 1 - - -def create_command_parser(parser: argparse.ArgumentParser): - parser.add_argument( - "-f", - "--file", - dest="script_file", - help="Path to the Python script.", - required=True - ) - - parser.add_argument( - "-d", "--dest", dest="dest", help="Where to save the FMU.", default="." - ) - - parser.add_argument( - "--doc", - dest="documentation_folder", - help="Documentation folder to include in the FMU.", - default=None - ) - - parser.add_argument( - "--terminals", - dest="terminals", - help="Terminals file (terminalsAndIcons.xml) to include in the FMU.", - default=None - ) - - for option in FMI3_MODEL_OPTIONS_COMMON: - action = "store_false" if option.value else "store_true" - parser.add_argument( - f"--{option.cli}", - dest=option.name, - help=f"If given, {option.name}={action[6:]}", - action=action - ) - - for option in FMI3_MODEL_OPTIONS_COSIM: - action = "store_false" if option.value else "store_true" - parser.add_argument( - f"--{option.cli}", - dest=option.name, - help=f"If given, {option.name}={action[6:]}", - action=action - ) - - for option in FMI3_MODEL_OPTIONS_MX: - action = "store_false" if option.value else "store_true" - parser.add_argument( - f"--{option.cli}", - dest=option.name, - help=f"If given, {option.name}={action[6:]}", - action=action - ) - - parser.add_argument( - "project_files", - metavar="Project files", - nargs="*", - help="Additional project files required by the Python script.", - default=set() - ) - - parser.set_defaults(execute=FmuBuilder.build_FMU) diff --git a/pythonfmu3/cosimulation.py b/pythonfmu3/cosimulation.py deleted file mode 100644 index 84665e1..0000000 --- a/pythonfmu3/cosimulation.py +++ /dev/null @@ -1,8 +0,0 @@ -from abc import ABC, abstractmethod - -# co-simulation mixin -class CoSimulation(ABC): - - @abstractmethod - def do_step(self, current_time: float, step_size: float): - pass \ No newline at end of file diff --git a/pythonfmu3/default_experiment.py b/pythonfmu3/default_experiment.py deleted file mode 100644 index c0aabb2..0000000 --- a/pythonfmu3/default_experiment.py +++ /dev/null @@ -1,7 +0,0 @@ -class DefaultExperiment: - - def __init__(self, start_time: float = None, stop_time: float = None, step_size: float = None, tolerance: float = None): - self.start_time = start_time - self.stop_time = stop_time - self.step_size = step_size - self.tolerance = tolerance diff --git a/pythonfmu3/fmi3slave.py b/pythonfmu3/fmi3slave.py deleted file mode 100644 index 2a95dc1..0000000 --- a/pythonfmu3/fmi3slave.py +++ /dev/null @@ -1,555 +0,0 @@ -"""Define the abstract facade class.""" -import json -import ctypes -import datetime -from abc import ABC, abstractmethod -from collections import OrderedDict, namedtuple -from pathlib import Path -from typing import Any, ClassVar, Dict, List, NamedTuple, Optional -from uuid import uuid1 -from xml.etree.ElementTree import Element, SubElement - -from .logmsg import LogMsg -from .default_experiment import DefaultExperiment -from .cosimulation import CoSimulation -from .modelexchange import ModelExchange -from ._version import __version__ as VERSION -from .enums import Fmi3Type, Fmi3Status, Fmi3Causality, Fmi3Initial, Fmi3Variability -from .variables import Boolean, Enumeration, Int32, Int64, UInt64, Float64, ModelVariable, String -from .variable_types import VariableType -from .unit import Unit - -ModelOptions = namedtuple("ModelOptions", ["name", "value", "cli"]) - -FMI3_MODEL_OPTIONS_COMMON: List[ModelOptions] = [ - ModelOptions("needsExecutionTool", True, "no-external-tool"), - ModelOptions("canBeInstantiatedOnlyOncePerProcess", False, "only-one-per-process"), - ModelOptions("canGetAndSetFMUState", False, "handle-state"), - ModelOptions("canSerializeFMUState", False, "serialize-state") -] - -FMI3_MODEL_OPTIONS_COSIM: List[ModelOptions] = [ - ModelOptions("canHandleVariableCommunicationStepSize", True, "no-variable-step"), -] - -FMI3_MODEL_OPTIONS_MX: List[ModelOptions] = [ - ModelOptions("needsCompletedIntegratorStep", False, "needs-completed-step"), -] - - -class Fmi3StepResult(NamedTuple): - status: Fmi3Status = Fmi3Status.ok - eventHandlingNeeded: bool = False - terminateSimulation: bool = False - earlyReturn: bool = False - - -class Fmi3SlaveBase(object): - """Abstract facade class to execute Python through FMI standard.""" - - # Dictionary of (category, description) entries - log_categories: Dict[str, str] = { - "logStatusWarning": "Log messages with fmi3Warning status.", - "logStatusDiscard": "Log messages with fmi3Discard status.", - "logStatusError": "Log messages with fmi3Error status.", - "logStatusFatal": "Log messages with fmi3Fatal status.", - "logAll": "Log all messages." - } - - def __init__(self, **kwargs): - self.vars = OrderedDict() - self.event_indicators: List[int] = [] - self.instance_name = kwargs["instance_name"] - self.resources = kwargs.get("resources", None) - self.visible = kwargs.get("visible", False) - self.log_queue = [] - - self.guid = uuid1() - self.author: Optional[str] = None - self.license: Optional[str] = None - self.version: Optional[str] = None - self.copyright: Optional[str] = None - self.modelName: Optional[str] = self.__class__.__name__ - self.description: Optional[str] = None - self.default_experiment: Optional[DefaultExperiment] = None - - self.type_definitions: Dict[str, VariableType] = {} - self.units: Dict[str, Unit] = {} - - def to_xml(self, model_options: Dict[str, str] = dict()) -> Element: - """Build the XML representation of the model. - - Args: - model_options (Dict[str, str]) : FMU model options - - Returns: - (xml.etree.TreeElement.Element) XML description of the FMU - """ - - t = datetime.datetime.now(datetime.timezone.utc) - date_str = t.isoformat(timespec="seconds") - - attrib = dict( - fmiVersion="3.0", - modelName=self.modelName, - instantiationToken=f"{self.guid!s}", - generationTool=f"PythonFMU3 {VERSION}", - generationDateAndTime=date_str, - variableNamingConvention="structured" - ) - if self.description is not None: - attrib["description"] = self.description - if self.author is not None: - attrib["author"] = self.author - if self.license is not None: - attrib["license"] = self.license - if self.version is not None: - attrib["version"] = self.version - if self.copyright is not None: - attrib["copyright"] = self.copyright - - root = Element("fmiModelDescription", attrib) - - options = dict() - for option in FMI3_MODEL_OPTIONS_COMMON: - value = model_options.get(option.name, option.value) - options[option.name] = str(value).lower() - - options["modelIdentifier"] = self.modelName - - options_cs = options.copy() - for option in FMI3_MODEL_OPTIONS_COSIM: - options_cs[option.name] = str(value).lower() - - options_me = options.copy() - for option in FMI3_MODEL_OPTIONS_MX: - options_me[option.name] = str(value).lower() - - # check if we have cosim mixin or model exchange mixin - if isinstance(self, ModelExchange): - SubElement(root, "ModelExchange", attrib=options_me) - - if isinstance(self, CoSimulation): - SubElement(root, "CoSimulation", attrib=options_cs) - - if self.units: - unit_defs = SubElement(root, "UnitDefinitions") - for _, unit in self.units.items(): - unit_defs.append(unit.to_xml()) - - if self.type_definitions: - type_defs = SubElement(root, "TypeDefinitions") - for _, val in self.type_definitions.items(): - type_defs.append(val.to_xml()) - - if len(self.log_categories) > 0: - categories = SubElement(root, "LogCategories") - for category, description in self.log_categories.items(): - categories.append( - Element( - "Category", - attrib={"name": category, "description": description}, - ) - ) - - if self.default_experiment is not None: - attrib = dict() - if self.default_experiment.start_time is not None: - attrib["startTime"] = str(self.default_experiment.start_time) - if self.default_experiment.stop_time is not None: - attrib["stopTime"] = str(self.default_experiment.stop_time) - if self.default_experiment.step_size is not None: - attrib["stepSize"] = str(self.default_experiment.step_size) - if self.default_experiment.tolerance is not None: - attrib["tolerance"] = str(self.default_experiment.tolerance) - SubElement(root, "DefaultExperiment", attrib) - - variables = SubElement(root, "ModelVariables") - for v in self.vars.values(): - if ModelVariable.requires_start(v): - self.__apply_start_value(v) - variables.append(v.to_xml()) - - structure = SubElement(root, "ModelStructure") - outputs = list( - filter(lambda v: v.causality == Fmi3Causality.output, self.vars.values()) - ) - - continuous_state_derivatives = list( - filter(lambda v: v.variability == Fmi3Variability.continuous and (isinstance(v, Float64) and v.derivative is not None), self.vars.values()) - ) - - allowed_variability = [None, Fmi3Initial.approx, Fmi3Initial.calculated] - initial_unknown = list( - filter(lambda v: (v.causality == Fmi3Causality.output and (v.initial in allowed_variability)) - or v.causality == Fmi3Causality.calculatedParameter - or v in continuous_state_derivatives and v.initial in allowed_variability, self.vars.values()) - ) - - for v in outputs: - SubElement(structure, "Output", attrib=dict(valueReference=str(v.value_reference))) - - for v in continuous_state_derivatives: - SubElement(structure, "ContinuousStateDerivative", attrib=dict(valueReference=str(v.value_reference))) - - for v in initial_unknown: - SubElement(structure, "InitialUnknown", attrib=dict(valueReference=str(v.value_reference))) - - for v in self.event_indicators: - SubElement(structure, "EventIndicator", attrib=dict(valueReference=str(v))) - - return root - - def __apply_start_value(self, var: ModelVariable): - vrs = [var.value_reference] - if isinstance(var, Int32): - refs = self.get_int32(vrs) - elif isinstance(var, (Enumeration, Int64)): - refs = self.get_int64(vrs) - elif isinstance(var, UInt64): - refs = [val.value for val in self.get_uint64(vrs)] - elif isinstance(var, Float64): - refs = self.get_float64(vrs) - elif isinstance(var, Boolean): - refs = self.get_boolean(vrs) - elif isinstance(var, String): - refs = self.get_string(vrs) - else: - raise Exception(f"Unsupported type {type(var)}!") - var.start = refs if len(getattr(var, "dimensions", [])) > 0 else refs[0] - - def register_variable(self, var: ModelVariable, nested: bool = True, var_type: Any = None, has_event_indicator: bool = False): - """Register a variable as FMU interface. - - Args: - var (ModelVariable): The variable to be registered - nested (bool): Optional, does the "." in the variable name reflect an object hierarchy to access it? Default True - """ - variable_reference = len(self.vars) - self.vars[variable_reference] = var - # Set the unique value reference - var.value_reference = variable_reference - owner = self - if var.getter is None and nested and "." in var.name: - split = var.name.split(".") - split.pop(-1) - for s in split: - owner = getattr(owner, s) - if var.getter is None: - if hasattr(var, "dimensions") and len(var.dimensions) > 0: - var.getter = lambda: getattr(owner, var.local_name).flatten().tolist() - else: - var.getter = lambda: getattr(owner, var.local_name) - if var.setter is None and hasattr(owner, var.local_name) and var.variability != Fmi3Variability.constant: - if hasattr(var, "dimensions") and len(var.dimensions) > 0: - import numpy as np - var.setter = lambda v: setattr(owner, var.local_name, np.reshape(v, newshape=getattr(owner, var.local_name).shape)) - else: - var.setter = lambda v: setattr(owner, var.local_name, v) - - if var_type: - self.type_definitions[var_type.name] = var_type - var.declared_type = var_type.name - - if has_event_indicator: - self.register_event_indicator(var.value_reference) - - def register_event_indicator(self, vr): - self.event_indicators.append(vr) - - def setup_experiment(self, start_time: float): - pass - - def register_units(self, units: List[Unit]): - for unit in units: - self.units[unit.name] = unit - - def enter_initialization_mode(self): - pass - - def exit_initialization_mode(self): - pass - - def do_step(self, current_time: float, step_size: float) -> Fmi3StepResult: - pass - - def terminate(self): - pass - - def get_int32(self, vrs: List[int]) -> List[int]: - refs = list() - for vr in vrs: - var = self.vars[vr] - if isinstance(var, Int32): - if len(var.dimensions) == 0: - refs.append(int(var.getter())) - else: - refs.extend(map(int, var.getter())) - else: - raise TypeError( - f"Variable with valueReference={vr} is not of type Int32!" - ) - return refs - - def get_int64(self, vrs: List[int]) -> List[int]: - refs = list() - for vr in vrs: - var = self.vars[vr] - if isinstance(var, (Enumeration, Int64)): - if len(var.dimensions) == 0: - refs.append(int(var.getter())) - else: - refs.extend(map(int, var.getter())) - else: - raise TypeError( - f"Variable with valueReference={vr} is not of type Int64!" - ) - return refs - - def get_uint64(self, vrs: List[int]) -> List[ctypes.c_uint64]: - refs = list() - for vr in vrs: - var = self.vars[vr] - if isinstance(var, UInt64): - if len(var.dimensions) == 0: - val = var.getter() - refs.append(ctypes.c_uint64(val) if not isinstance(val, ctypes.c_uint64) else val) - else: - refs.extend(map(ctypes.c_uint64, var.getter())) - else: - raise TypeError( - f"Variable with valueReference={vr} is not of type Uint64!" - ) - return refs - - def get_float64(self, vrs: List[int]) -> List[float]: - refs = list() - for vr in vrs: - var = self.vars[vr] - if isinstance(var, Float64): - if len(var.dimensions) == 0: - refs.append(float(var.getter())) - else: - refs.extend(var.getter()) - else: - raise TypeError( - f"Variable with valueReference={vr} is not of type Float64!" - ) - return refs - - def get_boolean(self, vrs: List[int]) -> List[bool]: - refs = list() - for vr in vrs: - var = self.vars[vr] - if isinstance(var, Boolean): - if len(var.dimensions) == 0: - refs.append(bool(var.getter())) - else: - refs.extend(var.getter()) - - else: - raise TypeError( - f"Variable with valueReference={vr} is not of type Boolean!" - ) - return refs - - def get_string(self, vrs: List[int]) -> List[str]: - refs = list() - for vr in vrs: - var = self.vars[vr] - if isinstance(var, String): - refs.append(str(var.getter())) - else: - raise TypeError( - f"Variable with valueReference={vr} is not of type String!" - ) - return refs - - def set_int32(self, vrs: List[int], values: List[int]): - offset = 0 - for vr in vrs: - var = self.vars[vr] - if isinstance(var, Int32): - size = var.size(self.vars) - if size > 1: - var.setter(values[offset:offset+size]) - else: - var.setter(values[offset]) - offset += size - else: - raise TypeError( - f"Variable with valueReference={vr} is not of type Int32!" - ) - - def set_int64(self, vrs: List[int], values: List[int]): - offset = 0 - for vr in vrs: - var = self.vars[vr] - if isinstance(var, (Enumeration, Int64)): - size = var.size(self.vars) - if size > 1: - var.setter(values[offset:offset+size]) - else: - var.setter(values[offset]) - offset += size - else: - raise TypeError( - f"Variable with valueReference={vr} is not of type Int64!" - ) - - def set_uint64(self, vrs: List[int], values: List[int]): - offset = 0 - for vr in vrs: - var = self.vars[vr] - if isinstance(var, UInt64): - size = var.size(self.vars) - if size > 1: - var.setter(values[offset:offset+size]) - else: - var.setter(values[offset]) - offset += size - else: - raise TypeError( - f"Variable with valueReference={vr} is not of type UInt64!" - ) - - def set_float64(self, vrs: List[int], values: List[float]): - offset = 0 - for vr in vrs: - var = self.vars[vr] - if isinstance(var, Float64): - size = var.size(self.vars) - if size > 1: - var.setter(values[offset:offset+size]) - else: - var.setter(values[offset]) - offset += size - else: - raise TypeError( - f"Variable with valueReference={vr} is not of type Float64!" - ) - - def set_boolean(self, vrs: List[int], values: List[bool]): - offset = 0 - for vr in vrs: - var = self.vars[vr] - if isinstance(var, Boolean): - size = var.size(self.vars) - if size > 1: - var.setter(values[offset:offset+size]) - else: - var.setter(values[offset]) - offset += size - else: - raise TypeError( - f"Variable with valueReference={vr} is not of type Boolean!" - ) - - def set_string(self, vrs: List[int], values: List[str]): - for vr, value in zip(vrs, values): - var = self.vars[vr] - if isinstance(var, String): - var.setter(value) - else: - raise TypeError( - f"Variable with valueReference={vr} is not of type String!" - ) - - def _get_fmu_state(self) -> Dict[str, Any]: - state = dict() - for var in self.vars.values(): - state[var.name] = var.getter() - return state - - def _set_fmu_state(self, state: Dict[str, Any]): - vars_by_name = dict([(v.name, v) for v in self.vars.values()]) - for name, value in state.items(): - if name not in vars_by_name: - setattr(self, name, value) - else: - v = vars_by_name[name] - if v.setter is not None: - v.setter(value) - - def get_number_of_event_indicators(self) -> int: - return len(self.event_indicators) - - def set_continuous_states(self, values: List[float]): - offset = 0 - continuous_state_derivatives = list( - filter(lambda v: v.variability == Fmi3Variability.continuous and (isinstance(v, Float64) and v.derivative is not None), self.vars.values()) - ) - - vrs = [v.derivative for v in continuous_state_derivatives] - - for vr in vrs: - var = self.vars[vr] - size = var.size(self.vars) - if size > 1: - var.setter(values[offset:offset+size]) - else: - var.setter(values[offset]) - offset += size - - def get_continuous_states(self) -> List[float]: - offset = 0 - continuous_state_derivatives = list( - filter(lambda v: v.variability == Fmi3Variability.continuous and (isinstance(v, Float64) and v.derivative is not None), self.vars.values()) - ) - - vrs = [v.derivative for v in continuous_state_derivatives] - - refs = list() - for vr in vrs: - var = self.vars[vr] - if len(var.dimensions) == 0: - refs.append(float(var.getter())) - else: - refs.extend(var.getter()) - - return refs - - def get_number_of_continuous_states(self) -> int: - continuous_state_derivatives = list( - filter(lambda v: v.variability == Fmi3Variability.continuous and (isinstance(v, Float64) and v.derivative is not None), self.vars.values()) - ) - return len(continuous_state_derivatives) - - def set_time(self, time: float): - self.time = time - - @staticmethod - def _fmu_state_to_bytes(state: Dict[str, Any]) -> bytes: - return json.dumps(state).encode("utf-8") - - @staticmethod - def _fmu_state_from_bytes(state: bytes) -> Dict[str, Any]: - return json.loads(state.decode("utf-8")) - - def _get_log_queue(self): - return self.log_queue - - def log( - self, - msg: str, - status: Fmi3Status = Fmi3Status.ok, - category: Optional[str] = None, - debug: bool = False - ): - """Log a message to the FMU logger. - - Args: - msg (str) : Log message - status (Fmi3Status) : Optional, message status (default ok) - category (str or None) : Optional, message category (default derived from status) - debug (bool) : Optional, is this a debug message (default False) - """ - if category is None: - category = f"logStatus{status.name.capitalize()}" - if category not in self.log_categories: - category = "logAll" - log_msg = LogMsg(status, category, msg, debug) - self.log_queue.append(log_msg) - -class Fmi3Slave(Fmi3SlaveBase, CoSimulation): - pass \ No newline at end of file diff --git a/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_cs.cpp b/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_cs.cpp deleted file mode 100644 index ecc0855..0000000 --- a/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_cs.cpp +++ /dev/null @@ -1,202 +0,0 @@ -/* Copyright 2016-2019, SINTEF Ocean. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -#include "cppfmu/cppfmu_cs.hpp" - -#include - - -namespace cppfmu -{ - -// ============================================================================= -// SlaveInstance -// ============================================================================= - - -void SlaveInstance::SetupExperiment( - FMIBoolean /*toleranceDefined*/, - FMIFloat64 /*tolerance*/, - FMIFloat64 /*tStart*/, - FMIBoolean /*stopTimeDefined*/, - FMIFloat64 /*tStop*/) -{ - // Do nothing -} - - -void SlaveInstance::EnterInitializationMode() -{ - // Do nothing -} - - -void SlaveInstance::ExitInitializationMode() -{ - // Do nothing -} - - -void SlaveInstance::Terminate() -{ - // Do nothing -} - - -void SlaveInstance::Reset() -{ - // Do nothing -} - - -void SlaveInstance::SetFloat64( - const FMIValueReference /*vr*/[], - std::size_t nvr, - const FMIFloat64 /*value*/[], - std::size_t nValues) -{ - if (nvr != 0) { - throw std::logic_error("Attempted to set nonexistent variable"); - } -} - - -void SlaveInstance::SetInt32( - const FMIValueReference /*vr*/[], - std::size_t nvr, - const FMIInt32 /*value*/[], - std::size_t nValues) -{ - if (nvr != 0) { - throw std::logic_error("Attempted to set nonexistent variable"); - } -} - -void SlaveInstance::SetInt64( - const FMIValueReference /*vr*/[], - std::size_t nvr, - const FMIInt64 /*value*/[], - std::size_t nValues) -{ - if (nvr != 0) { - throw std::logic_error("Attempted to set nonexistent variable"); - } -} - -void SlaveInstance::SetUInt64( - const FMIValueReference /*vr*/[], - std::size_t nvr, - const FMIUInt64 /*value*/[], - std::size_t nValues) -{ - if (nvr != 0) { - throw std::logic_error("Attempted to set nonexistent variable"); - } -} - - -void SlaveInstance::SetBoolean( - const FMIValueReference /*vr*/[], - std::size_t nvr, - const FMIBoolean /*value*/[], - std::size_t nValues) -{ - if (nvr != 0) { - throw std::logic_error("Attempted to set nonexistent variable"); - } -} - - -void SlaveInstance::SetString( - const FMIValueReference /*vr*/[], - std::size_t nvr, - const FMIString /*value*/[], - std::size_t nValues) -{ - if (nvr != 0) { - throw std::logic_error("Attempted to set nonexistent variable"); - } -} - - -void SlaveInstance::GetFloat64( - const FMIValueReference /*vr*/[], - std::size_t nvr, - FMIFloat64 /*value*/[], - std::size_t nValues) const -{ - if (nvr != 0) { - throw std::logic_error("Attempted to get nonexistent variable"); - } -} - - -void SlaveInstance::GetInt32( - const FMIValueReference /*vr*/[], - std::size_t nvr, - FMIInt32 /*value*/[], - std::size_t nValues) const -{ - if (nvr != 0) { - throw std::logic_error("Attempted to get nonexistent variable"); - } -} - - -void SlaveInstance::GetInt64( - const FMIValueReference /*vr*/[], - std::size_t nvr, - FMIInt64 /*value*/[], - std::size_t nValues) const -{ - if (nvr != 0) { - throw std::logic_error("Attempted to get nonexistent variable"); - } -} - - -void SlaveInstance::GetUInt64( - const FMIValueReference /*vr*/[], - std::size_t nvr, - FMIUInt64 /*value*/[], - std::size_t nValues) const -{ - if (nvr != 0) { - throw std::logic_error("Attempted to get nonexistent variable"); - } -} - - -void SlaveInstance::GetBoolean( - const FMIValueReference /*vr*/[], - std::size_t nvr, - FMIBoolean /*value*/[], - std::size_t nValues) const -{ - if (nvr != 0) { - throw std::logic_error("Attempted to set nonexistent variable"); - } -} - - -void SlaveInstance::GetString( - const FMIValueReference /*vr*/[], - std::size_t nvr, - FMIString /*value*/[], - std::size_t nValues) const -{ - if (nvr != 0) { - throw std::logic_error("Attempted to set nonexistent variable"); - } -} - - -SlaveInstance::~SlaveInstance() CPPFMU_NOEXCEPT -{ - // Do nothing -} - - -} // namespace cppfmu diff --git a/pythonfmu3/tests/conftest.py b/pythonfmu3/tests/conftest.py deleted file mode 100644 index 212955b..0000000 --- a/pythonfmu3/tests/conftest.py +++ /dev/null @@ -1,6 +0,0 @@ -import pytest - -def pytest_configure(config): - config.addinivalue_line( - "markers", "requirements(pkg): mark test as requiring the specified package" - ) \ No newline at end of file diff --git a/pythonfmu3/tests/slaves/PythonSlaveWithException.py b/pythonfmu3/tests/slaves/PythonSlaveWithException.py deleted file mode 100644 index 41fd133..0000000 --- a/pythonfmu3/tests/slaves/PythonSlaveWithException.py +++ /dev/null @@ -1,18 +0,0 @@ -from pythonfmu3.fmi3slave import Fmi3Slave, Fmi3Causality, Float64, Fmi3Variability - - -class PythonSlaveWithException(Fmi3Slave): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - - self.realIn = 22.0 - self.realOut = 0.0 - self.time = 0 - - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable(Float64("realIn", causality=Fmi3Causality.input)) - self.register_variable(Float64("realOut", causality=Fmi3Causality.output)) - - def do_step(self, current_time, step_size): - raise RuntimeError() diff --git a/pythonfmu3/tests/slaves/pythonslave.py b/pythonfmu3/tests/slaves/pythonslave.py deleted file mode 100644 index 3696792..0000000 --- a/pythonfmu3/tests/slaves/pythonslave.py +++ /dev/null @@ -1,52 +0,0 @@ -from pythonfmu3.fmi3slave import Fmi3Slave, Fmi3Causality, Fmi3Variability, Int32, Float64, Boolean, String - - -class Container: - pass - - -class PythonSlave(Fmi3Slave): - - author = "John Doe" - description = "A simple description" - - def __init__(self, **kwargs): - super().__init__(**kwargs) - - self.intParam = 42 - self.intOut = 23 - self.realOut = 3.0 - self.booleanVariable = True - self.stringVariable = "Hello World!" - self.realIn = 2. / 3. - self.booleanParameter = False - self.stringParameter = "dog" - self.time = 0 - - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable( - Int32("intParam", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable)) - self.register_variable(Float64("realIn", causality=Fmi3Causality.input)) - self.register_variable( - Boolean("booleanParameter", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable)) - self.register_variable( - String("stringParameter", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable)) - - self.register_variable(Int32("intOut", causality=Fmi3Causality.output)) - self.register_variable(Float64("realOut", causality=Fmi3Causality.output)) - self.register_variable(Boolean("booleanVariable", causality=Fmi3Causality.local)) - self.register_variable(String("stringVariable", causality=Fmi3Causality.local)) - - self.container = Container() - self.container.someReal = 99.0 - self.container.subContainer = sub = Container() - sub.someInteger = -15 - self.register_variable( - Float64("container.someReal", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable)) - self.register_variable( - Int32("container.subContainer.someInteger", causality=Fmi3Causality.parameter, - variability=Fmi3Variability.tunable)) - - def do_step(self, current_time, step_size): - self.realOut = current_time + step_size - return True diff --git a/pythonfmu3/tests/slaves/pythonslaveMX.py b/pythonfmu3/tests/slaves/pythonslaveMX.py deleted file mode 100644 index 4d22672..0000000 --- a/pythonfmu3/tests/slaves/pythonslaveMX.py +++ /dev/null @@ -1,27 +0,0 @@ -from pythonfmu3 import Fmi3Causality, ModelExchange, Fmi3Variability, Fmi3SlaveBase, Fmi3Status, Float64, Fmi3Initial, Unit, Float64Type, Fmi3StepResult - -from typing import List - -class Dahlquist(Fmi3SlaveBase, ModelExchange): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - - self.author = "Stephen Smith" - self.description = "Dahlquist's test problem for model exchange FMUs" - - self.time = 0.0 - self.k = 1.0 - self.x = 1.0 - self.derx = 0.0 - - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable(Float64("x", causality=Fmi3Causality.output, start=1, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact)) - self.register_variable(Float64("derx", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=1)) - self.register_variable(Float64("k", causality=Fmi3Causality.parameter, variability=Fmi3Variability.fixed)) - - - def get_continuous_state_derivatives(self) -> List[float]: - self.derx = -self.k * self.x - return [self.derx] - \ No newline at end of file diff --git a/pythonfmu3/tests/slaves/pythonslaveMXCS.py b/pythonfmu3/tests/slaves/pythonslaveMXCS.py deleted file mode 100644 index 27ca784..0000000 --- a/pythonfmu3/tests/slaves/pythonslaveMXCS.py +++ /dev/null @@ -1,32 +0,0 @@ -from pythonfmu3 import Fmi3Causality, CoSimulation, ModelExchange, Fmi3Variability, Fmi3SlaveBase, Fmi3Status, Float64, Fmi3Initial, Unit, Float64Type, Fmi3StepResult - -from typing import List - -class Dahlquist(Fmi3SlaveBase, ModelExchange, CoSimulation): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - - self.author = "Stephen Smith" - self.description = "Dahlquist's test problem for model exchange FMUs" - - self.time = 0.0 - self.k = 1.0 - self.x = 1.0 - self.derx = 0.0 - - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable(Float64("x", causality=Fmi3Causality.output, start=1, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact)) - self.register_variable(Float64("derx", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=1)) - self.register_variable(Float64("k", causality=Fmi3Causality.parameter, variability=Fmi3Variability.fixed)) - - - def get_continuous_state_derivatives(self) -> List[float]: - self.derx = -self.k * self.x - return [self.derx] - - def do_step(self, current_time: float, step_size: float) -> Fmi3StepResult: - self.time = current_time + step_size - self.derx = -self.k * self.x - self.x += self.derx * step_size - return True \ No newline at end of file diff --git a/pythonfmu3/tests/slaves/pythonslave_arraytypes.py b/pythonfmu3/tests/slaves/pythonslave_arraytypes.py deleted file mode 100644 index c1a67d5..0000000 --- a/pythonfmu3/tests/slaves/pythonslave_arraytypes.py +++ /dev/null @@ -1,80 +0,0 @@ - -from pythonfmu3 import Fmi3Causality, Fmi3Variability, Dimension, Fmi3Slave, Fmi3Status, Float64, Int32, Int64, UInt64, String, Boolean - -import numpy as np - -SIZE = 10 - -TYPES = [UInt64, Float64, Boolean, Int32, Int64] -CAUSALITY = [Fmi3Causality.output, Fmi3Causality.input] - -TYPE_MAP = { - UInt64: np.uint64, - Float64: np.float64, - Int32: np.int32, - Int64: np.int64, - Boolean: bool -} - -def var_names(var_type, causality): - return f"{var_type.__name__.lower()}_{causality.name.lower()}" - - -def init_var(var_type, causality, array=True): - if array: - return np.zeros(SIZE, dtype=TYPE_MAP[var_type]) - else: - return TYPE_MAP[var_type]() - - -def create_vars(self): - dimensions = [Dimension(start=str(SIZE))] - for var_type in TYPES: - for causality in CAUSALITY: - name = var_names(var_type, causality) - if var_type == Float64: - var = var_type(name, causality=causality, variability=Fmi3Variability.continuous, dimensions=dimensions) - else: - var = var_type(name, causality=causality, variability=Fmi3Variability.discrete, dimensions=dimensions) - setattr(self, name, init_var(var_type, causality)) - self.register_variable(var) - - -def generate_data(self): - for var_type in TYPES: - causality = Fmi3Causality.output - name = var_names(var_type, causality) - var = getattr(self, name) - if var_type == Boolean: - data = [False, True, False, True, True, False, False, True, False, True] - setattr(self, name, np.array(data).astype(bool)) - elif var_type == Int32 or var_type == Int64 or var_type == UInt64: - data = [1,2,3,4,5,6,7,8,9,10] - setattr(self, name, np.array(data).astype(TYPE_MAP[var_type])) - else: - data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] - setattr(self, name, np.array(data).astype(TYPE_MAP[var_type])) - -class ArrayTypes(Fmi3Slave): - - - def __init__(self, **kwargs): - super().__init__(**kwargs) - - self.author = "Tester" - self.description = "FMU with all basic types as arrays" - - self.time = 0.0 - - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - - create_vars(self) - - generate_data(self) - - - def do_step(self, current_time: float, step_size: float) -> Fmi3Status: - generate_data(self) - return True - - diff --git a/pythonfmu3/tests/slaves/pythonslave_read_file.py b/pythonfmu3/tests/slaves/pythonslave_read_file.py deleted file mode 100644 index f5afd82..0000000 --- a/pythonfmu3/tests/slaves/pythonslave_read_file.py +++ /dev/null @@ -1,23 +0,0 @@ -from pythonfmu3.fmi3slave import Fmi3Slave, Fmi3Causality, Fmi3Variability, String, DefaultExperiment, Float64 - - -class PythonSlaveReadFile(Fmi3Slave): - - default_experiment = DefaultExperiment(start_time=0) - - def __init__(self, **kwargs): - super().__init__(**kwargs) - - with (open(f'{self.resources}/hello.txt', 'r')) as file: - data = file.read() - - self.time = 0 - - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable( - String("file_content", getter=lambda: data, - causality=Fmi3Causality.output, - variability=Fmi3Variability.constant)) - - def do_step(self, current_time, step_size): - return True diff --git a/pythonfmu3/tests/slaves/slavewithdep.py b/pythonfmu3/tests/slaves/slavewithdep.py deleted file mode 100644 index 1b30a30..0000000 --- a/pythonfmu3/tests/slaves/slavewithdep.py +++ /dev/null @@ -1,21 +0,0 @@ -import math -from pythonfmu3.fmi3slave import Fmi3Slave, Fmi3Causality, Float64, Fmi3Variability -from localmodule import get_amplitude, get_time_constant - - -class PythonSlaveWithDep(Fmi3Slave): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - - self.realIn = 22.0 - self.realOut = 0.0 - self.time = 0 - - self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) - self.register_variable(Float64("realIn", causality=Fmi3Causality.input)) - self.register_variable(Float64("realOut", causality=Fmi3Causality.output)) - - def do_step(self, current_time, step_size): - self.realOut = self.realIn * get_amplitude() * math.exp((current_time + step_size) / get_time_constant()) - return True diff --git a/pythonfmu3/tests/test_fmi3slave.py b/pythonfmu3/tests/test_fmi3slave.py deleted file mode 100644 index b288c27..0000000 --- a/pythonfmu3/tests/test_fmi3slave.py +++ /dev/null @@ -1,171 +0,0 @@ -import pytest - -from pythonfmu3 import Fmi3Slave, ModelExchange -from pythonfmu3 import __version__ as VERSION - -from .utils import FMI2PY, PY2FMI - -# TODO test xml - - -@pytest.mark.parametrize("model", ["theModelName", None]) -def test_Fmi3Slave_constructor(model): - - class Slave(Fmi3Slave): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - if model is not None: - self.modelName = model - - def do_step(self, t, dt): - return True - - if model is None: - slave = Slave(instance_name="slaveInstance") - assert slave.modelName == "Slave" - assert slave.instance_name == "slaveInstance" - else: - slave = Slave(instance_name="slaveInstance") - assert slave.modelName == model - assert slave.instance_name == "slaveInstance" - - -def test_Fmi3Slave_generation_tool(): - class Slave(Fmi3Slave): - def do_step(self, t, dt): - return True - - slave = Slave(instance_name="instance") - xml = slave.to_xml() - - assert xml.attrib['generationTool'] == f"PythonFMU3 {VERSION}" - - -@pytest.mark.parametrize("fmi_type", FMI2PY) -@pytest.mark.parametrize("value", [ - False, - 22, - 2./3., - "hello_world" -]) -def test_Fmi3Slave_getters(fmi_type, value): - - class Slave(Fmi3Slave): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - self.var = value - self.register_variable(PY2FMI[type(value)]("var")) - - def do_step(self, t, dt): - return True - - py_type = FMI2PY[fmi_type] - fmi_type_name = fmi_type.__qualname__.lower() - - slave = Slave(instance_name="slaveInstance") - if type(value) is py_type: - assert getattr(slave, f"get_{fmi_type_name}")([0]) == [value] - else: - with pytest.raises(TypeError): - getattr(slave, f"get_{fmi_type_name}")([0]) - - -@pytest.mark.parametrize("fmi_type", FMI2PY) -@pytest.mark.parametrize("value", [ - False, - 22, - 2./3., - "hello_world", -]) -def test_Fmi3Slave_setters(fmi_type, value): - - class Slave(Fmi3Slave): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - self.var = None - self.register_variable(PY2FMI[type(value)]("var")) - - def do_step(self, t, dt): - return True - - slave = Slave(instance_name="slaveInstance") - py_type = FMI2PY[fmi_type] - fmi_type_name = fmi_type.__qualname__.lower() - - if type(value) is py_type: - set_method = getattr(slave, f"set_{fmi_type_name}") - set_method([0], [value]) - assert getattr(slave, f"get_{fmi_type_name}")([0]) == [value] - else: - set_method = getattr(slave, f"set_{fmi_type_name}") - with pytest.raises(TypeError): - set_method([0], [value]) - - -def test_Fmi3Slave_log_categories(): - class Slave(Fmi3Slave): - def do_step(self, t, dt): - return True - - slave = Slave(instance_name="instance") - xml = slave.to_xml() - - categories = xml.find("LogCategories") - assert len(categories) == len(Slave.log_categories) - for category, description in Slave.log_categories.items(): - assert categories.find(f"Category[@name='{category}'][@description='{description}']") is not None - - -@pytest.mark.parametrize("new_categories", [ - dict(), - { - "logStatusWarning": "Log messages with fmi3Warning status.", - "logStatusError": "Log messages with fmi3Error status.", - "logStatusFatal": "Log messages with fmi3Fatal status.", - "logAll": "Log all messages." - }, - { - "logCustom1": "My first custom log category", - "logCustom2": "My second custom log category" - } -]) -def test_Fmi3Slave_customized_log_categories(new_categories): - class Slave(Fmi3Slave): - log_categories = new_categories - - def do_step(self, t, dt): - return True - - slave = Slave(instance_name="instance") - xml = slave.to_xml() - - categories = xml.find("LogCategories") - - if len(new_categories) > 0: - assert len(categories) == len(Slave.log_categories) - for category, description in Slave.log_categories.items(): - assert categories.find(f"Category[@name='{category}'][@description='{description}']") is not None - else: - assert categories is None - - -def test_Fmi3Slave_model_exchange(): - class Slave(Fmi3Slave, ModelExchange): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - self.time = 0.0 - - def get_continuous_state_derivatives(self, vals): - return [] - - slave = Slave(instance_name="instance") - xml = slave.to_xml() - - categories = xml.find("ModelExchange") - - assert categories is not None, "ModelExchange category should be present in the XML" - diff --git a/pythonfmu3/tests/test_variables.py b/pythonfmu3/tests/test_variables.py deleted file mode 100644 index 142b8a2..0000000 --- a/pythonfmu3/tests/test_variables.py +++ /dev/null @@ -1,335 +0,0 @@ -from enum import Enum -from random import randint - -import pytest -import ctypes - -from xml.etree import ElementTree - -from pythonfmu3 import Fmi3Slave -from pythonfmu3.enums import Fmi3Causality, Fmi3Initial, Fmi3Variability -from pythonfmu3.variables import flatten, Boolean, Int32, UInt64, Float64, ModelVariable, String, Dimension - -from .utils import PY2FMI, UInt64ValType - -MODEL_VARIABLE_ATTRIBUTES = ["name", "valueReference", "description", "causality", "variability", "initial"] - - -def test_ModelVariable_reference_set_once_only(): - v = ModelVariable('variable') - v.value_reference = 22 - - with pytest.raises(RuntimeError): - v.value_reference = 33 - - -@pytest.mark.parametrize("causality", list(Fmi3Causality) + [None]) -@pytest.mark.parametrize("initial", list(Fmi3Initial) + [None]) -@pytest.mark.parametrize("variability", list(Fmi3Variability) + [None]) -@pytest.mark.parametrize("name, description", [ - ("var", None), - ("var", "description of var"), -]) -def test_ModelVariable_constructor(causality, initial, variability, name, description): - var = ModelVariable(name, causality, description, initial, variability) - - assert var.name == name - assert var.value_reference is None - assert var.causality == causality - assert var.description == description - assert var.initial == initial - assert var.variability == variability - - -@pytest.mark.parametrize("fmi_type,value", [ - (Boolean, False), - (Int32, 22), - (UInt64, UInt64ValType(23)), - (Float64, 2./3.), - (String, "hello_world"), -]) -def test_ModelVariable_getter(fmi_type, value): - - class Slave(Fmi3Slave): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - self.var = [value] - self.register_variable(PY2FMI[type(value)]("var", getter=lambda: self.var[0])) - - def do_step(self, t, dt): - return True - - fmi_type_name = fmi_type.__qualname__.lower() - - slave = Slave(instance_name="slaveInstance") - assert [getattr(val, "value", val) for val in getattr(slave, f"get_{fmi_type_name}")([0])] == [value] - - -@pytest.mark.parametrize("fmi_type,value", [ - (Boolean, False), - (Int32, 22), - (UInt64, UInt64ValType(23)), - (Float64, 2./3.), - (String, "hello_world") -]) -def test_ModelVariable_setter(fmi_type, value): - - class Slave(Fmi3Slave): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - self.var = [None] - self.register_variable( - PY2FMI[type(value)]( - "var", - getter=lambda: self.var[0], - setter=lambda v: self.var.__setitem__(0, v) - ) - ) - - def do_step(self, t, dt): - return True - - slave = Slave(instance_name="slaveInstance") - fmi_type_name = fmi_type.__qualname__.lower() - - set_method = getattr(slave, f"set_{fmi_type_name}") - set_method([0, ], [value, ]) - assert [getattr(val, "value", val) for val in getattr(slave, f"get_{fmi_type_name}")([0])] == [value] - -@pytest.mark.requirements("numpy") -@pytest.mark.parametrize("fmi_type,value,dims", [ - (Float64, [1.,2.,3.,4.], [4]), - (Float64, [1.,2.,3.,4.], [2, 2]), -]) -def test_ModelVariable_getter_array(fmi_type, value, dims): - - class Slave(Fmi3Slave): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - self.var = value - dimensions = [Dimension(start=val) for val in dims] - self.register_variable(PY2FMI[type(value[0])]("var", getter=lambda: self.var, dimensions=dimensions)) - - def do_step(self, t, dt): - return True - - fmi_type_name = fmi_type.__qualname__.lower() - - slave = Slave(instance_name="slaveInstance") - assert [getattr(val, "value", val) for val in getattr(slave, f"get_{fmi_type_name}")([0])] == value - - -@pytest.mark.requirements("numpy") -@pytest.mark.parametrize("fmi_type,value,dims", [ - (Float64, [1.,2.,3.,4.], [4]), - (Float64, [1.,2.,3.,4.], [2, 2]), -]) -def test_ModelVariable_setter_array(fmi_type, value, dims): - - class Slave(Fmi3Slave): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - self.var = [None]*len(value) - dimensions = [Dimension(start=val) for val in dims] - self.register_variable( - PY2FMI[type(value[0])]( - "var", - getter=lambda: self.var, - setter=lambda v: setattr(self, 'var', v), - dimensions=dimensions - ) - ) - - def do_step(self, t, dt): - return True - - slave = Slave(instance_name="slaveInstance") - fmi_type_name = fmi_type.__qualname__.lower() - - set_method = getattr(slave, f"set_{fmi_type_name}") - set_method([0, ], value) - assert [getattr(val, "value", val) for val in getattr(slave, f"get_{fmi_type_name}")([0])] == value - -@pytest.mark.parametrize("causality", list(Fmi3Causality) + [None]) -@pytest.mark.parametrize("initial", list(Fmi3Initial) + [None]) -@pytest.mark.parametrize("variability", list(Fmi3Variability) + [None]) -@pytest.mark.parametrize("name, description", [ - ("var", None), - ("var", "description of var"), -]) -def test_ModelVariable_to_xml(causality, initial, variability, name, description): - var = ModelVariable(name, causality, description, initial, variability) - valueReference = randint(0, 25000) - var.value_reference = valueReference - - node = var.to_xml() - assert node.tag == None - args = locals() - for attr in MODEL_VARIABLE_ATTRIBUTES: - value = args[attr] - if value is not None: - if isinstance(value, Enum): - assert node.attrib[attr] == value.name - else: - assert node.attrib[attr] == str(value) - - -@pytest.mark.parametrize("var_type, value", [ - (Boolean, True), - (Int32, 23), - (UInt64, UInt64ValType(23)), - (Float64, 15.), - (String, "hello")]) -@pytest.mark.parametrize("causality", list(Fmi3Causality) + [None]) -@pytest.mark.parametrize("initial", list(Fmi3Initial) + [None]) -@pytest.mark.parametrize("variability", list(Fmi3Variability) + [None]) -def test_ModelVariable_start(var_type, value, causality, initial, variability): - var_obj = var_type("var", causality=causality, description="a variable", initial=initial, variability=variability) - - class PySlave(Fmi3Slave): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - setattr(self, "var", value) - self.register_variable(var_obj) - - def do_step(self, current_time: float, step_size: float): - return True - - slave = PySlave(instance_name="testInstance") - - xml = slave.to_xml() - var_node = xml.find(f".//{var_obj._type}[@name='var']") - - assert var_node is not None - - if ModelVariable.requires_start(var_obj): - assert var_obj.start == value - else: - assert var_obj.start is None - - -@pytest.mark.parametrize("name,start", [ - ("boolean_name", None), - ("boolean_another_name", False), -]) -def test_Boolean_constructor(name, start): - r = Boolean(name, start) - - assert r.start == start - - -@pytest.mark.parametrize("name,start", [ - ("boolean_name", None), - ("boolean_another_name", True), - ("boolean_yet_another", False), -]) -def test_Boolean_to_xml(name, start): - r = Boolean(name, start) - xml = r.to_xml() - if start is not None: - assert xml.attrib['start'] == str(start).lower() - - -@pytest.mark.parametrize("name,start", [ - ("integer_name", None), - ("integer_another_name", 42), -]) -def test_Integer_constructor(name, start): - r = Int32(name, start) - - assert r.start == start - - -@pytest.mark.parametrize("name,start", [ - ("integer_name", None), - ("integer_another_name", 42), -]) -def test_Integer_to_xml(name, start): - r = Int32(name, start) - xml = r.to_xml() - if start is not None: - assert xml.attrib['start'] == str(start) - - -@pytest.mark.parametrize("name,start", [ - ("real_name", None), - ("real_another_name", 22.), -]) -def test_Real_constructor(name, start): - r = Float64(name, start) - - assert r.start == start - - -@pytest.mark.parametrize("name,start", [ - ("real_name", None), - ("real_another_name", 22.), -]) -def test_Real_to_xml(name, start): - r = Float64(name, start) - xml = r.to_xml() - if start is not None: - assert xml.attrib['start'] == f"{start:.16g}" - - -@pytest.mark.parametrize("name,start", [ - ("string_name", None), - ("string_another_name", "dummy"), -]) -def test_String_constructor(name, start): - r = String(name, start) - - assert r.start == start - - -@pytest.mark.parametrize("name,start", [ - ("string_name", None), - ("string_another_name", "dummy"), -]) -def test_String_to_xml(name, start): - r = String(name, start) - xml = r.to_xml() - if start is not None: - start_elements = xml.findall('.//Start') - assert len(start_elements) == 1 - assert start_elements[0].attrib['value'] == str(start) - - -@pytest.mark.requirements("numpy") -@pytest.mark.parametrize("name,start,dims", [ - ("array1", [1.,2.,3.,4.], [4]), - ("array2", [1.,2.,3.,4.], [2, 2]) -]) -def test_array_to_xml(name, start, dims): - r = Float64(name, start, dimensions=[Dimension(start=val) for val in dims]) - xml = r.to_xml() - if start is not None: - assert xml.attrib['start'] == " ".join([f"{val:.16g}" for val in flatten(start)]) - if dims is not None: - xml_dims = xml.findall('.//Dimension') - assert len(xml_dims) == len(dims) - assert [xml_dim.attrib['start'] for xml_dim in xml_dims] == dims - - -@pytest.mark.requirements("numpy") -@pytest.mark.parametrize("name,start,dims", [ - ("array1", [1.,2.,3.,4.], [4]), - ("array2", [1.,2.,3.,4.], [2, 2]), - ("array3", [1.,2.,3.,4.,5.,6.,7.,8.], [2, 2, 2]) -]) -def test_array_output_to_xml(name, start, dims): - import numpy as np - start = np.reshape(start, newshape=dims) - r = Float64(name, start, dimensions=[Dimension(start=val) for val in dims], causality=Fmi3Causality.output) - xml = r.to_xml() - if start is not None: - assert xml.attrib['start'] == " ".join([f"{val:.16g}" for val in flatten(start)]) - if dims is not None: - xml_dims = xml.findall('.//Dimension') - assert len(xml_dims) == len(dims) - assert [xml_dim.attrib['start'] for xml_dim in xml_dims] == dims \ No newline at end of file diff --git a/pythonfmu3/tests/utils.py b/pythonfmu3/tests/utils.py deleted file mode 100644 index 218a0c9..0000000 --- a/pythonfmu3/tests/utils.py +++ /dev/null @@ -1,13 +0,0 @@ -from pythonfmu3.variables import Boolean, Int32, UInt64, Float64, ModelVariable, String - -class UInt64ValType(int): pass - - -FMI2PY = dict(( - (Boolean, bool), - (Int32, int), - (Float64, float), - (String, str), - (UInt64, UInt64ValType), -)) -PY2FMI = dict([(v, k) for k, v in FMI2PY.items()]) diff --git a/pythonfmu3/unit.py b/pythonfmu3/unit.py deleted file mode 100644 index cb8640f..0000000 --- a/pythonfmu3/unit.py +++ /dev/null @@ -1,62 +0,0 @@ -from xml.etree.ElementTree import Element - -class BaseUnit(object): - tag = "BaseUnit" - base_units = { - "kg": 0, - "m": 0, - "s": 0, - "A": 0, - "K": 0, - "mol": 0, - "cd": 0, - "rad": 0, - } - - def __init__(self, factor=1.0, offset=0.0, **kwargs) -> None: - self._factor = factor - self._offset = offset - self._units = {**BaseUnit.base_units, **kwargs} - - @property - def units(self): - return {key: str(value) for key, value in self._units.items() if value != 0} - - def to_xml(self): - """Convert the variable to XML node. - - Returns - xml.etree.ElementTree.Element: XML node - """ - attrib = dict() - if self._factor != 1.0: - attrib["factor"] = str(self._factor) - if self._offset != 0.0: - attrib["offset"] = str(self._offset) - attrib.update(self.units) - ele = Element(self.tag, attrib) - return ele - - -class Unit(object): - tag = "Unit" - - def __init__(self, name, **kwargs): - self._name = name - self._base_unit = BaseUnit(**kwargs) - - @property - def name(self) -> str: - return self._name - - def to_xml(self) -> Element: - """Convert the variable to XML node. - - Returns - xml.etree.ElementTree.Element: XML node - """ - attrib = dict() - attrib["name"] = self._name - ele = Element(self.tag, attrib) - ele.append(self._base_unit.to_xml()) - return ele diff --git a/pythonfmu3/variables.py b/pythonfmu3/variables.py deleted file mode 100644 index c2ee44e..0000000 --- a/pythonfmu3/variables.py +++ /dev/null @@ -1,425 +0,0 @@ -"""Classes describing interface variables.""" -from abc import ABC -from enum import Enum -import importlib -from typing import Any, Optional, List -from xml.etree.ElementTree import Element, SubElement -from collections.abc import Iterable -from collections import ChainMap -from functools import reduce - -from .enums import Fmi3Causality, Fmi3Initial, Fmi3Variability - -MAX_LENGTH = 1000 - -def flatten(lst): - for item in lst: - if isinstance(item, Iterable) and not isinstance(item, (str, bytes)): - yield from flatten(item) - else: - yield item - -def check_numpy(): - try: - importlib.import_module('numpy') - except ModuleNotFoundError: - raise ModuleNotFoundError("Numpy is not installed, it is required for Array support") - -class ModelVariable(ABC): - """Abstract FMI model variable definition. - - Args: - name (str): Variable name - causality (:obj:`Fmi3Causality`, optional): Variable causality - description (str, optional): Variable description - initial (:obj:`Fmi3Initial`, optional): Variable initial status - variability (:obj:`Fmi3Variability`, optional): Variable variability - """ - def __init__( - self, - name: str, - causality: Optional[Fmi3Causality] = None, - description: Optional[str] = None, - initial: Optional[Fmi3Initial] = None, - variability: Optional[Fmi3Variability] = None, - declared_type: Optional[str] = None, - getter: Any = None, - setter: Any = None - ): - self.getter = getter - self.setter = setter - self._type = None - self.local_name = name.split(".")[-1] - - # demanagle names - self.local_name = self.local_name.lstrip('_') - - - self.__attrs = { - "name": name, - "valueReference": None, - "description": description, - "causality": causality, - "variability": variability, - "initial": initial, - "declaredType": declared_type, - # 'canHandleMultipleSetPerTimeInstant': # Only for ME - } - self._extras = {} - - @property - def causality(self) -> Optional[Fmi3Causality]: - """:obj:`Fmi3Causality` or None: Variable causality - None if not set""" - return self.__attrs["causality"] - - @property - def description(self) -> Optional[str]: - """str or None: Variable description - None if not set""" - return self.__attrs["description"] - - @property - def initial(self) -> Optional[Fmi3Initial]: - """:obj:`Fmi3Initial` or None: Variable initial status - None if not set""" - return self.__attrs["initial"] - - @property - def name(self) -> str: - """str: Variable name""" - return self.__attrs["name"] - - @property - def value_reference(self) -> int: - """int: Variable reference index""" - return self.__attrs["valueReference"] - - @value_reference.setter - def value_reference(self, value: int): - if self.__attrs["valueReference"] is not None: - raise RuntimeError("Value reference already set.") - self.__attrs["valueReference"] = value - - @property - def declared_type(self) -> str: - """str: declared type""" - return self.__attrs["declaredType"] - - @declared_type.setter - def declared_type(self, value: str): - if self.__attrs["declaredType"] is not None: - raise RuntimeError("Declared type already set.") - self.__attrs["declaredType"] = value - - @property - def variability(self) -> Optional[Fmi3Variability]: - """:obj:`Fmi3Variability` or None: Variable variability - None if not set""" - return self.__attrs["variability"] - - @staticmethod - def requires_start(v: 'ModelVariable') -> bool: - """Test if a variable requires a start attribute - - Returns: - True if successful, False otherwise - """ - return ( - v.initial == Fmi3Initial.exact - or v.initial == Fmi3Initial.approx - or v.causality == Fmi3Causality.input - or v.causality == Fmi3Causality.parameter - or v.variability == Fmi3Variability.constant - ) - - def to_xml(self) -> Element: - """Convert the variable to XML node. - - Returns - xml.etree.ElementTree.Element: XML node - """ - attrib = dict() - for key, value in ChainMap(self._extras, self.__attrs).items(): - if value is not None: - attrib[key] = str(value.name if isinstance(value, Enum) else value) - return Element(self._type, attrib) - - def __repr__(self) -> str: - return f"{self.__class__.__name__}" \ - f"(name={self.name}, " \ - f"causality={self.causality}, " \ - f"variability={self.variability})" - -class Start(object): - def __init__(self, startValue): - self.value = startValue - - def to_xml(self) -> Element: - attrib = dict() - attrib["value"] = self.value - return Element("Start", attrib) - -class Dimension(object): - def __init__(self, start: str = "", valueReference: str = ""): - if start and valueReference and any((start, valueReference)): - raise RuntimeError("start and valueReference attributes are mutally exclusive for Dimension element") - - self.start = start - self.value_reference = valueReference - - def size(self, vars : List[ModelVariable]): - if self.start: - return self.start - else: - result = next((value for vr, value in vars.items() if vr == int(self.value_reference)), None) - return result.getter() - - def to_xml(self) -> Element: - attrib = dict() - - if self.start: - attrib["start"] = self.start - else: - attrib['valueReference'] = self.value_reference - ele = Element("Dimension", attrib) - return ele - -class Arrayable(object): - def __init__(self, dimensions : List[Dimension] = [], **kwargs): - if dimensions: - check_numpy() - self._dimensions = dimensions - - @property - def dimensions(self) -> List[Dimension]: - return self._dimensions - - def get_start_str(self, value, formatter): - if len(self.dimensions) > 0: - output = " ".join([formatter(val) for val in flatten(value)]) - if len(output) > MAX_LENGTH: - output = output[0] - return output - else: - return formatter(value) - - def dimensions_xml(self) -> List[Element]: - return [dim.to_xml() for dim in self._dimensions] - - def size(self, vars): - return reduce(lambda x, dim: x * int(dim.size(vars)), self._dimensions, 1) - -class Float64(ModelVariable, Arrayable): - def __init__(self, name: str, start: Optional[Any] = None, derivative: Optional[Any] = None, dimensions: List[Dimension] = [], unit: Optional[str] = None, **kwargs): - ModelVariable.__init__(self, name, **kwargs) - Arrayable.__init__(self, dimensions) - self.__attrs = {"start": start, "derivative": derivative} - self._type = "Float64" - self._unit = unit - - @property - def start(self) -> Optional[Any]: - return self.__attrs["start"] - - @start.setter - def start(self, value: float): - self.__attrs["start"] = value - - @property - def unit(self) -> Optional[Any]: - return self._unit - - @unit.setter - def unit(self, value: str): - self._unit = value - - @property - def derivative(self): - return self.__attrs["derivative"] - - def to_xml(self) -> Element: - attrib = dict() - for key, value in self.__attrs.items(): - if value is not None: - # In order to not loose precision, a number of this type should be - # stored on an XML file with at least 16 significant digits - output = self.get_start_str(value, lambda v: f"{v:.16g}") - attrib[key] = output - - if self.unit: - attrib["unit"] = self.unit - - self._extras = attrib - parent = super().to_xml() - - parent.extend(self.dimensions_xml()) - - return parent - - -class Int32(ModelVariable, Arrayable): - def __init__(self, name: str, start: Optional[Any] = None, dimensions: List[Dimension] = [], **kwargs): - ModelVariable.__init__(self, name, **kwargs) - Arrayable.__init__(self, dimensions, **kwargs) - self.__attrs = {"start": start} - self._type = "Int32"; - - @property - def start(self) -> Optional[Any]: - return self.__attrs["start"] - - @start.setter - def start(self, value: int): - self.__attrs["start"] = value - - def to_xml(self) -> Element: - attrib = dict() - for key, value in self.__attrs.items(): - if value is not None: - attrib[key] = self.get_start_str(value, lambda v: str(v)) - self._extras = attrib - parent = super().to_xml() - - parent.extend(self.dimensions_xml()) - - return parent - -class Int64(ModelVariable, Arrayable): - def __init__(self, name: str, start: Optional[Any] = None, dimensions: List[Dimension] = [], **kwargs): - ModelVariable.__init__(self, name, **kwargs) - Arrayable.__init__(self, dimensions, **kwargs) - self.__attrs = {"start": start} - self._type = "Int64"; - - @property - def start(self) -> Optional[Any]: - return self.__attrs["start"] - - @start.setter - def start(self, value: int): - self.__attrs["start"] = value - - def to_xml(self) -> Element: - attrib = dict() - for key, value in self.__attrs.items(): - if value is not None: - attrib[key] = self.get_start_str(value, lambda v: str(v)) - self._extras = attrib - parent = super().to_xml() - - parent.extend(self.dimensions_xml()) - - return parent - -class UInt64(ModelVariable, Arrayable): - def __init__(self, name: str, start: Optional[Any] = None, dimensions: List[Dimension] = [], **kwargs): - ModelVariable.__init__(self, name, **kwargs) - Arrayable.__init__(self, dimensions, **kwargs) - self.__attrs = {"start": start} - self._type = "UInt64"; - - @property - def start(self) -> Optional[Any]: - return self.__attrs["start"] - - @start.setter - def start(self, value: int): - self.__attrs["start"] = value - - def to_xml(self) -> Element: - attrib = dict() - for key, value in self.__attrs.items(): - if value is not None: - attrib[key] = self.get_start_str(value, lambda v: str(v)) - self._extras = attrib - parent = super().to_xml() - - parent.extend(self.dimensions_xml()) - - return parent - -class Boolean(ModelVariable, Arrayable): - def __init__(self, name: str, start: Optional[Any] = None, dimensions: List[Dimension] = [], **kwargs): - ModelVariable.__init__(self, name, **kwargs) - Arrayable.__init__(self, dimensions, **kwargs) - self.__attrs = {"start": start} - self._type = "Boolean" - - @property - def start(self) -> Optional[Any]: - return self.__attrs["start"] - - @start.setter - def start(self, value: float): - self.__attrs["start"] = value - - def to_xml(self) -> Element: - attrib = dict() - for key, value in self.__attrs.items(): - if value is not None: - attrib[key] = self.get_start_str(value, lambda v: str(v).lower()) - self._extras = attrib - parent = super().to_xml() - - parent.extend(self.dimensions_xml()) - - return parent - - -class String(ModelVariable): - def __init__(self, name: str, start: Optional[Any] = None, dimensions: List[Dimension] = [], **kwargs): - ModelVariable.__init__(self, name, **kwargs) - self.__attrs = dict() - self._type = "String" - self._start = Start(start) - - @property - def start(self) -> Optional[Any]: - return self._start.value - - @start.setter - def start(self, value: float): - self._start.value = value - - def to_xml(self) -> Element: - attrib = dict() - for key, value in self.__attrs.items(): - if value is not None: - attrib[key] = str(value, lambda v: str(v)) - self._extras = attrib - parent = super().to_xml() - - if self.start is not None: - parent.append(self._start.to_xml()) - - return parent - -class Enumeration(ModelVariable, Arrayable): - def __init__(self, name: str, start: Optional[Any] = None, declared_type: Optional[Any] = None, dimensions: List[Dimension] = [], **kwargs): - ModelVariable.__init__(self, name, **kwargs) - Arrayable.__init__(self, dimensions, **kwargs) - self.__attrs = {"start": start, "declaredType": declared_type} - self._type = "Enumeration" - - @property - def start(self) -> Optional[Any]: - return self.__attrs["start"] - - @start.setter - def start(self, value: float): - self.__attrs["start"] = value - - @property - def declared_type(self) -> Optional[Any]: - return self.__attrs["declaredType"] - - @declared_type.setter - def declared_type(self, value: float): - self.__attrs["declaredType"] = value - - def to_xml(self) -> Element: - attrib = dict() - for key, value in self.__attrs.items(): - if value is not None: - attrib[key] = str(value) - self._extras = attrib - parent = super().to_xml() - - return parent diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index c6cea94..0000000 --- a/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -fmpy -pytest \ No newline at end of file diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..80a6795 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,192 @@ +exclude = [ + ".git", + ".venv", + "dist", + "*cache", + "**/__pycache__", + "tests/data", + "tests/test_working_directory", # used during testing + "examples", # python files in examples originate from other sources (FMUs) +] +src = [ + "src", +] +line-length = 120 +target-version = "py311" + +[lint] +# Settings for Ruff linter (invoked with `uv run ruff check`). +# Start by including _all_ Ruff lint rules, then ignore selected rules as needed +# https://docs.astral.sh/ruff/rules/ +select = [ + "ALL", +] +ignore = [ + # Ruff lint rules temporarily ignored, but which should be reactivated and resolved in the future. + "CPY001", #Missing copyright notice at top of file + "N802", # lowercase function names. Since many names are aligned with fmpy this is difficult to achieve + "D100", # Missing docstring in public module + "D101", # Missing docstring in public class + "D102", # Missing docstring in public method + "D103", # Missing docstring in public function + "D104", # Missing docstring in public package + "D105", # Missing docstring in magic method + "D107", # Missing docstring in __init__ + # "D202", # No blank lines allowed after function docstring + # "D203", # 1 blank line required before class docstring + # "D205", # 1 blank line required between summary line and description + # "D212", # Multi-line docstring summary should start at the first line + # "D213", # Multi-line docstring summary should start at the second line + # "E501", # Line length too long + # "N803", # Argument name should be lowercase (uncommented. Lower-camelCase is accepted for variables related to XML and FMI standard) + # "N806", # Variable in function should be lowercase (uncomment if you want to allow Uppercase variable names in functions) + + # Ruff lint rules considered as too strict and hence ignored + "FIX002", # Line contains TODO, consider resolving the issue + "TD003", # Missing issue link on the line following a TODO + "S101", # Use of assert detected + "RET504", # Unnecessary assignment to `result` before `return` statement + "EM101", # Exception must not use a string literal, assign to variable first + "EM102", # Exception must not use an f-string literal, assign to variable first + "TRY003", # Avoid specifying long messages outside the exception class + "PLR1711", # Useless `return` statement at end of function + "G00", # Logging statement uses string formatting ('G00' covers all rules flagging string formatting in logging, e.g. G001, G002, etc.) + "S311", # Standard pseudo-random generators are not suitable for cryptographic purposes + "PLW0603", # Using the global statement to update {name} is discouraged + "PYI041", # Use `float` instead of `int | float` + + # Ruff lint rules recommended to keep enabled, + # but which are typical candidates you might have a need to ignore, + # especially in the beginning or when refactoring an existing codebase, + # to avoid too many Ruff errors at once. + # -> Listed here for easy access and reference. + # (uncomment to ignore) + # "N803", # Argument name should be lowercase (NOTE: ignore to allow capital arguments (e.g X) in scientific code) + # "N806", # Variable in function should be lowercase (NOTE: ignore to allow capital variables (e.g X) in scientific code) + # "TC002", # Move third-party import into a type-checking block + # "TC003", # Move standard library import into a type-checking block + + # Ruff lint rules known to be in conflict with Ruff formatter. + # https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules + "W191", # Tab-indentation (in conflict with Ruff formatter) + "E111", # Indentation with invalid multiple (in conflict with Ruff formatter) + "E114", # Indentation with invalid multiple comment (in conflict with Ruff formatter) + "E117", # Over-indented (in conflict with Ruff formatter) + "D206", # Indent with spaces (in conflict with Ruff formatter) + "D300", # Triple single quotes (in conflict with Ruff formatter) + "Q000", # Bad quotes in inline string (in conflict with Ruff formatter) + "Q001", # Bad quotes in multi-line string (in conflict with Ruff formatter) + "Q002", # Bad quotes in DocString (in conflict with Ruff formatter) + "Q003", # Avoidable escaped quote (in conflict with Ruff formatter) + "COM812", # Missing trailing comma (in conflict with Ruff formatter) + "COM819", # Prohibited trailing comma (in conflict with Ruff formatter) + "ISC001", # Single-line implicit string concatenation (in conflict with Ruff formatter) + "ISC002", # Multi-line implicit string concatenation (in conflict with Ruff formatter) +] +# File patterns to be excluded from Ruff lint +# (only needed for file patterns not already listed in the common `exclude` setting +# at top of this file, i.e. list here _additional_ excludes specific to Ruff lint.) +exclude = [ +] +allowed-confusables = [ + "×", # used as dim multiplication sign in comments, such as `19×16×15×16×8×6×3 = 10,506,240 possible combinations of parameters`. +] + +[lint.pep8-naming] +ignore-names = [ + "test_*", +] + +[lint.pylint] +max-args = 7 + +[lint.flake8-pytest-style] +raises-require-match-for = [ + "BaseException", + "Exception", + "OSError", + "IOError", + "EnvironmentError", + "socket.error", +] + +[lint.per-file-ignores] +# `__init__.py` specific ignores +"__init__.py" = [ + "F401", # {name} imported but unused (NOTE: ignored as imports in `__init__.py` files are almost never used inside the module, but are intended for namespaces) + "I001", # Import block is un-sorted or un-formatted + "PLC0414", # Import alias does not rename original package +] +# `tests/simulation.py` specific ignores (copied from fmpy) +"tests/simulation.py" = [ + "F405", # {name} may be undefined, or defined from star imports +] +# `tests` specific ignores +"tests/**/*" = [ + "D", # Missing docstrings + "ERA001", # Found commented-out code + "PT006", # Wrong type passed to first argument of `@pytest.mark.parametrize` (NOTE: ignored to allow parameters args as "args_1,arg_2,arg_3,..." + "S101", # Use of assert detected + "PLR2004", # Magic value used in comparison + "ANN201", # Missing return type annotation for public function + "ANN202", # Missing return type annotation for private function + "ARG001", # Unused function argument: {name} + "ARG002", # Unused method argument: {name} + "INP001", # File is part of an implicit namespace package. Add an `__init__.py`. (NOTE: tests are not intended to be a module, __init__.py hence not required.) + "SLF001", # Private member accessed + "TRY004", # Prefer `TypeError` exception for invalid type + "T201", # `print` found <-- consider replacing `print` with `logging` statements and reactivate this rule. CLAROS, 2026-04-13 +] +# `stubs` specific ignores +"stubs/**/*" = [ + "D", # Missing docstrings + "ERA001", # Found commented-out code + "SLF001", # Private member accessed + "F405", # {name} may be undefined, or defined from star imports: {module} + "F403", # from {name} import * used; unable to detect undefined names + "ANN", # Missing type annotation + "N", # Naming violations + "A001", # Variable {name} is shadowing a Python builtin + "A002", # Argument {name} is shadowing a Python builtin + "FBT001", # Boolean-typed positional argument in function definition + "PYI042", # Type alias {name} should be CamelCase + "PYI002", # complex if statement in stub + "PLR0913", # Too many arguments in function definition +] +# Jupyter notebook specific ignores +"**/*.ipynb" = [ + "D103", # Missing docstring in public function + "T201", # `print` found + "PGH003", # Use specific rule codes when ignoring type issues + "TCH002", # Move third-party import into a type-checking block +] +# `examples` specific ignores +"examples/**/*" = [ + "D", # Missing docstrings + "S101", # Use of assert detected + "PLR2004", # Magic value used in comparison + "INP001", # File is part of an implicit namespace package. Add an `__init__.py`. (NOTE: tutorials are not intended to be a module, __init__.py hence not required.) + "T201", # `print` found + "E402", # Module level import not at top of cell +] +# utils/logging specific ignores +"**/utils/logging.py" = [ + "A005", # Module `logging` shadows a Python standard-library module +] +# docs/source/conf.py specific ignores +"docs/source/conf.py" = [ + "INP001", # File is part of an implicit namespace package. Add an `__init__.py`. (NOTE: conf.py is not intended to be a module, __init__.py hence not required.) + "A001", # Variable {name} is shadowing a Python builtin + "D100", # Missing docstring in public module +] +# types.py specific ignores +"**/types.py" = [ + "A005", # Module `types` shadows a Python standard-library module +] + +[lint.pydocstyle] +convention = "numpy" + +[format] +docstring-code-format = true +# preview = true # uncomment to enable preview features of Ruff formatter (https://docs.astral.sh/ruff/formatter/#preview-features) diff --git a/pythonfmu3/tests/__init__.py b/src/pythonfmu3/__init__.py similarity index 100% rename from pythonfmu3/tests/__init__.py rename to src/pythonfmu3/__init__.py diff --git a/pythonfmu3/__main__.py b/src/pythonfmu3/__main__.py similarity index 83% rename from pythonfmu3/__main__.py rename to src/pythonfmu3/__main__.py index da58e8d..3ac507d 100644 --- a/pythonfmu3/__main__.py +++ b/src/pythonfmu3/__main__.py @@ -1,13 +1,14 @@ import argparse from pythonfmu3 import builder, deploy -from ._version import __version__ + +from importlib.metadata import version def cli_main(): parser = argparse.ArgumentParser(prog="pythonfmu") - parser.add_argument("-V", "--version", action="version", version=__version__) + parser.add_argument("-V", "--version", action="version", version=version) def default_execution(**kwargs): print("A subcommand must be provided.\n") @@ -16,13 +17,14 @@ def default_execution(**kwargs): parser.set_defaults(execute=default_execution) subparsers = parser.add_subparsers( - title="Subcommands", description="Call `pythonfmu _command_ -h` to get more help." + title="Subcommands", + description="Call `pythonfmu _command_ -h` to get more help.", ) build_parser = subparsers.add_parser( "build", description="Build an FMU from a Python script.", - help="Build an FMU from a Python script." + help="Build an FMU from a Python script.", ) builder.create_command_parser(build_parser) @@ -39,7 +41,7 @@ def default_execution(**kwargs): The tool assume the Python environment in which the FMU should be executed is the current one. """, - help="Install Python FMU dependencies." + help="Install Python FMU dependencies.", ) deploy.create_command_parser(deploy_parser) diff --git a/src/pythonfmu3/builder.py b/src/pythonfmu3/builder.py new file mode 100644 index 0000000..e991323 --- /dev/null +++ b/src/pythonfmu3/builder.py @@ -0,0 +1,275 @@ +"""Python FMU builder.""" + +import argparse +import itertools +import logging +import re +import shutil +import sys +import tempfile +import zipfile +from collections.abc import Iterable +from importlib.util import module_from_spec, spec_from_file_location +from pathlib import Path +import xml.etree.ElementTree as ET + +from pythonfmu3.fmi3slave import Fmi3SlaveBase, Fmi3Slave +from pythonfmu3.model_options import Fmi3ModelOptionsCS, Fmi3ModelOptionsME +from pythonfmu3.osutil import get_lib_extension, get_platform + +FilePath = str | Path +HERE = Path(__file__).parent + +logger = logging.getLogger(__name__) + + +def get_class_name(file_name: Path) -> str: + with Path.open(file_name) as file: + data = file.read() + found = re.search(r"class (\w+)\(([^)]*\bFmi3Slave(?:Base)?\b[^)]*)\)\s*:", data) + assert found is not None, "Class name could not be extracted." + return found.group(1) + + +def get_model_description(filepath: Path, module_name: str) -> tuple[str, ET.Element]: + """Extract the FMU model description as XML. + + Args: + filepath (pathlib.Path) : script file path + module_name (str) : python module to load + + Returns + ------- + FMU model name, model description as xml ET.Element + """ + # Add current folder to handle local dependencies + sys.path.insert(0, str(filepath.parent)) + try: + # Import the user interface + spec = spec_from_file_location(module_name, filepath) + assert spec is not None, f"Spec could not be imported from module {module_name}, path {filepath}" + fmu_interface = module_from_spec(spec) + assert fmu_interface is not None, f"Intrface could not be imported from spec {spec}" + assert spec.loader is not None, f"No loader for spec {spec} found." + spec.loader.exec_module(fmu_interface) + # Instantiate the interface + class_name = get_class_name(filepath) + instance = getattr(fmu_interface, class_name)(instanceName="dummyInstance", resources=str(filepath.parent)) + model_options_cs = instance.model_options_cs.to_dict() + finally: + sys.path.remove(str(filepath.parent)) # remove inserted temporary path + + if not isinstance(instance, Fmi3SlaveBase): + raise TypeError(f"The provided class '{class_name}' does not inherit from {Fmi3SlaveBase.__qualname__}") + # Produce the xml + _xml : ET.Element = instance.to_xml(model_options_cs) + assert instance.modelName is not None, "Need an instance and modelName at this point" + return (instance.modelName, _xml) + + +class FmuBuilder: + @staticmethod + def build_FMU( # noqa: PLR0915, PLR0912, C901 ## should be simplified! + script_file: FilePath, + dest: FilePath = ".", + project_files: Iterable[FilePath] = set(), + documentation_folder: FilePath | None = None, + terminals: FilePath | None = None, + options: dict[str, bool|int|float|None] | None = None, + ) -> Path: + _script_file = Path(script_file) + if not _script_file.exists(): + raise ValueError(f"No such file {_script_file}") + if not _script_file.suffix.endswith(".py"): + raise ValueError(f"File {_script_file} must have extension '.py'!") + + _dest = Path(dest) + if not _dest.exists(): + _dest.mkdir(parents=True) + _project_files = set(map(Path, project_files)) + + if documentation_folder is not None: + documentation_folder = Path(documentation_folder) + if not documentation_folder.exists(): + raise ValueError(f"The documentation folder does not exists {documentation_folder!s}") + + if terminals is not None: + terminals = Path(terminals) + if not terminals.exists(): + raise ValueError(f"The specified terminalsAndIcons file does not exists {terminals!s}") + if not terminals.name == "terminalsAndIcons.xml": + raise ValueError( + f"Incorrect terminal name {terminals!s}. Terminal file must be named terminalsAndIcons.xml" + ) + + module_name = _script_file.stem + + with tempfile.TemporaryDirectory(prefix="pythonfmu_") as tempd: + temp_dir = Path(tempd) + shutil.copy2(_script_file, temp_dir) + + # Embed pythonfmu in the FMU so it does not need to be included + dep_folder = temp_dir / "pythonfmu3" + dep_folder.mkdir() + for dep in HERE.glob("*.py"): # Find all python files at the same level as this one + shutil.copy2(dep, dep_folder) + for file_ in _project_files: + if file_ == _script_file.parent: + new_folder = temp_dir / file_.name + new_folder.mkdir() + for f in file_.iterdir(): + if f.is_dir(): + temp_dest = new_folder / f.name + shutil.copytree(f, temp_dest) + elif f.name != _script_file.name: + shutil.copy2(f, new_folder) + else: + logger.debug("Skip file with the same name as the script found in project file.") + elif file_.is_dir(): + temp_dest = temp_dir / file_.name + shutil.copytree(file_, temp_dest) + else: + shutil.copy2(file_, temp_dir) + + model_identifier, xml = get_model_description(temp_dir.absolute() / _script_file.name, module_name) + + dest_file = _dest / f"{model_identifier}.fmu" + + type_node = xml.find("CoSimulation") + cs_option_names = list(Fmi3ModelOptionsCS().to_dict().keys()) + if type_node is not None and options is not None: + for option, value in options.items(): + if option in cs_option_names: + type_node.set(option, str(value).lower()) + + type_node = xml.find("ModelExchange") + me_option_names = list(Fmi3ModelOptionsME().to_dict().keys()) + if type_node is not None and options is not None: + for option, value in options.items(): + if option in me_option_names: + type_node.set(option, str(value).lower()) + + with zipfile.ZipFile(dest_file, "w") as zip_fmu: + resource = Path("resources") + + # Add files copied in temporary directory + for f in temp_dir.rglob("*"): + if f.is_file() and f.parent.name != "__pycache__": + relative_f = f.relative_to(temp_dir) + zip_fmu.write(f, arcname=(resource / relative_f)) + + # Add information for the Python loader + zip_fmu.writestr(str(resource.joinpath("slavemodule.txt")), module_name) + + # Add FMI API wrapping Python class source + sources = Path("sources") + src = HERE / "pythonfmu-export" + for f in itertools.chain(src.rglob("*.hpp"), src.rglob("*.cpp"), src.rglob("CMakeLists.txt")): + relative_f = f.relative_to(src) + if "build" in relative_f.parts: + continue + zip_fmu.write(f, arcname=(sources / relative_f)) + + # Add FMI API wrapping Python class library + binaries = Path("binaries") + src_binaries = HERE / "resources" / "binaries" + for f in itertools.chain( + src_binaries.rglob("*.dll"), + src_binaries.rglob("*.so"), + src_binaries.rglob("*.dylib"), + ): + relative_f = f.relative_to(src_binaries) + arcname = binaries / relative_f.parent / f"{model_identifier}{relative_f.suffix}" + zip_fmu.write(f, arcname=arcname) + + # Add the documentation folder + if documentation_folder is not None: + documentation = Path("documentation") + for f in documentation_folder.rglob("*"): + if f.is_file(): + relative_f = f.relative_to(documentation_folder) + zip_fmu.write(f, arcname=(documentation / relative_f)) + + if terminals is not None: + terminals_folder = Path("terminalsAndIcons") + relative_f = terminals.relative_to(terminals.parent) + zip_fmu.write(f, arcname=(terminals_folder / relative_f)) + + # Add the model description + tree = ET.ElementTree(xml) + ET.indent(tree, space=" ", level=0) + #res = tree.write(zip_fmu, encoding='utf-8', xml_declaration=True) + #print("RES", res) +# with Path.open(temp_dir /"modelDescription.xml", 'wb') as f: +# tree.write(f, encoding='utf-8') +# num = zip_fmu.write(f) +# assert num>0 + with zip_fmu.open("modelDescription.xml", 'w') as f: + tree.write( f, encoding='utf-8', xml_declaration=True) + return dest_file + + @staticmethod + def has_binary() -> bool: + """Check the existence of the binary for this platform.""" + binary_folder = get_platform() + lib_ext = get_lib_extension() or "*" # if library extension is unknown, it will look for '*.*' in src_binaries + src_binaries = HERE / "resources" / "binaries" / binary_folder + return src_binaries.exists() and len(list(src_binaries.glob(f"*.{lib_ext}"))) >= 1 + + +def create_command_parser(parser: argparse.ArgumentParser) -> None: + parser.add_argument( + "-f", + "--file", + dest="script_file", + help="Path to the Python script.", + required=True, + ) + + parser.add_argument("-d", "--dest", dest="dest", help="Where to save the FMU.", default=".") + + parser.add_argument( + "--doc", + dest="documentation_folder", + help="Documentation folder to include in the FMU.", + default=None, + ) + + parser.add_argument( + "--terminals", + dest="terminals", + help="Terminals file (terminalsAndIcons.xml) to include in the FMU.", + default=None, + ) + + # Boolean options are added using their FMI name, making them implicitly True. + # For other options their (non-default) number is added after a space. + for name, default in Fmi3ModelOptionsCS().to_dict().items(): + if default in (True, False): + parser.add_argument(f"--{name}", dest=name, help=f"If given, {name}={not default}", action="store_true") + elif name in ("fixedInternalStepSize", "maxOutputDerivativeOrder", "recommendedIntermediateInputSmoothness"): + parser.add_argument( + f"--{name}", + dest=name, + help=f"If given, {name}= number", + ) + else: + raise ValueError(f"Something wrong with option {name}, default:{default}") from None + + cs_keys = list(Fmi3ModelOptionsCS().to_dict().keys()) + for name, default in Fmi3ModelOptionsME().to_dict().items(): + if name not in cs_keys: + if default in (True, False): + parser.add_argument(f"--{name}", dest=name, help=f"If given, {name}={not default}", action="store_true") + else: + raise ValueError(f"Something wrong with option {name}, default:{default}") from None + + parser.add_argument( + "project_files", + metavar="Project files", + nargs="*", + help="Additional project files required by the Python script.", + default=set(), + ) + + parser.set_defaults(execute=FmuBuilder.build_FMU) diff --git a/src/pythonfmu3/cosimulation.py b/src/pythonfmu3/cosimulation.py new file mode 100644 index 0000000..a716bba --- /dev/null +++ b/src/pythonfmu3/cosimulation.py @@ -0,0 +1,16 @@ +from abc import ABC, abstractmethod + +from pythonfmu3.model_returns import Fmi3StepResult + + +# co-simulation mixin +class CoSimulation(ABC): + @abstractmethod + def do_step( + self, + current_communication_point: float, + communication_step_size: float, + *, + no_set_fmu_state_prior_to_current_point: bool = False + ) -> Fmi3StepResult: + pass diff --git a/src/pythonfmu3/default_experiment.py b/src/pythonfmu3/default_experiment.py new file mode 100644 index 0000000..b560106 --- /dev/null +++ b/src/pythonfmu3/default_experiment.py @@ -0,0 +1,12 @@ +class DefaultExperiment: + def __init__( + self, + start_time: float = None, + stop_time: float = None, + communication_step_size: float = None, + tolerance: float = None, + ): + self.start_time = start_time + self.stop_time = stop_time + self.communication_step_size = communication_step_size + self.tolerance = tolerance diff --git a/pythonfmu3/deploy.py b/src/pythonfmu3/deploy.py similarity index 82% rename from pythonfmu3/deploy.py rename to src/pythonfmu3/deploy.py index 830926a..b697741 100644 --- a/pythonfmu3/deploy.py +++ b/src/pythonfmu3/deploy.py @@ -1,4 +1,5 @@ """CLI command to deploy a FMU.""" + import argparse import os import subprocess @@ -6,26 +7,24 @@ import zipfile from pathlib import Path from tempfile import TemporaryDirectory -from typing import Union from .enums import PackageManager - # Dictionary of ("default file name", "associated package manager") ENVIRONMENT_FILES = { "requirements.txt": PackageManager.pip, "environment.yaml": PackageManager.conda, - "environment.yml": PackageManager.conda + "environment.yml": PackageManager.conda, } def deploy( - fmu: Union[str, Path], - environment: Union[str, Path, None] = None, - package_manager: Union[str, PackageManager, None] = None + fmu: str | Path, + environment: str | Path | None = None, + package_manager: str | PackageManager | None = None, ) -> None: """Install Python dependency packages from requirement file shipped within the FMU. - + Args: fmu (str or pathlib.Path) : FMU file path environment (str or pathlib.Path) : optional, requirements file within the `resources` folder of the FMU @@ -75,10 +74,19 @@ def deploy( if manager == PackageManager.pip: subprocess.run( - [sys.executable, "-m", "pip", "install", "-r", f"{copy_env!s}", "--progress-bar", "off"], + [ + sys.executable, + "-m", + "pip", + "install", + "-r", + f"{copy_env!s}", + "--progress-bar", + "off", + ], stdout=sys.stdout, stderr=sys.stderr, - check=True + check=True, ) elif manager == PackageManager.conda: conda_exe = os.environ.get("CONDA_EXE", "conda") @@ -86,33 +94,27 @@ def deploy( [conda_exe, "env", "update", f"--file={copy_env!s}", "--quiet"], stdout=sys.stdout, stderr=sys.stderr, - check=True + check=True, ) def create_command_parser(parser: argparse.ArgumentParser): - parser.add_argument( - "-f", - "--file", - dest="fmu", - help="Path to the Python FMU.", - required=True - ) + parser.add_argument("-f", "--file", dest="fmu", help="Path to the Python FMU.", required=True) parser.add_argument( "-e", "--env", dest="environment", help="Requirements or environment file.", - default=None + default=None, ) parser.add_argument( choices=["pip", "conda"], dest="package_manager", - nargs='?', - help="Python packages manager" + nargs="?", + help="Python packages manager", ) parser.set_defaults(execute=deploy) diff --git a/pythonfmu3/enums.py b/src/pythonfmu3/enums.py similarity index 83% rename from pythonfmu3/enums.py rename to src/pythonfmu3/enums.py index 1311aec..d433470 100644 --- a/pythonfmu3/enums.py +++ b/src/pythonfmu3/enums.py @@ -1,4 +1,5 @@ """FMI enumerations""" + from enum import Enum, IntEnum @@ -34,6 +35,15 @@ class Fmi3Variability(Enum): continuous = 4 +class Fmi3IntervalVariability(Enum): + constant = 0 + fixed = 1 + tunable = 2 + changing = 3 + countdown = 4 + triggered = 5 + + class Fmi3Status(IntEnum): ok = 0 warning = 1 @@ -44,5 +54,6 @@ class Fmi3Status(IntEnum): class PackageManager(Enum): """Enumeration of Python packages manager.""" + pip = "pip" conda = "conda" diff --git a/src/pythonfmu3/fmi3slave.py b/src/pythonfmu3/fmi3slave.py new file mode 100644 index 0000000..c99ad52 --- /dev/null +++ b/src/pythonfmu3/fmi3slave.py @@ -0,0 +1,668 @@ +"""Define the abstract facade class.""" + +import ctypes +import datetime as dt +from functools import partialmethod +import importlib.metadata +import json +from typing import TypeVar, TYPE_CHECKING, Any, ClassVar +from uuid import uuid1 +from xml.etree.ElementTree import Element, SubElement + +import numpy as np + +from pythonfmu3.cosimulation import CoSimulation +from pythonfmu3.enums import Fmi3Causality, Fmi3Initial, Fmi3Status, Fmi3Variability +from pythonfmu3.logmsg import LogMsg +from pythonfmu3.model_options import Fmi3ModelOptionsCS, Fmi3ModelOptionsME +from pythonfmu3.modelexchange import ModelExchange +from pythonfmu3.model_returns import Fmi3StepResult, Fmi3UpdateDiscreteStatesResult +from pythonfmu3.unit import Unit +from pythonfmu3.variable_types import VariableType +from pythonfmu3.variables import ( + Boolean, + Enumeration, + Float32, + Float64, + Int8, + Int16, + Int32, + Int64, + ModelVariable, + String, + UInt8, + UInt16, + UInt32, + UInt64, +) + +if TYPE_CHECKING: + from collections.abc import Callable + from pythonfmu3.default_experiment import DefaultExperiment + from pythonfmu3.variables import FmiScalar + +TUInt = TypeVar("TUInt") + +class Fmi3SlaveBase: + """Abstract facade class to execute Python through FMI standard. + + Note that argument names use non-python style camelCase, as defined and expected in FMI standard. + Args: + instanceName: the name of the instantiated component model (FMU) + resources: optional relative path to additional resources + logger: logger callable + visible: determine whether visible features in simulation shall be active or not + eventModeUsed: Orchestrator can tell the FMU whether event mode is used + earlyReturnAllowed: Orchestrator can tell the FMU whether early return from step is allowed + model_options_cs: non-default settings of Co-Simulation model options. Transferred to modelDescription + model_options_me: non-default settings of Co-Simulation model options. Transferred to modelDescription + """ + + def __init__(self, + instanceName : str, + *, + resources : str|None = None, + logger =None, #: Callable|None = None, + visible : bool = False, + eventModeUsed : bool = False, + earlyReturnAllowed : bool = False, + model_options_cs : Fmi3ModelOptionsCS | None = None, + model_options_me : Fmi3ModelOptionsME | None = None, + # required_intermediate_variables : list[int]|None = None, + # n_required_intermediate_variables : int = 0, + # instance_environment : Callable|None = None, + # logger_msg : Callable|None = None, + # intermediate_update : Callable|None = None, + ) -> None: + print("INSTANTIATING...", instanceName) + self.model_options_cs = model_options_cs or Fmi3ModelOptionsCS() + self.model_options_me = model_options_me or Fmi3ModelOptionsME() + self.vars : dict[int,ModelVariable] = {} + self.event_indicators: list[int] = [] + self.instance_name = instanceName + self.resources = resources + self.visible = visible + #self.logger = logger + self.event_mode_used = eventModeUsed + self.early_return_allowed = earlyReturnAllowed + #self.model_options_cs = model_options_cs or Fmi3ModelOptionsCS() + #self.model_options_me = model_options_me or Fmi3ModelOptionsME() + self.log_queue : list[LogMsg] = [] + + self.guid = uuid1() + self.author: str | None = None + self.license: str | None = None + self.version: str | None = None + self.copyright: str | None = None + self.modelName: str | None = self.__class__.__name__ + self.description: str | None = None + self.default_experiment: DefaultExperiment | None = None + + self.type_definitions: dict[str, VariableType] = {} + self.units: dict[str, Unit] = {} + + log_categories: ClassVar[dict[str, str]] = { + "logStatusWarning": "Log messages with fmi3Warning status.", + "logStatusDiscard": "Log messages with fmi3Discard status.", + "logStatusError": "Log messages with fmi3Error status.", + "logStatusFatal": "Log messages with fmi3Fatal status.", + "logAll": "Log all messages.", + } + + def to_xml(self, model_options: dict[str, str] | None = None) -> Element: # noqa: PLR0915, PLR0912, C901 + """Build the XML representation of the model. + + Args: + model_options: FMU model options + + Returns + ------- + xml Element description of the FMU + """ + t = dt.datetime.now(dt.UTC) + date_str = t.isoformat(timespec="seconds") + assert self.modelName is not None, "Need a modelName at this stage." + + attrib : dict[str, str] = { + 'fmiVersion' : "3.0", + 'modelName' : self.modelName, + 'instantiationToken' : f"{self.guid!s}", + 'generationTool' : f"PythonFMU3 {importlib.metadata.version('PythonFMU3')}", + 'generationDateAndTime' : date_str, + 'variableNamingConvention' : "structured", + } + if self.description is not None: + attrib["description"] = self.description + if self.author is not None: + attrib["author"] = self.author + if self.license is not None: + attrib["license"] = self.license + if self.version is not None: + attrib["version"] = self.version + if self.copyright is not None: + attrib["copyright"] = self.copyright + + root = Element("fmiModelDescription", attrib=attrib) + + options_cs = {"modelIdentifier": self.modelName} + model_options_cs = Fmi3ModelOptionsCS().to_dict() if model_options is None else model_options + for name, default in Fmi3ModelOptionsCS().to_dict().items(): + if name in model_options_cs: + value = model_options_cs.get(name, default) + if value is not None: + options_cs[name] = str(value).lower() + + options_me = {"modelIdentifier": self.modelName} + model_options_me = Fmi3ModelOptionsME().to_dict() if model_options is None else model_options + for name, default in Fmi3ModelOptionsME().to_dict().items(): + if name in model_options_me: + value = model_options_me.get(name, default) + if value is not None: + options_me[name] = str(value).lower() + + # check if we have cosim mixin or model exchange mixin + if isinstance(self, ModelExchange): + SubElement(root, "ModelExchange", attrib=options_me) + + if isinstance(self, CoSimulation): + SubElement(root, "CoSimulation", attrib=options_cs) + + if self.units: + unit_defs = SubElement(root, "UnitDefinitions") + for unit in self.units.values(): + unit_defs.append(unit.to_xml()) + + if self.type_definitions: + type_defs = SubElement(root, "TypeDefinitions") + for val in self.type_definitions.values(): + type_defs.append(val.to_xml()) + + if len(Fmi3SlaveBase.log_categories) > 0: + categories = SubElement(root, "LogCategories") + for category, description in self.log_categories.items(): + categories.append( + Element( + "Category", + attrib={"name": category, "description": description}, + ) + ) + + if self.default_experiment is not None: + if self.default_experiment.start_time is not None: + attrib["startTime"] = str(self.default_experiment.start_time) + if self.default_experiment.stop_time is not None: + attrib["stopTime"] = str(self.default_experiment.stop_time) + if self.default_experiment.communicationStepSize is not None: + attrib["stepSize"] = str(self.default_experiment.communicationStepSize) + if self.default_experiment.tolerance is not None: + attrib["tolerance"] = str(self.default_experiment.tolerance) + SubElement(root, "DefaultExperiment", attrib) + + variables = SubElement(root, "ModelVariables") + for mv in self.vars.values(): + if mv.requires_start(): + self.__apply_start_value(mv) + variables.append(mv.to_xml()) + + structure = SubElement(root, "ModelStructure") + outputs = list(filter(lambda v: v.causality == Fmi3Causality.output, self.vars.values())) + + continuous_state_derivatives = list( + filter( + lambda v: ( + v.variability == Fmi3Variability.continuous + and (isinstance(v, Float64) and v.derivative is not None) + ), + self.vars.values(), + ) + ) + + allowed_variability = [None, Fmi3Initial.approx, Fmi3Initial.calculated] + initial_unknown = list( + filter( + lambda v: ( + (v.causality == Fmi3Causality.output and (v.initial in allowed_variability)) + or v.causality == Fmi3Causality.calculatedParameter + or (v in continuous_state_derivatives + and v.initial in allowed_variability) + ), + self.vars.values(), + ) + ) + + for v in outputs: + SubElement(structure, "Output", attrib = {'valueReference' : str(v.value_reference)}) + + for v in continuous_state_derivatives: + SubElement(structure, "ContinuousStateDerivative", attrib={'valueReference' : str(v.value_reference)}) + + for v in initial_unknown: + SubElement(structure, "InitialUnknown", attrib={'valueReference' : str(v.value_reference)}) + + for v in self.event_indicators: + SubElement(structure, "EventIndicator", attrib={'valueReference' : str(v)}) + + return root + + def __apply_start_value(self, mv: ModelVariable) -> None: + vrs = [mv.value_reference] + refs : FmiScalar | list[FmiScalar] + if isinstance(mv, Int32): + refs = self.get_int32(vrs) + elif isinstance(mv, (Enumeration, Int64)): + refs = self.get_int64(vrs) + elif isinstance(mv, UInt64): + refs = [val.value for val in self.get_uint64(vrs)] + elif isinstance(mv, Float64): + refs = self.get_float64(vrs) + elif isinstance(mv, Boolean): + refs = self.get_boolean(vrs) + elif isinstance(mv, String): + refs = self.get_string(vrs) + else: + raise KeyError(f"Unsupported type {type(mv)}!") + mv.start = refs if len(getattr(mv, "dimensions", [])) else refs[0] + + def register_variable( + self, + var: ModelVariable, + *, + nested: bool = True, + var_type : VariableType | None = None, + has_event_indicator: bool = False, + ) -> None: + """Register a variable as FMU interface. + + Args: + var: The variable to be registered + nested: Optional, does the "." in the variable name reflect an object hierarchy to access it? Default True + var_type: + has_event_indicator: + """ + variable_reference = len(self.vars) + self.vars[variable_reference] = var + # Set the unique value reference + var.value_reference = variable_reference + owner = self + if var.getter is None and nested and "." in var.name: + split = var.name.split(".") + split.pop(-1) + for s in split: + owner = getattr(owner, s) + if var.getter is None: + if hasattr(var, "dimensions") and len(var.dimensions) > 0: + var.getter = lambda: getattr(owner, var.local_name).flatten().tolist() + else: + var.getter = lambda: getattr(owner, var.local_name) + if var.setter is None and hasattr(owner, var.local_name) and var.variability != Fmi3Variability.constant: + if hasattr(var, "dimensions") and len(var.dimensions) > 0: + var.setter = lambda v: setattr( + owner, + var.local_name, + np.reshape(v, shape=getattr(owner, var.local_name).shape), + ) + else: + var.setter = lambda v: setattr(owner, var.local_name, v) + + if var_type is not None: + self.type_definitions[var_type.name] = var_type + var.declared_type = var_type.name + + if has_event_indicator: + self.register_event_indicator(var.value_reference) + + def register_event_indicator(self, vr:int) -> None: + self.event_indicators.append(vr) + + def setup_experiment(self, start_time: float) -> None: + self.log(f"setup_experiment({start_time}) not defined within FMI3. Use enter_initialization_mode()") + + def register_units(self, units: list[Unit]) -> None: + for unit in units: + self.units[unit.name] = unit + + def enterInitializationMode(self, + toleranceDefined:bool, + tolerance:float, + startTime:float, + stopTimeDefined:bool, + stopTime:float): + """Translate the FMI3 call to the python-adapted call.""" + return self.enter_initialization_mode( + tolerance = tolerance if toleranceDefined else None, + start_time = startTime, + stop_time = stopTime if stopTimeDefined else None + ) + + def enter_initialization_mode( + self, tolerance: float | None = None, start_time: float = 0.0, stop_time: float | None = None + ) -> None: + """Run initialization mode in Python-adapted style. + + Note: we allow that both tolerance and stop_time are set to None. + This means only that there are no limits and that the orchestrator can run as long as desired. + """ + pass + + def exit_initialization_mode(self) -> None: + pass + + def doStep(self, + currentCommunicationPoint: float, + communicationStepSize: float, + noSetFMUStatePriorToCurrentPoint: bool + ) -> Fmi3StepResult: + """Translate the FMI3 call to the python-adapted call.""" + return self.do_step(currentCommunicationPoint, communicationStepSize, noSetFMUStatePriorToCurrentPoint) + + def do_step(self, + current_communication_point: float, + communication_step_size: float, + *, + no_set_fmu_state_prior_to_current_point: bool = False, + ) -> Fmi3StepResult: + """Run doStep in Python-adapted style.""" + return Fmi3StepResult(False, False, False, current_communication_point+communication_step_size) + + + def update_discrete_states(self) -> Fmi3UpdateDiscreteStatesResult: + return Fmi3UpdateDiscreteStatesResult() # default. Should be overridden. + + def terminate(self) -> None: + pass + + def get_int32(self, vrs: list[int]) -> list[int]: + refs : list[int] = [] + for vr in vrs: + var = self.vars[vr] + if isinstance(var, (Int32,Int8,Int16,Int64)): + if len(var.dimensions) == 0: + refs.append(int(var.getter())) + else: + refs.extend(map(int, var.getter())) + else: + raise TypeError(f"Variable with valueReference={vr} is not of type Int32!") + return refs + + def get_int8(self, vrs: list[int]) -> list[int]: + return self.get_int32( vrs) + + def get_int16(self, vrs: list[int]) -> list[int]: + return self.get_int32( vrs) + + def get_int64(self, vrs: list[int]) -> list[int]: + return self.get_int32( vrs) + +# def get_uint64(self, vrs: list[int]) -> list[ctypes.c_uint64]: +# refs : list[ctypes.c_uint64] = [] +# for vr in vrs: +# var = self.vars[vr] +# if isinstance(var, (UInt64,UInt32,UInt16,UInt8)): +# if len(var.dimensions) == 0: +# val = var.getter() +# refs.append(ctypes.c_uint64(val) if not isinstance(val, ctypes.c_uint64) else val) +# else: +# refs.extend(map(ctypes.c_uint64, var.getter())) +# else: +# raise TypeError(f"Variable with valueReference={vr} is not of type Uint64!") +# return refs +# + + def get_uint(self, vrs: list[int], fmi_type:TUInt, c_type:TUInt=ctypes.c_uint64) -> list[TUInt]: + refs : list[T] = [] + for vr in vrs: + var = self.vars[vr] + if isinstance(var, fmi_type): + if len(var.dimensions) == 0: + val = var.getter() + refs.append(c_type(val) if not isinstance(val, c_type) else val) + else: + refs.extend(map(c_type, var.getter())) + else: + raise TypeError(f"Variable with valueReference={vr} is not of type {fmi_type}, but {var._type}!") + return refs + + def get_uint8(self, vrs: list[int]) -> list[ctypes.c_uint8]: + return self.get_uint( vrs, fmi_type=UInt8, c_type=ctypes.c_uint8) + + def get_uint16(self, vrs: list[int]) -> list[ctypes.c_uint16]: + return self.get_uint( vrs, fmi_type=UInt16, c_type=ctypes.c_uint16) + + def get_uint32(self, vrs: list[int]) -> list[ctypes.c_uint32]: + return self.get_uint( vrs, fmi_type=UInt32, c_type=ctypes.c_uint32) + + def get_uint64(self, vrs: list[int]) -> list[ctypes.c_uint64]: + return self.get_uint( vrs, fmi_type=UInt64, c_type=ctypes.c_uint64) + + def get_float64(self, vrs: list[int]) -> list[float]: + refs : list[float] = [] + for vr in vrs: + var = self.vars[vr] + if isinstance(var, (Float64, Float32)): + if len(var.dimensions) == 0: + refs.append(float(var.getter())) + else: + refs.extend(var.getter()) + else: + raise TypeError(f"Variable with valueReference={vr} is not of type Float64!") + return refs + + def get_float32(self, vrs: list[int]) -> list[float]: + return self.get_float64( vrs) + + def get_boolean(self, vrs: list[int]) -> list[bool]: + refs : list[bool] = [] + for vr in vrs: + var = self.vars[vr] + if isinstance(var, Boolean): + if len(var.dimensions) == 0: + refs.append(bool(var.getter())) + else: + refs.extend(var.getter()) + + else: + raise TypeError(f"Variable with valueReference={vr} is not of type Boolean!") + return refs + + def get_string(self, vrs: list[int]) -> list[str]: + refs : list[str] = [] + for vr in vrs: + var = self.vars[vr] + if isinstance(var, String): + refs.append(str(var.getter())) + else: + raise TypeError(f"Variable with valueReference={vr} is not of type String!") + return refs + + def set_int32(self, vrs: list[int], values: list[int]) -> None: + offset = 0 + for vr in vrs: + var = self.vars[vr] + if isinstance(var, Int32): + size = var.size(self.vars) + if size > 1: + var.setter(values[offset : offset + size]) + else: + var.setter(values[offset]) + offset += size + else: + raise TypeError(f"Variable with valueReference={vr} is not of type Int32!") + + def set_int64(self, vrs: list[int], values: list[int]) -> None: + offset = 0 + for vr in vrs: + var = self.vars[vr] + if isinstance(var, (Enumeration, Int64)): + size = var.size(self.vars) + if size > 1: + var.setter(values[offset : offset + size]) + else: + var.setter(values[offset]) + offset += size + else: + raise TypeError(f"Variable with valueReference={vr} is not of type Int64!") + + def set_uint64(self, vrs: list[int], values: list[int]) -> None: + offset = 0 + for vr in vrs: + var = self.vars[vr] + if isinstance(var, UInt64): + size = var.size(self.vars) + if size > 1: + var.setter(values[offset : offset + size]) + else: + var.setter(values[offset]) + offset += size + else: + raise TypeError(f"Variable with valueReference={vr} is not of type UInt64!") + + def set_float64(self, vrs: list[int], values: list[float]) -> None: + offset = 0 + for vr in vrs: + var = self.vars[vr] + if isinstance(var, Float64): + size = var.size(self.vars) + if size > 1: + var.setter(values[offset : offset + size]) + else: + var.setter(values[offset]) + offset += size + else: + raise TypeError(f"Variable with valueReference={vr} is not of type Float64!") + + def set_boolean(self, vrs: list[int], values: list[bool]) -> None: + offset = 0 + for vr in vrs: + var = self.vars[vr] + if isinstance(var, Boolean): + size = var.size(self.vars) + if size > 1: + var.setter(values[offset : offset + size]) + else: + var.setter(values[offset]) + offset += size + else: + raise TypeError(f"Variable with valueReference={vr} is not of type Boolean!") + + def set_string(self, vrs: list[int], values: list[str]) -> None: + for vr, value in zip(vrs, values, strict=True): + var = self.vars[vr] + if isinstance(var, String): + var.setter(value) + else: + raise TypeError(f"Variable with valueReference={vr} is not of type String!") + + def _get_fmu_state(self) -> dict[str, Any]: + return {var.name : var.getter() for var in self.vars.values()} + + def _set_fmu_state(self, state: dict[str, Any]) -> None: + vars_by_name = {v.name : v for v in self.vars.values()} + for name, value in state.items(): + if name not in vars_by_name: + setattr(self, name, value) + else: + v = vars_by_name[name] + if v.setter is not None: + v.setter(value) + + def get_number_of_event_indicators(self) -> int: + return len(self.event_indicators) + + def set_continuous_states(self, values: list[float]) -> None: + offset = 0 + continuous_state_derivatives = list( + filter( + lambda v: ( + v.variability == Fmi3Variability.continuous + and (isinstance(v, Float64) and v.derivative is not None) + ), + self.vars.values(), + ) + ) + + vrs = [v.derivative for v in continuous_state_derivatives] + + for vr in vrs: + var = self.vars[vr] + size = var.size(self.vars) + if size > 1: + var.setter(values[offset : offset + size]) + else: + var.setter(values[offset]) + offset += size + + def get_continuous_states(self) -> list[float]: + continuous_state_derivatives = list( + filter( + lambda v: ( + v.variability == Fmi3Variability.continuous + and (isinstance(v, Float64) and v.derivative is not None) + ), + self.vars.values(), + ) + ) + + vrs = [v.derivative for v in continuous_state_derivatives] + + refs : list[Any] = [] + for vr in vrs: + var = self.vars[vr] + if len(var.dimensions) == 0: + refs.append(float(var.getter())) + else: + refs.extend(var.getter()) + + return refs + + def get_number_of_continuous_states(self) -> int: + continuous_state_derivatives = list( + filter( + lambda v: ( + v.variability == Fmi3Variability.continuous + and (isinstance(v, Float64) and v.derivative is not None) + ), + self.vars.values(), + ) + ) + return len(continuous_state_derivatives) + + def set_time(self, time: float)->None: + self.time = time + + @staticmethod + def _fmu_state_to_bytes(state: dict[str, Any]) -> bytes: + return json.dumps(state).encode("utf-8") + + @staticmethod + def _fmu_state_from_bytes(state: bytes) -> dict[str, Any]: + return json.loads(state.decode("utf-8")) + + def _get_log_queue(self) -> list[LogMsg]: + return self.log_queue + + def log( + self, + msg: str, + status: Fmi3Status = Fmi3Status.ok, + category: str | None = None, + *, + debug: bool = False, + )->None: + """Log a message to the FMU logger. + + Args: + msg (str) : Log message + status (Fmi3Status) : Optional, message status (default ok) + category (str or None) : Optional, message category (default derived from status) + debug (bool) : Optional, is this a debug message (default False) + """ + if category is None: + category = f"logStatus{status.name.capitalize()}" + if category not in Fmi3SlaveBase.log_categories: + category = "logAll" + log_msg = LogMsg(status, category, msg, debug) + self.log_queue.append(log_msg) + + +class Fmi3Slave(Fmi3SlaveBase, CoSimulation): + pass diff --git a/pythonfmu3/logmsg.py b/src/pythonfmu3/logmsg.py similarity index 64% rename from pythonfmu3/logmsg.py rename to src/pythonfmu3/logmsg.py index ad28489..d3151d5 100644 --- a/pythonfmu3/logmsg.py +++ b/src/pythonfmu3/logmsg.py @@ -1,6 +1,4 @@ - class LogMsg: - def __init__(self, status: int, category: str, msg: str, debug: bool): self.status = status self.category = category @@ -8,7 +6,4 @@ def __init__(self, status: int, category: str, msg: str, debug: bool): self.debug = debug def __str__(self) -> str: - return "LogMsg(status={}, category={}, msg={}, debug={}".format(self.status, self.category, self.msg, self.debug) - - - + return f"LogMsg(status={self.status}, category={self.category}, msg={self.msg}, debug={self.debug}" diff --git a/src/pythonfmu3/model_options.py b/src/pythonfmu3/model_options.py new file mode 100644 index 0000000..85506b6 --- /dev/null +++ b/src/pythonfmu3/model_options.py @@ -0,0 +1,73 @@ +"""Contains modelOptions for both CoSimulation and ModelExchange, defined as dataclass. +These are included in several modules and should therefore be defined separately +""" + +from dataclasses import dataclass, fields + + +# Note: all Bool options are false by default and the name expresses the option as True. +# The cli uses therefore the original name to add the option as implicit True (non-default) +# other options are added with their (non-default) numbers +@dataclass(kw_only=True, frozen=True, slots=True) +class Fmi3ModelOptionsCommon: + """Model options common for Co-Simulation and Model Exchange.""" + + needsExecutionTool: bool = False + canBeInstantiatedOnlyOncePerProcess: bool = False + canGetAndSetFMUState: bool = False + canSerializeFMUState: bool = False + providesDirectionalDerivatives: bool = False + providesAdjointDerivatives: bool = False + providesPerElementDependencies: bool = False + providesEvaluateDiscreteStates: bool = False + + def to_dict(self, *, w_default: bool = True, w_none: bool = True): + """A special version of 'asdict', which also allows for choice what to include. + Note: self.do_dict() == asdict(self) if the default value is None. + + Args: + w_defaults: include also the elements with default value + w_none: include also elements with a 'None' value + """ + dct: dict[str, bool | int | float] = {} + for _f in fields(self): + value = getattr(self, _f.name) + if ( + (value is not None and value != _f.default) + or (value is not None and value == _f.default and w_default) + or (value is None and value == _f.default and w_default and w_none) + or (value is None and value != _f.default and w_none) + ): + dct.update({_f.name: value}) + return dct + + def __getitem__(self, key:str): + """Get one of the dataclass elements through a str key.""" + if not hasattr(self, key): + raise KeyError(f"dataclass {self} has no element {key}") from None + return getattr(self,key) + +@dataclass(kw_only=True, frozen=True, slots=True) +class Fmi3ModelOptionsCS(Fmi3ModelOptionsCommon): + """Model options for Co-Simulation. + + Note: This uses non-standard Python names, because they are transferred to the ModelDescription + If users prefer, the options can be instantiated with a dict: Fmi3ModelOptionsCS(**{...}) + and can be used with the __getitem__ method - both as str. + """ + + canHandleVariableCommunicationStepSize: bool = False + fixedInternalStepSize: float | None = None + maxOutputDerivativeOrder: int = 0 # uInt + recommendedIntermediateInputSmoothness: int = 0 + providesIntermediateUpdate: bool = False + mightReturnEarlyFromDoStep: bool = False + canReturnEarlyAfterIntermediateUpdate: bool = False + hasEventMode: bool = False + + +@dataclass(kw_only=True, frozen=True, slots=True) +class Fmi3ModelOptionsME(Fmi3ModelOptionsCommon): + """Model options for Model Exchange.""" + + needsCompletedIntegratorStep: bool = False diff --git a/src/pythonfmu3/model_returns.py b/src/pythonfmu3/model_returns.py new file mode 100644 index 0000000..c654a74 --- /dev/null +++ b/src/pythonfmu3/model_returns.py @@ -0,0 +1,40 @@ +"""Contains model return classes for both CoSimulation and ModelExchange, +i.e. FMI3 function returns as NamedTuple +Defined selarately, so that they can be imported where needed. +""" + +from typing import NamedTuple + + +class Fmi3StepResult(NamedTuple): + """Signal the results from do_step to the orchestrator. + + Returns + eventHandingNeeded: True; the orchestrator must swithc to event mode. + terminateSimulation: True; the FMU requests to stop the simulation. + earlyReturn: True; the FMU singals that it returned early (step not fully done) + lastSuccessfullTime: If earlyReturn=True, provide the time until which the step was performed. + """ + eventHandlingNeeded: bool = False + terminateSimulation: bool = False + earlyReturn: bool = False + lastSuccessfullTime: "Float64" = 0.0 + +class Fmi3UpdateDiscreteStatesResult(NamedTuple): + """Signal the results from update_discrete_events to the orchestrator. + + Returns: + discreteStatesNeedUpdate: True; the Orchestrator must stay in Event Mode for another event iteration, + starting a new super-dense time instant. Never only return 'True' since it leads to an infinite loop! + terminateSimulation: True; the FMU requests to stop the simulation. + nominalsOfContinuousStatesChanged: True; use only for ME! + valuesOfContinuousStatesChanged: False; use only for configuration changes + nextEventTimeDefined: True; the next time event is known and nextEventTime has a valid value. + nextEventTime: contains the absolute time of the next time event if nextEventTimeDefined = True. + """ + discreteStatesNeedUpdate: bool = False + terminateSimulation: bool = False + nominalContinuousStatesChanged: bool = False # (only ME) + valuesOfContinuousStatesChanged: bool = False + nextEventTimeDefined: bool = False + nextEventTime: float = 0.0 diff --git a/pythonfmu3/modelexchange.py b/src/pythonfmu3/modelexchange.py similarity index 76% rename from pythonfmu3/modelexchange.py rename to src/pythonfmu3/modelexchange.py index 7848b24..428ef2a 100644 --- a/pythonfmu3/modelexchange.py +++ b/src/pythonfmu3/modelexchange.py @@ -1,23 +1,18 @@ from abc import ABC, ABCMeta, abstractmethod -from dataclasses import dataclass -@dataclass -class Fmi3UpdateDiscreteStatesResult: - discreteStateNeedsUpdate: bool = False - terminateSimulation: bool = False - nominalsOfContinuousStatesChanged: bool = False - valuesOfContinuousStatesChanged: bool = False - nextEventTimeDefined: bool = False - nextEventTime: float = 0.0 +from pythonfmu3.model_returns import Fmi3UpdateDiscreteStatesResult + class RequireTimeMeta(ABCMeta): def __init__(cls, name, bases, namespace): super().__init__(name, bases, namespace) orig_init = cls.__init__ + def new_init(self, *args, **kwargs): orig_init(self, *args, **kwargs) - if not hasattr(self, 'time'): + if not hasattr(self, "time"): raise AttributeError(f"{cls.__name__} must define 'self.time' in __init__") + cls.__init__ = new_init @@ -25,7 +20,7 @@ def new_init(self, *args, **kwargs): class ModelExchange(ABC, metaclass=RequireTimeMeta): """ Classes derived from ModelExchange must define a 'self.time' member variable. - + Required methods to override: - `get_continuous_state_derivatives`: Must return a list of continuous state derivatives. @@ -33,20 +28,19 @@ class ModelExchange(ABC, metaclass=RequireTimeMeta): - `get_event_indicators`: Should return a list of event indicators. - `update_discrete_states`: Signify converged solution at current super-dense time instant. """ - + @abstractmethod def get_continuous_state_derivatives(self): """Return the continuous state derivatives of the model.""" - pass - + def get_event_indicators(self): """Return the event indicators of the model.""" return [] - + def update_discrete_states(self): """Update the discrete states of the model.""" return Fmi3UpdateDiscreteStatesResult() def get_nominals_of_continuous_states(self, size: int) -> list[float]: """Return the nominal values of the continuous states.""" - return [1.0] * size \ No newline at end of file + return [1.0] * size diff --git a/pythonfmu3/osutil.py b/src/pythonfmu3/osutil.py similarity index 92% rename from pythonfmu3/osutil.py rename to src/pythonfmu3/osutil.py index 568350e..81fb6f3 100644 --- a/pythonfmu3/osutil.py +++ b/src/pythonfmu3/osutil.py @@ -1,15 +1,15 @@ -import sys - import platform + def get_fmu_arch(): - #is_64bits = sys.maxsize > 2 ** 32 + # is_64bits = sys.maxsize > 2 ** 32 system = platform.system() is_x86 = platform.machine() in ["i386", "AMD64", "x86_64"] platforms = {"Windows": "windows", "Linux": "linux", "Darwin": "darwin"} arch = "x86_64" if is_x86 else "x86" return arch + "-" + platforms.get(system, "unknown") + def get_platform() -> str: """Get FMU binary platform folder name.""" return get_fmu_arch() @@ -19,4 +19,3 @@ def get_lib_extension() -> str: """Get FMU library platform extension.""" platforms = {"Darwin": "dylib", "Linux": "so", "Windows": "dll"} return platforms.get(platform.system(), "") - diff --git a/pythonfmu3/pythonfmu-export/.clang-format b/src/pythonfmu3/pythonfmu-export/.clang-format similarity index 100% rename from pythonfmu3/pythonfmu-export/.clang-format rename to src/pythonfmu3/pythonfmu-export/.clang-format diff --git a/pythonfmu3/pythonfmu-export/CMakeLists.txt b/src/pythonfmu3/pythonfmu-export/CMakeLists.txt similarity index 100% rename from pythonfmu3/pythonfmu-export/CMakeLists.txt rename to src/pythonfmu3/pythonfmu-export/CMakeLists.txt diff --git a/pythonfmu3/pythonfmu-export/build_unix.sh b/src/pythonfmu3/pythonfmu-export/build_unix.sh old mode 100755 new mode 100644 similarity index 100% rename from pythonfmu3/pythonfmu-export/build_unix.sh rename to src/pythonfmu3/pythonfmu-export/build_unix.sh diff --git a/pythonfmu3/pythonfmu-export/build_win.sh b/src/pythonfmu3/pythonfmu-export/build_win.bat similarity index 100% rename from pythonfmu3/pythonfmu-export/build_win.sh rename to src/pythonfmu3/pythonfmu-export/build_win.bat diff --git a/src/pythonfmu3/pythonfmu-export/build_win.sh b/src/pythonfmu3/pythonfmu-export/build_win.sh new file mode 100644 index 0000000..888c8f2 --- /dev/null +++ b/src/pythonfmu3/pythonfmu-export/build_win.sh @@ -0,0 +1,4 @@ +mkdir build +cd build +cmake .. -DCMAKE_BUILD_TYPE=Release -A x64 +cmake --build . --config Release diff --git a/pythonfmu3/pythonfmu-export/src/CMakeLists.txt b/src/pythonfmu3/pythonfmu-export/src/CMakeLists.txt similarity index 100% rename from pythonfmu3/pythonfmu-export/src/CMakeLists.txt rename to src/pythonfmu3/pythonfmu-export/src/CMakeLists.txt diff --git a/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_common.hpp b/src/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_common.hpp similarity index 93% rename from pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_common.hpp rename to src/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_common.hpp index 4855b3f..aa4e8ba 100644 --- a/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_common.hpp +++ b/src/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_common.hpp @@ -40,11 +40,13 @@ typedef fmi3Int64 FMIInt64; typedef fmi3UInt64 FMIUInt64; typedef fmi3Boolean FMIBoolean; typedef fmi3String FMIString; +typedef fmi3Clock FMIClock; typedef fmi3LogMessageCallback FMICallbackLogger; typedef fmi3Instance FMIComponent; typedef fmi3InstanceEnvironment FMIComponentEnvironment; typedef fmi3Status FMIStatus; typedef fmi3ValueReference FMIValueReference; +typedef fmi3IntervalQualifier FMIIntervalQualifier; const FMIBoolean FMIFalse = fmi3False; const FMIBoolean FMITrue = fmi3True; @@ -55,6 +57,10 @@ const FMIStatus FMIDiscard = fmi3Discard; const FMIStatus FMIError = fmi3Error; const FMIStatus FMIFatal = fmi3Fatal; +const FMIIntervalQualifier FMIIntervalNotYetKnown = fmi3IntervalNotYetKnown; +const FMIIntervalQualifier FMIIntervalUnchanged = fmi3IntervalUnchanged; +const FMIIntervalQualifier FMIIntervalChanged = fmi3IntervalChanged; + using String = std::string; diff --git a/src/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_cs.cpp b/src/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_cs.cpp new file mode 100644 index 0000000..4cae4cc --- /dev/null +++ b/src/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_cs.cpp @@ -0,0 +1,332 @@ +/* Copyright 2016-2019, SINTEF Ocean. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#include "cppfmu/cppfmu_cs.hpp" + +#include + + +namespace cppfmu +{ + +// ============================================================================= +// SlaveInstance +// ============================================================================= + + +/* not defined in FMI3. Changed EnterInitializationMode takes this role! +void SlaveInstance::SetupExperiment( + FMIBoolean, //toleranceDefined, + FMIFloat64, //tolerance + FMIFloat64, //tStart + FMIBoolean, //stopTimeDefined + FMIFloat64, //tStop + ) +{ + // Do nothing +} +*/ + +void SlaveInstance::EnterInitializationMode( + FMIBoolean, //toleranceDefined, + FMIFloat64, //tolerance + FMIFloat64, //tStart + FMIBoolean, //stopTimeDefined + FMIFloat64 //stopTime + ) +{ + // Do nothing +} + +void SlaveInstance::ExitInitializationMode() +{ + // Do nothing +} + + +void SlaveInstance::Terminate() +{ + // Do nothing +} + + +void SlaveInstance::Reset() +{ + // Do nothing +} + +void SlaveInstance::SetFloat64( + const FMIValueReference /*vr*/[], + std::size_t nvr, + const FMIFloat64 /*value*/[], + std::size_t nValues) +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} + +void SlaveInstance::SetInt32( + const FMIValueReference /*vr*/[], + std::size_t nvr, + const FMIInt32 /*value*/[], + std::size_t nValues) +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} + +void SlaveInstance::SetInt64( + const FMIValueReference /*vr*/[], + std::size_t nvr, + const FMIInt64 /*value*/[], + std::size_t nValues) +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} + +void SlaveInstance::SetUInt64( + const FMIValueReference /*vr*/[], + std::size_t nvr, + const FMIUInt64 /*value*/[], + std::size_t nValues) +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} + +void SlaveInstance::SetBoolean( + const FMIValueReference /*vr*/[], + std::size_t nvr, + const FMIBoolean /*value*/[], + std::size_t nValues) +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} + +void SlaveInstance::SetString( + const FMIValueReference /*vr*/[], + std::size_t nvr, + const FMIString /*value*/[], + std::size_t nValues) +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} + + +void SlaveInstance::GetFloat64( + const FMIValueReference /*vr*/[], + std::size_t nvr, + FMIFloat64 /*value*/[], + std::size_t nValues) const +{ + if (nvr != 0) { + throw std::logic_error("Attempted to get nonexistent variable"); + } +} + + +void SlaveInstance::GetInt32( + const FMIValueReference /*vr*/[], + std::size_t nvr, + FMIInt32 /*value*/[], + std::size_t nValues) const +{ + if (nvr != 0) { + throw std::logic_error("Attempted to get nonexistent variable"); + } +} + + +void SlaveInstance::GetInt64( + const FMIValueReference /*vr*/[], + std::size_t nvr, + FMIInt64 /*value*/[], + std::size_t nValues) const +{ + if (nvr != 0) { + throw std::logic_error("Attempted to get nonexistent variable"); + } +} + + +void SlaveInstance::GetUInt64( + const FMIValueReference /*vr*/[], + std::size_t nvr, + FMIUInt64 /*value*/[], + std::size_t nValues) const +{ + if (nvr != 0) { + throw std::logic_error("Attempted to get nonexistent variable"); + } +} + + +void SlaveInstance::GetBoolean( + const FMIValueReference /*vr*/[], + std::size_t nvr, + FMIBoolean /*value*/[], + std::size_t nValues) const +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} + + +void SlaveInstance::GetString( + const FMIValueReference /*vr*/[], + std::size_t nvr, + FMIString /*value*/[], + std::size_t nValues) const +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} + +void SlaveInstance::DoStep( + FMIFloat64 currentCommunicationPoint, + FMIFloat64 communicationStepSize, + FMIBoolean noSetFMUStatePriorToCurrentPoint, + FMIBoolean* eventHandlingNeeded, + FMIBoolean* terminateSimulation, + FMIBoolean* earlyReturn, + FMIFloat64* lastSuccessfullTime) +{ + // Do nothing +} + +// Event- and Clock-related functions +void SlaveInstance::EnterEventMode() +{ + // Do nothing +} +void SlaveInstance::EnterStepMode() +{ + // Do nothing +} +void SlaveInstance::EnterContinuousTimeMode() +{ + + // Do nothing +} +void SlaveInstance::CompletedIntegratorStep( + fmi3Boolean noSetFMUStatePriorToCurrentPoint, + fmi3Boolean* enterEventMode, + fmi3Boolean* terminateSimulation) +{ + // Do nothing +} +/*void SlaveInstance::UpdateDiscreteStates( + cppfmu::FMIBoolean* discreteStatesNeedUpdate, + cppfmu::FMIBoolean* terminateSimulation, + cppfmu::FMIBoolean* nominalContinuousStatesChanged, + cppfmu::FMIBoolean* valuesOfContinuousStatesChanged, + cppfmu::FMIBoolean* nextEventTimeDefined, + cppfmu::FMIFloat64* nextEventTime) +{ + // Do nothing +} +*/ +void SlaveInstance::GetClock( const FMIValueReference /*vr*/[], std::size_t nvr, FMIClock /*values*/[]) const +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} +void SlaveInstance::SetClock( const FMIValueReference /*vr*/[], std::size_t nvr, const FMIClock /*values*/[]) +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} +void SlaveInstance::GetIntervalDecimal( + const FMIValueReference /*vr*/[], + std::size_t nvr, + FMIFloat64 /*intervals*/[], + FMIIntervalQualifier /*qualifiers*/[]) const +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} +void SlaveInstance::SetIntervalDecimal(const FMIValueReference /*vr*/[], std::size_t nvr, const FMIFloat64 /*intervals*/[]) +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} +void SlaveInstance::GetShiftDecimal( const FMIValueReference /*vr*/[], std::size_t nvr, FMIFloat64 /*shifts*/[]) const +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} +void SlaveInstance::SetShiftDecimal( const FMIValueReference /*vr*/[], std::size_t nvr, const FMIFloat64 /*shifts*/[]) +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} +void SlaveInstance::GetIntervalFraction( + const FMIValueReference /*vr*/[], + std::size_t nvr, + FMIUInt64 /*intervalCounters*/[], + FMIUInt64 /*resolutions*/[], + FMIIntervalQualifier /*qualifiers*/[]) const +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} +void SlaveInstance::SetIntervalFraction( + const FMIValueReference /*vr*/[], + std::size_t nvr, + const FMIUInt64 /*intervalCounters*/[], + const FMIUInt64 /*resolutions*/[]) +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} +void SlaveInstance::GetShiftFraction( + const FMIValueReference /*vr*/[], + std::size_t nvr, + FMIUInt64 /*shiftCounters*/[], + FMIUInt64 /*resolutions*/[]) const +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} +void SlaveInstance::SetShiftFraction( + const FMIValueReference /*vr*/[], + std::size_t nvr, + const FMIUInt64 /*shiftCounters*/[], + const FMIUInt64 /*resolutions*/[]) +{ + if (nvr != 0) { + throw std::logic_error("Attempted to set nonexistent variable"); + } +} + + + +SlaveInstance::~SlaveInstance() CPPFMU_NOEXCEPT +{ + // Do nothing +} + + +} // namespace cppfmu diff --git a/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_cs.hpp b/src/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_cs.hpp similarity index 75% rename from pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_cs.hpp rename to src/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_cs.hpp index 61bc2cb..e8b2833 100644 --- a/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_cs.hpp +++ b/src/pythonfmu3/pythonfmu-export/src/cppfmu/cppfmu_cs.hpp @@ -36,6 +36,7 @@ class SlaveInstance * (FMI 1.0). * Does nothing by default. */ + /* not in FMI3: virtual void SetupExperiment( FMIBoolean toleranceDefined, FMIFloat64 tolerance, @@ -43,14 +44,18 @@ class SlaveInstance FMIBoolean stopTimeDefined, FMIFloat64 tStop); - /* Called from fmi3EnterInitializationMode() (FMI 2.0) or + * Called from fmi3EnterInitializationMode() (FMI 2.0) or * fmiInitializeSlave() (FMI 1.0). * Does nothing by default. */ - virtual void EnterInitializationMode(); + virtual void EnterInitializationMode( + FMIBoolean toleranceDefined, + FMIFloat64 tolerance, + FMIFloat64 tStart, + FMIBoolean stopTimeDefined, + FMIFloat64 stopTime); - /* Called from fmi3ExitInitializationMode() (FMI 2.0) or - * fmiInitializeSlave() (FMI 1.0). + /* Changed signature in FMI3! * Does nothing by default. */ virtual void ExitInitializationMode(); @@ -134,14 +139,54 @@ class SlaveInstance std::size_t nValues) const; // Called from fmi3DoStep()/fmiDoStep(). Must be implemented in model code. - virtual FMIStatus DoStep( + virtual void DoStep( FMIFloat64 currentCommunicationPoint, FMIFloat64 communicationStepSize, - FMIBoolean newStep, + FMIBoolean noSetFMUStatePriorToCurrentPoint, FMIBoolean* eventHandlingNeeded, FMIBoolean* terminateSimulation, FMIBoolean* earlyReturn, - FMIFloat64& endOfStep) = 0; + FMIFloat64* lastSuccessfullTime); + + // Event- and Clock-related functions + virtual void EnterEventMode(); + virtual void EnterContinuousTimeMode(); + virtual void CompletedIntegratorStep( + fmi3Boolean noSetFMUStatePriorToCurrentPoint, + fmi3Boolean* enterEventMode, + fmi3Boolean* terminateSimulation); + virtual void EnterStepMode(); + virtual void GetClock( const FMIValueReference vr[], std::size_t nvr, FMIClock values[]) const; + virtual void SetClock( const FMIValueReference vr[], std::size_t nvr, const FMIClock values[]); + virtual void GetIntervalDecimal( + const FMIValueReference vr[], + std::size_t nvr, + FMIFloat64 intervals[], + FMIIntervalQualifier qualifiers[]) const; + virtual void SetIntervalDecimal(const FMIValueReference vr[], std::size_t nvr, const FMIFloat64 intervals[]); + virtual void GetShiftDecimal( const FMIValueReference vr[], std::size_t nvr, FMIFloat64 shifts[]) const; + virtual void SetShiftDecimal( const FMIValueReference vr[], std::size_t nvr, const FMIFloat64 shifts[]); + virtual void GetIntervalFraction( + const FMIValueReference vr[], + std::size_t nvr, + FMIUInt64 intervalCounters[], + FMIUInt64 resolutions[], + FMIIntervalQualifier qualifiers[]) const; + virtual void SetIntervalFraction( + const FMIValueReference vr[], + std::size_t nvr, + const FMIUInt64 intervalCounters[], + const FMIUInt64 resolutions[]); + virtual void GetShiftFraction( + const FMIValueReference vr[], + std::size_t nvr, + FMIUInt64 shiftCounters[], + FMIUInt64 resolutions[]) const; + virtual void SetShiftFraction( + const FMIValueReference vr[], + std::size_t nvr, + const FMIUInt64 shiftCounters[], + const FMIUInt64 resolutions[]); // Model Exchange methods virtual void GetContinuousStates(cppfmu::FMIFloat64* continuousStates, std::size_t nStates) const = 0; @@ -159,7 +204,7 @@ class SlaveInstance cppfmu::FMIBoolean* valuesOfContinuousStatesChanged, cppfmu::FMIBoolean* nextEventTimeDefined, cppfmu::FMIFloat64* nextEventTime) = 0; - + virtual void GetFMUstate(fmi3FMUState& state) = 0; virtual void SetFMUstate(const fmi3FMUState& state) = 0; @@ -207,7 +252,9 @@ std::unique_ptr CppfmuInstantiateSlave( cppfmu::FMIFloat64 timeout, cppfmu::FMIBoolean visible, cppfmu::FMIBoolean interactive, - const cppfmu::Logger& logger); - + const cppfmu::Logger& logger, + cppfmu::FMIBoolean eventModeUsed, + cppfmu::FMIBoolean earlyReturnAllowed + ); #endif // header guard diff --git a/pythonfmu3/pythonfmu-export/src/cppfmu/fmi_functions.cpp b/src/pythonfmu3/pythonfmu-export/src/cppfmu/fmi_functions.cpp similarity index 78% rename from pythonfmu3/pythonfmu-export/src/cppfmu/fmi_functions.cpp rename to src/pythonfmu3/pythonfmu-export/src/cppfmu/fmi_functions.cpp index 6cd61d4..5b127d8 100644 --- a/pythonfmu3/pythonfmu-export/src/cppfmu/fmi_functions.cpp +++ b/src/pythonfmu3/pythonfmu-export/src/cppfmu/fmi_functions.cpp @@ -7,6 +7,8 @@ #include #include +#include + #define NOT_IMPLEMENTED throw std::logic_error("function " + std::string(__func__) + " not implemented") @@ -16,14 +18,14 @@ const fmi3ValueReference vr[], \ size_t nValueReferences, \ var values[], \ - size_t nValues) { NOT_IMPLEMENTED;} + size_t nValues) { NOT_IMPLEMENTED;} #define NOT_IMPLEMENTED_SETTER(suffix, var) fmi3Status fmi3Set##suffix ( \ fmi3Instance c, \ const fmi3ValueReference vr[], \ size_t nValueReferences, \ const var values[], \ - size_t nValues) { NOT_IMPLEMENTED;} + size_t nValues) { NOT_IMPLEMENTED;} namespace { @@ -103,11 +105,13 @@ fmi3Instance fmi3InstantiateCoSimulation( instanceName, instantiationToken, fmuResourceLocation, - "application/x-fmu-sharedlibrary", - 0.0, + "application/x-fmu-sharedlibrary", // mimeType + 0.0, // timeout visible, - cppfmu::FMIFalse, - component->logger); + cppfmu::FMIFalse, // interactive + component->logger, + eventModeUsed, + earlyReturnAllowed); return component; } catch (const cppfmu::FatalError& e) { if (logMessage) @@ -146,7 +150,9 @@ fmi3Instance fmi3InstantiateModelExchange( 0.0, visible, cppfmu::FMIFalse, - component->logger); + component->logger, + cppfmu::FMIFalse, // dummy added for compatibility with CoSimulation + cppfmu::FMIFalse); // dummy added for compatibility with CoSimulation return component; } catch (const cppfmu::FatalError& e) { if (logMessage) @@ -205,11 +211,17 @@ fmi3Status fmi3SetDebugLogging( return fmi3OK; } -fmi3Status fmi3EnterInitializationMode(fmi3Instance c, fmi3Boolean, fmi3Float64, fmi3Float64, fmi3Boolean, fmi3Float64) +fmi3Status fmi3EnterInitializationMode(fmi3Instance c, + fmi3Boolean toleranceDefined, + fmi3Float64 tolerance, + fmi3Float64 startTime, + fmi3Boolean stopTimeDefined, + fmi3Float64 stopTime + ) { const auto component = reinterpret_cast(c); try { - component->slave->EnterInitializationMode(); + component->slave->EnterInitializationMode(toleranceDefined, tolerance, startTime, stopTimeDefined, stopTime); return fmi3OK; } catch (const cppfmu::FatalError& e) { component->logger.Log(fmi3Fatal, "", e.what()); @@ -238,7 +250,7 @@ fmi3Status fmi3ExitInitializationMode(fmi3Instance c) fmi3Status fmi3EnterConfigurationMode(fmi3Instance c) { - + const auto component = reinterpret_cast(c); component->state = Component::State::ConfigurationMode; return fmi3OK; @@ -554,7 +566,7 @@ fmi3Status fmi3GetContinuousStates( auto component = reinterpret_cast(c); try { component->slave->GetContinuousStates(continuousStates, nStates); - return fmi3OK; + return fmi3OK; } catch (const cppfmu::FatalError& e) { component->logger.Log(fmi3Fatal, "", e.what()); return fmi3Fatal; @@ -643,7 +655,7 @@ fmi3Status fmi3GetNominalsOfContinuousStates( const auto component = reinterpret_cast(c); try { component->slave->GetNominalsOfContinuousStates(nominalContinuousStates, nStates); - return fmi3OK; + return fmi3OK; } catch (const cppfmu::FatalError& e) { component->logger.Log(fmi3Fatal, "", e.what()); return fmi3Fatal; @@ -654,7 +666,7 @@ fmi3Status fmi3GetNominalsOfContinuousStates( } fmi3Status fmi3GetNumberOfContinuousStates( - fmi3Instance c, + fmi3Instance c, std::size_t * nContinuousStates) { const auto component = reinterpret_cast(c); @@ -671,7 +683,7 @@ fmi3Status fmi3GetNumberOfContinuousStates( } fmi3Status fmi3GetNumberOfEventIndicators( - fmi3Instance c, + fmi3Instance c, std::size_t * nEventIndicators) { const auto component = reinterpret_cast(c); @@ -717,6 +729,8 @@ fmi3Status fmi3UpdateDiscreteStates(fmi3Instance c, fmi3Status fmi3EnterContinuousTimeMode(fmi3Instance c) { + const auto component = reinterpret_cast(c); + component->state = Component::State::ContinuousTimeMode; return fmi3OK; } @@ -726,9 +740,21 @@ fmi3Status fmi3CompletedIntegratorStep( fmi3Boolean* enterEventMode, fmi3Boolean* terminateSimulation) { - *enterEventMode = false; - *terminateSimulation = false; - + const auto component = reinterpret_cast(c); + try { + component->slave->CompletedIntegratorStep( + noSetFMUStatePriorToCurrentPoint, + enterEventMode, + terminateSimulation); + return fmi3OK; + } catch (const cppfmu::FatalError& e) { + component->logger.Log(fmi3Fatal, "", e.what()); + return fmi3Fatal; + } catch (const std::exception& e) { + component->logger.Log(fmi3Error, "", e.what()); + return fmi3Error; + } + return fmi3OK; } @@ -883,7 +909,22 @@ fmi3Status fmi3DoStep( fmi3Boolean* eventHandlingNeeded , fmi3Boolean* terminateSimulation, fmi3Boolean* earlyReturn, - fmi3Float64* lastSuccessfulTime) + fmi3Float64* lastSuccessfullTime) +{ + const auto component = reinterpret_cast(c); + try { + component->slave->DoStep( + currentCommunicationPoint, + communicationStepSize, + noSetFmuStatePriorToCurrentPoint, + eventHandlingNeeded, + terminateSimulation, + earlyReturn, + lastSuccessfullTime); + + return fmi3OK; +/* Changed that back to the original definition leaving the logic to the components + fmi3Float64* lastSuccessfulTime) { const auto component = reinterpret_cast(c); try { @@ -903,7 +944,7 @@ fmi3Status fmi3DoStep( } else { *lastSuccessfulTime = endTime; return status; - } + }*/ } catch (const cppfmu::FatalError& e) { component->logger.Log(fmi3Fatal, "", e.what()); return fmi3Fatal; @@ -912,8 +953,200 @@ fmi3Status fmi3DoStep( return fmi3Error; } } + +// Clock-related functions + +fmi3Status fmi3GetClock( + fmi3Instance c, + const fmi3ValueReference vr[], + size_t nvr, + fmi3Clock values[]) +{ + const auto component = reinterpret_cast(c); + try { + component->slave->GetClock(vr, nvr, values); + return fmi3OK; + } catch (const cppfmu::FatalError& e) { + component->logger.Log(fmi3Fatal, "", e.what()); + return fmi3Fatal; + } catch (const std::exception& e) { + component->logger.Log(fmi3Error, "", e.what()); + return fmi3Error; + } +} + +} +fmi3Status fmi3SetClock( + fmi3Instance c, + const fmi3ValueReference vr[], + size_t nvr, + const fmi3Clock values[]) +{ + const auto component = reinterpret_cast(c); + try { + component->slave->SetClock(vr, nvr, values); + return fmi3OK; + } catch (const cppfmu::FatalError& e) { + component->logger.Log(fmi3Fatal, "", e.what()); + return fmi3Fatal; + } catch (const std::exception& e) { + component->logger.Log(fmi3Error, "", e.what()); + return fmi3Error; + } } +fmi3Status fmi3GetIntervalDecimal( + fmi3Instance c, + const fmi3ValueReference vr[], + size_t nvr, + fmi3Float64 intervals[], + fmi3IntervalQualifier qualifiers[]) +{ + const auto component = reinterpret_cast(c); + try { + component->slave->GetIntervalDecimal(vr, nvr, intervals, qualifiers); + return fmi3OK; + } catch (const cppfmu::FatalError& e) { + component->logger.Log(fmi3Fatal, "", e.what()); + return fmi3Fatal; + } catch (const std::exception& e) { + component->logger.Log(fmi3Error, "", e.what()); + return fmi3Error; + } +} +fmi3Status fmi3SetIntervalDecimal( + fmi3Instance c, + const fmi3ValueReference vr[], + size_t nvr, + const fmi3Float64 intervals[]) +{ + const auto component = reinterpret_cast(c); + try { + component->slave->SetIntervalDecimal(vr, nvr, intervals); + return fmi3OK; + } catch (const cppfmu::FatalError& e) { + component->logger.Log(fmi3Fatal, "", e.what()); + return fmi3Fatal; + } catch (const std::exception& e) { + component->logger.Log(fmi3Error, "", e.what()); + return fmi3Error; + } +} +fmi3Status fmi3GetShiftDecimal( + fmi3Instance c, + const fmi3ValueReference vr[], + size_t nvr, + fmi3Float64 shifts[]) +{ + const auto component = reinterpret_cast(c); + try { + component->slave->GetShiftDecimal(vr, nvr, shifts); + return fmi3OK; + } catch (const cppfmu::FatalError& e) { + component->logger.Log(fmi3Fatal, "", e.what()); + return fmi3Fatal; + } catch (const std::exception& e) { + component->logger.Log(fmi3Error, "", e.what()); + return fmi3Error; + } +} +fmi3Status fmi3SetShiftDecimal( + fmi3Instance c, + const fmi3ValueReference vr[], + size_t nvr, + const fmi3Float64 shifts[]) +{ + const auto component = reinterpret_cast(c); + try { + component->slave->SetShiftDecimal(vr, nvr, shifts); + return fmi3OK; + } catch (const cppfmu::FatalError& e) { + component->logger.Log(fmi3Fatal, "", e.what()); + return fmi3Fatal; + } catch (const std::exception& e) { + component->logger.Log(fmi3Error, "", e.what()); + return fmi3Error; + } +} +fmi3Status fmi3GetIntervalFraction( + fmi3Instance c, + const fmi3ValueReference vr[], + size_t nvr, + fmi3UInt64 intervalCounters[], + fmi3UInt64 resolutions[], + fmi3IntervalQualifier qualifiers[]) +{ + const auto component = reinterpret_cast(c); + try { + component->slave->GetIntervalFraction(vr, nvr, intervalCounters, resolutions, qualifiers); + return fmi3OK; + } catch (const cppfmu::FatalError& e) { + component->logger.Log(fmi3Fatal, "", e.what()); + return fmi3Fatal; + } catch (const std::exception& e) { + component->logger.Log(fmi3Error, "", e.what()); + return fmi3Error; + } +} +fmi3Status fmi3SetIntervalFraction( + fmi3Instance c, + const fmi3ValueReference vr[], + size_t nvr, + const fmi3UInt64 intervalCounters[], + const fmi3UInt64 resolutions[]) +{ + const auto component = reinterpret_cast(c); + try { + component->slave->SetIntervalFraction(vr, nvr, intervalCounters, resolutions); + return fmi3OK; + } catch (const cppfmu::FatalError& e) { + component->logger.Log(fmi3Fatal, "", e.what()); + return fmi3Fatal; + } catch (const std::exception& e) { + component->logger.Log(fmi3Error, "", e.what()); + return fmi3Error; + } +} + +fmi3Status fmi3GetShiftFraction( + fmi3Instance c, + const fmi3ValueReference vr[], + size_t nvr, + fmi3UInt64 shiftCounters[], + fmi3UInt64 resolutions[]) +{ + const auto component = reinterpret_cast(c); + try { + component->slave->GetShiftFraction(vr, nvr, shiftCounters, resolutions); + return fmi3OK; + } catch (const cppfmu::FatalError& e) { + component->logger.Log(fmi3Fatal, "", e.what()); + return fmi3Fatal; + } catch (const std::exception& e) { + component->logger.Log(fmi3Error, "", e.what()); + return fmi3Error; + } +} + +fmi3Status fmi3SetShiftFraction( + fmi3Instance c, + const fmi3ValueReference vr[], + size_t nvr, + const fmi3UInt64 shiftCounters[], + const fmi3UInt64 resolutions[]) +{ + const auto component = reinterpret_cast(c); + try { + component->slave->SetShiftFraction(vr, nvr, shiftCounters, resolutions); + return fmi3OK; + } catch (const cppfmu::FatalError& e) { + component->logger.Log(fmi3Fatal, "", e.what()); + return fmi3Fatal; + } catch (const std::exception& e) { + component->logger.Log(fmi3Error, "", e.what()); + return fmi3Error; + } +} // NOT IMPLEMENTED NOT_IMPLEMENTED_GETTER(Float32, fmi3Float32); @@ -932,22 +1165,6 @@ NOT_IMPLEMENTED_GETTER(UInt32, fmi3UInt32); NOT_IMPLEMENTED_SETTER(UInt32, fmi3UInt32); -fmi3Status fmi3GetClock(fmi3Instance instance, - const fmi3ValueReference valueReferences[], - size_t nValueReferences, - fmi3Clock values[]) -{ - NOT_IMPLEMENTED; -} - -fmi3Status fmi3SetClock(fmi3Instance instance, - const fmi3ValueReference valueReferences[], - size_t nValueReferences, - const fmi3Clock values[]) -{ - NOT_IMPLEMENTED; -} - fmi3Status fmi3GetBinary(fmi3Instance instance, const fmi3ValueReference valueReferences[], size_t nValueReferences, @@ -1000,71 +1217,6 @@ fmi3Status fmi3GetAdjointDerivative(fmi3Instance instance, NOT_IMPLEMENTED; } -fmi3Status fmi3GetIntervalDecimal( - fmi3Instance instance, - const fmi3ValueReference valueReferences[], - size_t nValueReferences, - fmi3Float64 intervals[], - fmi3IntervalQualifier qualifiers[]) -{ - NOT_IMPLEMENTED; -} - -fmi3Status fmi3GetIntervalFraction( - fmi3Instance instance, - const fmi3ValueReference valueReferences[], - size_t nValueReferences, - fmi3UInt64 intervalCounters[], - fmi3UInt64 resolutions[], - fmi3IntervalQualifier qualifiers[]) -{ - NOT_IMPLEMENTED; -} - -fmi3Status -fmi3GetShiftDecimal(fmi3Instance instance, const fmi3ValueReference valueReferences[], - size_t nValueReferences, fmi3Float64 shifts[]) -{ - NOT_IMPLEMENTED; -} - -fmi3Status -fmi3GetShiftFraction(fmi3Instance instance, const fmi3ValueReference valueReferences[], - size_t nValueReferences, fmi3UInt64 shiftCounters[], fmi3UInt64 resolutions[]) -{ - NOT_IMPLEMENTED; -} - -fmi3Status -fmi3SetIntervalDecimal(fmi3Instance instance, const fmi3ValueReference valueReferences[], - size_t nValueReferences, const fmi3Float64 intervals[]) -{ - NOT_IMPLEMENTED; -} - -fmi3Status -fmi3SetIntervalFraction(fmi3Instance instance, const fmi3ValueReference valueReferences[], - size_t nValueReferences, const fmi3UInt64 intervalCounters[], - const fmi3UInt64 resolutions[]) -{ - NOT_IMPLEMENTED; -} - -fmi3Status -fmi3SetShiftDecimal(fmi3Instance instance, const fmi3ValueReference valueReferences[], - size_t nValueReferences, const fmi3Float64 shifts[]) -{ - NOT_IMPLEMENTED; -} - -fmi3Status -fmi3SetShiftFraction(fmi3Instance instance, const fmi3ValueReference valueReferences[], - size_t nValueReferences, const fmi3UInt64 shiftCounters[], - const fmi3UInt64 resolutions[]) -{ - NOT_IMPLEMENTED; -} - fmi3Status fmi3EvaluateDiscreteStates(fmi3Instance instance) { diff --git a/pythonfmu3/pythonfmu-export/src/fmi/fmi3FunctionTypes.h b/src/pythonfmu3/pythonfmu-export/src/fmi/fmi3FunctionTypes.h similarity index 100% rename from pythonfmu3/pythonfmu-export/src/fmi/fmi3FunctionTypes.h rename to src/pythonfmu3/pythonfmu-export/src/fmi/fmi3FunctionTypes.h diff --git a/pythonfmu3/pythonfmu-export/src/fmi/fmi3Functions.h b/src/pythonfmu3/pythonfmu-export/src/fmi/fmi3Functions.h similarity index 100% rename from pythonfmu3/pythonfmu-export/src/fmi/fmi3Functions.h rename to src/pythonfmu3/pythonfmu-export/src/fmi/fmi3Functions.h diff --git a/pythonfmu3/pythonfmu-export/src/fmi/fmi3PlatformTypes.h b/src/pythonfmu3/pythonfmu-export/src/fmi/fmi3PlatformTypes.h similarity index 100% rename from pythonfmu3/pythonfmu-export/src/fmi/fmi3PlatformTypes.h rename to src/pythonfmu3/pythonfmu-export/src/fmi/fmi3PlatformTypes.h diff --git a/pythonfmu3/pythonfmu-export/src/pythonfmu/IPyState.hpp b/src/pythonfmu3/pythonfmu-export/src/pythonfmu/IPyState.hpp similarity index 100% rename from pythonfmu3/pythonfmu-export/src/pythonfmu/IPyState.hpp rename to src/pythonfmu3/pythonfmu-export/src/pythonfmu/IPyState.hpp diff --git a/pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.cpp b/src/pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.cpp similarity index 63% rename from pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.cpp rename to src/pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.cpp index 59508be..fe33441 100644 --- a/pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.cpp +++ b/src/pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.cpp @@ -12,6 +12,7 @@ #include #include #include +#include namespace pythonfmu { @@ -46,12 +47,21 @@ inline void py_safe_run(const std::function& f) PyGILState_Release(gil_state); } -PySlaveInstance::PySlaveInstance(std::string instanceName, std::string resources, const cppfmu::Logger& logger, const bool visible, std::shared_ptr pyState) +PySlaveInstance::PySlaveInstance(std::string instanceName, + std::string resources, + const cppfmu::Logger& logger, + const bool visible, + const bool eventModeUsed, + const bool earlyReturnAllowed, + std::shared_ptr pyState + ) : pyState_{ std::move(pyState) } , instanceName_(std::move(instanceName)) , resources_(std::move(resources)) , logger_(logger) , visible_(visible) + , eventModeUsed_(eventModeUsed) + , earlyReturnAllowed_(earlyReturnAllowed) { py_safe_run([this](PyGILState_STATE gilState) { // Append resources path to python sys path @@ -151,11 +161,14 @@ void PySlaveInstance::initialize(PyGILState_STATE gilState) Py_XDECREF(pMessages_); PyObject* args = PyTuple_New(0); - PyObject* kwargs = Py_BuildValue("{ss,ss,sn,si}", - "instance_name", instanceName_.c_str(), + PyObject* kwargs = Py_BuildValue("{ss,ss,sn,si,si,si}", + "instanceName", instanceName_.c_str(), "resources", resources_.c_str(), "logger", &logger_, - "visible", visible_); + "visible", visible_, + "eventModeUsed", eventModeUsed_, + "earlyReturnAllowed", earlyReturnAllowed_ + ); pInstance_ = PyObject_Call(pClass_, args, kwargs); Py_DECREF(args); Py_DECREF(kwargs); @@ -165,10 +178,11 @@ void PySlaveInstance::initialize(PyGILState_STATE gilState) pMessages_ = PyObject_CallMethod(pInstance_, "_get_log_queue", nullptr); } +/* not included in FMI3: void PySlaveInstance::SetupExperiment(cppfmu::FMIBoolean, cppfmu::FMIFloat64, cppfmu::FMIFloat64 startTime, cppfmu::FMIBoolean, cppfmu::FMIFloat64) { py_safe_run([this, startTime](PyGILState_STATE gilState) { - auto f = PyObject_CallMethod(pInstance_, "setup_experiment", "(d)", startTime); + auto f = PyObject_CallMethod(pInstance_, "setupExperiment", "(d)", startTime); if (f == nullptr) { handle_py_exception("[setupExperiment] PyObject_CallMethod", gilState); } @@ -176,11 +190,24 @@ void PySlaveInstance::SetupExperiment(cppfmu::FMIBoolean, cppfmu::FMIFloat64, cp clearLogBuffer(); }); } - -void PySlaveInstance::EnterInitializationMode() + cppfmu::FMIBoolean toleranceDefined, + cppfmu::FMIFloat64 tolerance, + cppfmu::FMIFloat64 tStart, + cppfmu::FMIBoolean stopTimeDefined, + cppfmu::FMIFloat64 tStop) override; + */ +// As defined in FMI3 standard: +void PySlaveInstance::EnterInitializationMode( + cppfmu::FMIBoolean toleranceDefined, + cppfmu::FMIFloat64 tolerance, + cppfmu::FMIFloat64 startTime, + cppfmu::FMIBoolean stopTimeDefined, + cppfmu::FMIFloat64 stopTime + ) { - py_safe_run([this](PyGILState_STATE gilState) { - auto f = PyObject_CallMethod(pInstance_, "enter_initialization_mode", nullptr); + py_safe_run([this, toleranceDefined, tolerance, startTime, stopTimeDefined, stopTime](PyGILState_STATE gilState){ + /*org: auto f = PyObject_CallMethod(pInstance_, "enterInitializationMode", "(ddd)", tolerance, startTime, stopTime); */ + auto f = PyObject_CallMethod(pInstance_, "enterInitializationMode", "(iddid)", toleranceDefined, tolerance, startTime, stopTimeDefined, stopTime); if (f == nullptr) { handle_py_exception("[enterInitializationMode] PyObject_CallMethod", gilState); } @@ -201,21 +228,31 @@ void PySlaveInstance::ExitInitializationMode() }); } -cppfmu::FMIStatus PySlaveInstance::DoStep(cppfmu::FMIFloat64 currentTime, - cppfmu::FMIFloat64 stepSize, - cppfmu::FMIBoolean noSetFmuStatePriorToCurrentPoint, +//cppfmu::FMIStatus PySlaveInstance::DoStep( +void PySlaveInstance::DoStep( + cppfmu::FMIFloat64 currentCommunicationPoint, + cppfmu::FMIFloat64 communicationStepSize, + cppfmu::FMIBoolean noSetFMUStatePriorToCurrentPoint, cppfmu::FMIBoolean* eventHandlingNeeded, cppfmu::FMIBoolean* terminateSimulation, cppfmu::FMIBoolean* earlyReturn, - cppfmu::FMIFloat64& endOfStep) + cppfmu::FMIFloat64* lastSuccessfullTime) { +/* Changed back to the original definition of DoStep cppfmu::FMIStatus fmuStatus = cppfmu::FMIOK; - py_safe_run([this, &fmuStatus, currentTime, stepSize, terminateSimulation](PyGILState_STATE gilState) { - auto f = PyObject_CallMethod(pInstance_, "do_step", "(dd)", currentTime, stepSize); + py_safe_run([this, &fmuStatus, currentTime, stepSize, eventHandlingNeeded, terminateSimulation, earlyReturn](PyGILState_STATE gilState) { +*/ + py_safe_run([this, currentCommunicationPoint, communicationStepSize, noSetFMUStatePriorToCurrentPoint, + eventHandlingNeeded, terminateSimulation, earlyReturn, lastSuccessfullTime](PyGILState_STATE gilState) { + auto f = PyObject_CallMethod(pInstance_, "doStep", "(ddO)", + currentCommunicationPoint, + communicationStepSize, + noSetFMUStatePriorToCurrentPoint ? Py_True : Py_False); if (f == nullptr) { handle_py_exception("[doStep] PyObject_CallMethod", gilState); } +/* optional result according to the old definition if (PyObject_HasAttrString(f, "status")) { PyObject* pyStatus = PyObject_GetAttrString(f, "status"); if (pyStatus) { @@ -228,19 +265,48 @@ cppfmu::FMIStatus PySlaveInstance::DoStep(cppfmu::FMIFloat64 currentTime, fmuStatus = cppfmu::FMIDiscard; } } - +*/ + if (PyObject_HasAttrString(f, "eventHandlingNeeded")) { + PyObject* pyEventHandlingNeeded = PyObject_GetAttrString(f, "eventHandlingNeeded"); + if (pyEventHandlingNeeded) { + *eventHandlingNeeded = static_cast(PyObject_IsTrue(pyEventHandlingNeeded)); + Py_DECREF(pyEventHandlingNeeded); + } + } else { + *eventHandlingNeeded = false; + } if (PyObject_HasAttrString(f, "terminateSimulation")) { PyObject* pyTerminateSimulation = PyObject_GetAttrString(f, "terminateSimulation"); if (pyTerminateSimulation) { *terminateSimulation = static_cast(PyObject_IsTrue(pyTerminateSimulation)); Py_DECREF(pyTerminateSimulation); } + } else { + *terminateSimulation = false; + } + if (PyObject_HasAttrString(f, "earlyReturn")) { + PyObject* pyEarlyReturn = PyObject_GetAttrString(f, "earlyReturn"); + if (pyEarlyReturn) { + *earlyReturn = static_cast(PyObject_IsTrue(pyEarlyReturn)); + Py_DECREF(pyEarlyReturn); + } + } else { + *earlyReturn = false; + } + if (PyObject_HasAttrString(f, "lastSuccessfullTime")) { + PyObject* pyLastSuccessfullTime = PyObject_GetAttrString(f, "lastSuccessfullTime"); + if (pyLastSuccessfullTime) { + *lastSuccessfullTime = PyFloat_AsDouble(pyLastSuccessfullTime); + Py_DECREF(pyLastSuccessfullTime); + } + } else { + *lastSuccessfullTime = currentCommunicationPoint + communicationStepSize; } Py_DECREF(f); clearLogBuffer(); }); - return fmuStatus; +// return fmuStatus; } void PySlaveInstance::Reset() @@ -546,7 +612,7 @@ void PySlaveInstance::GetContinuousStates(cppfmu::FMIFloat64* continuousStates, py_safe_run([this, &continuousStates, nStates](PyGILState_STATE gilState) { auto f = PyObject_CallMethod(pInstance_, "get_continuous_states", nullptr); if (f == nullptr) { - handle_py_exception("[get_continuous_states] PyObject_CallMethod", gilState); + handle_py_exception("[getContinuousStates] PyObject_CallMethod", gilState); } // Assuming f is a list of floats for (std::size_t i = 0; i < nStates; i++) { @@ -564,7 +630,7 @@ void PySlaveInstance::GetContinuousStateDerivatives(cppfmu::FMIFloat64* continuo auto f = PyObject_CallMethod(pInstance_, "get_continuous_state_derivatives", nullptr); if (f == nullptr) { PyErr_Print(); - handle_py_exception("[get_continuous_state_derivatives] PyObject_CallMethod", gilState); + handle_py_exception("[getContinuousStateDerivatives] PyObject_CallMethod", gilState); } // Assuming f is a list of floats for (std::size_t i = 0; i < nStates; i++) { @@ -582,7 +648,7 @@ void PySlaveInstance::GetNominalsOfContinuousStates(cppfmu::FMIFloat64* nominals auto f = PyObject_CallMethod(pInstance_, "get_nominals_of_continuous_states", "(i)", static_cast(nStates)); // Check if f is a valid object if (f == nullptr) { - handle_py_exception("[getNominalContinuousStates] PyObject_CallMethod", gilState); + handle_py_exception("[getNominalsOfContinuousStates] PyObject_CallMethod", gilState); } // Assuming f is a list of floats for (std::size_t i = 0; i < nStates; i++) { @@ -677,7 +743,8 @@ void PySlaveInstance::UpdateDiscreteStates( cppfmu::FMIBoolean* nextEventTimeDefined, cppfmu::FMIFloat64* nextEventTime) { - py_safe_run([this, discreteStatesNeedUpdate, terminateSimulation, nominalContinuousStatesChanged, valuesOfContinuousStatesChanged, nextEventTimeDefined, nextEventTime](PyGILState_STATE gilState) { + py_safe_run([this, discreteStatesNeedUpdate, terminateSimulation, nominalContinuousStatesChanged, + valuesOfContinuousStatesChanged, nextEventTimeDefined, nextEventTime](PyGILState_STATE gilState) { auto f = PyObject_CallMethod(pInstance_, "update_discrete_states", nullptr); if (f == nullptr) { handle_py_exception("[updateDiscreteStates] PyObject_CallMethod", gilState); @@ -724,7 +791,7 @@ void PySlaveInstance::GetFMUstate(fmi3FMUState& state) py_safe_run([this, &state](PyGILState_STATE gilState) { auto f = PyObject_CallMethod(pInstance_, "_get_fmu_state", nullptr); if (f == nullptr) { - handle_py_exception("[_get_fmu_state] PyObject_CallMethod", gilState); + handle_py_exception("[getFMUState] PyObject_CallMethod", gilState); } state = reinterpret_cast(f); clearLogBuffer(); @@ -737,7 +804,7 @@ void PySlaveInstance::SetFMUstate(const fmi3FMUState& state) auto pyState = reinterpret_cast(state); auto f = PyObject_CallMethod(pInstance_, "_set_fmu_state", "(O)", pyState); if (f == nullptr) { - handle_py_exception("[_set_fmu_state] PyObject_CallMethod", gilState); + handle_py_exception("[setFMUState] PyObject_CallMethod", gilState); } clearLogBuffer(); }); @@ -805,6 +872,376 @@ void PySlaveInstance::DeSerializeFMUstate(const fmi3Byte bytes[], size_t size, f }); } +// ================================ +// Event- and Clock-related methods +void PySlaveInstance::EnterEventMode() +{ + py_safe_run([this](PyGILState_STATE gilState) { + auto f = PyObject_CallMethod(pInstance_, "enter_event_mode", nullptr); + if (f == nullptr) { + handle_py_exception("[enterEventMode] PyObject_CallMethod", gilState); + } + Py_DECREF(f); + clearLogBuffer(); + }); +} + +void PySlaveInstance::EnterContinuousTimeMode() +{ + py_safe_run([this](PyGILState_STATE gilState) { + auto f = PyObject_CallMethod(pInstance_, "enter_continuous_time_mode", nullptr); + if (f == nullptr) { + handle_py_exception("[enterContinuousTimeMode] PyObject_CallMethod", gilState); + } + Py_DECREF(f); + clearLogBuffer(); + }); +} + +void PySlaveInstance::CompletedIntegratorStep( + cppfmu::FMIBoolean noSetFMUStatePriorToCurrentPoint, + cppfmu::FMIBoolean* enterEventMode, + cppfmu::FMIBoolean* terminateSimulation) +{ + py_safe_run([this, noSetFMUStatePriorToCurrentPoint, &enterEventMode, &terminateSimulation](PyGILState_STATE gilState) { + auto f = PyObject_CallMethod(pInstance_, "completedIntegratorStep", "(p)", noSetFMUStatePriorToCurrentPoint); + if (f == nullptr) { + handle_py_exception("[completedIntegratorStep] PyObject_CallMethod", gilState); + } + if (PyObject_HasAttrString(f, "enterEventMode")) { + PyObject* pyEnterEventMode = PyObject_GetAttrString(f, "enterEventMode"); + if (pyEnterEventMode) { + *enterEventMode = static_cast(PyObject_IsTrue(pyEnterEventMode)); + Py_DECREF(pyEnterEventMode); + } + } else { + *enterEventMode = false; + } + if (PyObject_HasAttrString(f, "terminateSimulation")) { + PyObject* pyTerminateSimulation = PyObject_GetAttrString(f, "terminateSimulation"); + if (pyTerminateSimulation) { + *terminateSimulation = static_cast(PyObject_IsTrue(pyTerminateSimulation)); + Py_DECREF(pyTerminateSimulation); + } + } else { + *terminateSimulation = false; + } + Py_DECREF(f); + clearLogBuffer(); + }); +} + + +void PySlaveInstance::EnterStepMode() +{ + py_safe_run([this](PyGILState_STATE gilState) { + auto f = PyObject_CallMethod(pInstance_, "enter_step_mode", nullptr); + if (f == nullptr) { + handle_py_exception("[enterStepMode] PyObject_CallMethod", gilState); + } + Py_DECREF(f); + clearLogBuffer(); + }); +} + +void PySlaveInstance::GetClock(const cppfmu::FMIValueReference* vr, std::size_t nvr, cppfmu::FMIClock* values) const +{ + py_safe_run([this, &vr, nvr, &values](PyGILState_STATE gilState) { + PyObject* vrs = PyList_New(nvr); + for (int i = 0; i < nvr; i++) { + PyList_SetItem(vrs, i, Py_BuildValue("i", vr[i])); + } + auto refs = PyObject_CallMethod(pInstance_, "get_clock", "O", vrs); + Py_DECREF(vrs); + if (refs == nullptr) { + handle_py_exception("[getClock] PyObject_CallMethod", gilState); + } + + for (int i = 0; i < nvr; i++) { + PyObject* value = PyList_GetItem(refs, i); + values[i] = PyObject_IsTrue(value); + } + Py_DECREF(refs); + clearLogBuffer(); + }); +} +void PySlaveInstance::SetClock(const cppfmu::FMIValueReference* vr, std::size_t nvr, const cppfmu::FMIClock* values) +{ + py_safe_run([this, &vr, nvr, &values](PyGILState_STATE gilState) { + PyObject* vrs = PyList_New(nvr); + PyObject* refs = PyList_New(nvr); + for (int i = 0; i < nvr; i++) { + PyList_SetItem(vrs, i, Py_BuildValue("i", vr[i])); + } + for (int i = 0; i < nvr; i++) { + PyList_SetItem(refs, i, PyBool_FromLong(values[i])); + } + + auto f = PyObject_CallMethod(pInstance_, "set_clock", "(OO)", vrs, refs); + Py_DECREF(vrs); + Py_DECREF(refs); + if (f == nullptr) { + handle_py_exception("[setClock] PyObject_CallMethod", gilState); + } + Py_DECREF(f); + clearLogBuffer(); + }); +} +void PySlaveInstance::GetIntervalDecimal( + const cppfmu::FMIValueReference* vr, + std::size_t nvr, + cppfmu::FMIFloat64* intervals, + cppfmu::FMIIntervalQualifier* qualifiers) const +{ + py_safe_run([this, &vr, nvr, &intervals, &qualifiers](PyGILState_STATE gilState) { + PyObject* vrs = PyList_New(nvr); + for (int i = 0; i < nvr; i++) { + PyList_SetItem(vrs, i, Py_BuildValue("i", vr[i])); + } + + auto refs = PyObject_CallMethod(pInstance_, "get_interval_decimal", "O", vrs); + Py_DECREF(vrs); + if (refs == nullptr) { + handle_py_exception("[getIntervalDecimal] PyObject_CallMethod", gilState); + } + if (PySequence_Size(refs)!=2) { + handle_py_exception("[getIntervalDecimal] !=2 return objects", gilState); + } + PyObject* ref0 = PyList_GetItem(refs, 0); + for (int i = 0; i < nvr; i++) { + PyObject* value = PyList_GetItem(ref0, i); + intervals[i] = PyFloat_AsDouble(value); + } + PyObject* ref1 = PyList_GetItem(refs, 1); + for (int i = 0; i < nvr; i++) { + PyObject* value = PyList_GetItem(ref1, i); + if (value && PyLong_Check(value)) + qualifiers[i] = static_cast(PyLong_AsLong(value)); + else + handle_py_exception("[getIntervalDecimal] invalid interval qualifier", gilState); + } + // ref0 and ref1 represent borrowed references. No DECREF used on them. + Py_DECREF(refs); + clearLogBuffer(); + }); +} + +void PySlaveInstance::SetIntervalDecimal(const cppfmu::FMIValueReference* vr, std::size_t nvr, const cppfmu::FMIFloat64* intervals) +{ + py_safe_run([this, &vr, nvr, &intervals](PyGILState_STATE gilState) { + PyObject* vrs = PyList_New(nvr); + PyObject* refs = PyList_New(nvr); + for (int i = 0; i < nvr; i++) { + PyList_SetItem(vrs, i, Py_BuildValue("i", vr[i])); + } + for (int i = 0; i < nvr; i++) { + PyList_SetItem(refs, i, Py_BuildValue("d", intervals[i])); + } + + auto f = PyObject_CallMethod(pInstance_, "set_interval_decimal", "(OO)", vrs, refs); + Py_DECREF(vrs); + Py_DECREF(refs); + if (f == nullptr) { + handle_py_exception("[setFloat64] PyObject_CallMethod", gilState); + } + Py_DECREF(f); + clearLogBuffer(); + }); +} +void PySlaveInstance::GetShiftDecimal(const cppfmu::FMIValueReference* vr, std::size_t nvr, cppfmu::FMIFloat64* shifts) const +{ + py_safe_run([this, &vr, nvr, &shifts](PyGILState_STATE gilState) { + PyObject* vrs = PyList_New(nvr); + for (int i = 0; i < nvr; i++) { + PyList_SetItem(vrs, i, Py_BuildValue("i", vr[i])); + } + auto refs = PyObject_CallMethod(pInstance_, "get_shift_decimal", "O", vrs); + Py_DECREF(vrs); + if (refs == nullptr) { + handle_py_exception("[getShiftDecimal] PyObject_CallMethod", gilState); + } + + for (int i = 0; i < nvr; i++) { + PyObject* value = PyList_GetItem(refs, i); + shifts[i] = PyFloat_AsDouble(value); + } + Py_DECREF(refs); + clearLogBuffer(); + }); +} + +void PySlaveInstance::SetShiftDecimal(const cppfmu::FMIValueReference* vr, std::size_t nvr, const cppfmu::FMIFloat64* shifts) +{ + py_safe_run([this, &vr, nvr, &shifts](PyGILState_STATE gilState) { + PyObject* vrs = PyList_New(nvr); + PyObject* refs = PyList_New(nvr); + for (int i = 0; i < nvr; i++) { + PyList_SetItem(vrs, i, Py_BuildValue("i", vr[i])); + } + for (int i = 0; i < nvr; i++) { + PyList_SetItem(refs, i, Py_BuildValue("d", shifts[i])); + } + + auto f = PyObject_CallMethod(pInstance_, "set_shift_decimal", "(OO)", vrs, refs); + Py_DECREF(vrs); + Py_DECREF(refs); + if (f == nullptr) { + handle_py_exception("[setShiftDecimal] PyObject_CallMethod", gilState); + } + Py_DECREF(f); + clearLogBuffer(); + }); +} + +void PySlaveInstance::GetIntervalFraction( + const cppfmu::FMIValueReference* vr, + std::size_t nvr, + cppfmu::FMIUInt64* intervalCounters, + cppfmu::FMIUInt64* resolutions, + cppfmu::FMIIntervalQualifier* qualifiers) const +{ + py_safe_run([this, &vr, nvr, &intervalCounters, &resolutions, &qualifiers](PyGILState_STATE gilState) { + PyObject* vrs = PyList_New(nvr); + for (int i = 0; i < nvr; i++) { + PyList_SetItem(vrs, i, Py_BuildValue("i", vr[i])); + } + + auto refs = PyObject_CallMethod(pInstance_, "get_interval_fraction", "O", vrs); + Py_DECREF(vrs); + if (refs == nullptr) { + handle_py_exception("[getIntervalFraction] PyObject_CallMethod", gilState); + } + if (PySequence_Size(refs)!=3) { + handle_py_exception("[getIntervalFraction] !=3 return objects", gilState); + } + PyObject* ref0 = PyList_New(nvr); + ref0 = PyList_GetItem( refs, 0); + //auto ref0 = PyList_GetItem(refs, 0); + for (int i = 0; i < nvr; i++) { + PyObject* value = PyList_GetItem(ref0, i); + intervalCounters[i] = static_cast(PyLong_AsUnsignedLongLong(value)); + } + Py_DECREF(ref0); + auto ref1 = PyList_GetItem(refs, 1); + for (int i = 0; i < nvr; i++) { + PyObject* value = PyList_GetItem(ref1, i); + resolutions[i] = static_cast(PyLong_AsUnsignedLongLong(value)); + } + Py_DECREF(ref1); + auto ref2 = PyList_GetItem(refs, 2); + for (int i = 0; i < nvr; i++) { + PyObject* value = PyList_GetItem(ref2, i); + qualifiers[i] = static_cast(PyLong_AsLong(value)); + } + Py_DECREF(ref2); + Py_DECREF(refs); + clearLogBuffer(); + }); +} + +void PySlaveInstance::SetIntervalFraction( + const cppfmu::FMIValueReference* vr, + std::size_t nvr, + const cppfmu::FMIUInt64* intervalCounters, + const cppfmu::FMIUInt64* resolutions) +{ + py_safe_run([this, &vr, nvr, &intervalCounters, &resolutions](PyGILState_STATE gilState) { + PyObject* vrs = PyList_New(nvr); + PyObject* refs1 = PyList_New(nvr); + PyObject* refs2 = PyList_New(nvr); + for (int i = 0; i < nvr; i++) { + PyList_SetItem(vrs, i, Py_BuildValue("i", vr[i])); + } + for (int i = 0; i < nvr; i++) { + PyList_SetItem(refs1, i, Py_BuildValue("K", intervalCounters[i])); + } + for (int i = 0; i < nvr; i++) { + PyList_SetItem(refs2, i, Py_BuildValue("K", resolutions[i])); + } + + auto f = PyObject_CallMethod(pInstance_, "set_interval_fraction", "(OO)", vrs, refs1, refs2); + Py_DECREF(vrs); + Py_DECREF(refs1); + Py_DECREF(refs2); + if (f == nullptr) { + handle_py_exception("[setIntervalFraction] PyObject_CallMethod", gilState); + } + Py_DECREF(f); + clearLogBuffer(); + }); +} + +void PySlaveInstance::GetShiftFraction( + const cppfmu::FMIValueReference* vr, + std::size_t nvr, + cppfmu::FMIUInt64* shiftCounters, + cppfmu::FMIUInt64* resolutions) const +{ + py_safe_run([this, &vr, nvr, &shiftCounters, &resolutions](PyGILState_STATE gilState) { + PyObject* vrs = PyList_New(nvr); + for (int i = 0; i < nvr; i++) { + PyList_SetItem(vrs, i, Py_BuildValue("i", vr[i])); + } + auto refs = PyObject_CallMethod(pInstance_, "get_shift_fraction", "O", vrs); + Py_DECREF(vrs); + if (refs == nullptr) { + handle_py_exception("[getShiftFraction] PyObject_CallMethod", gilState); + } + if (PySequence_Size(refs)!=2) { + handle_py_exception("[getShiftFraction] !=2 return objects", gilState); + } + auto ref0 = PyList_GetItem(refs, 0); + for (int i = 0; i < nvr; i++) { + PyObject* value = PyList_GetItem(ref0, i); + shiftCounters[i] = static_cast(PyLong_AsUnsignedLongLong(value)); + } + Py_DECREF(ref0); + auto ref1 = PyList_GetItem(refs, 1); + for (int i = 0; i < nvr; i++) { + PyObject* value = PyList_GetItem(ref1, i); + resolutions[i] = static_cast(PyLong_AsUnsignedLongLong(value)); + } + Py_DECREF(ref1); + Py_DECREF(refs); + clearLogBuffer(); + }); +} + +void PySlaveInstance::SetShiftFraction( + const cppfmu::FMIValueReference* vr, + std::size_t nvr, + const cppfmu::FMIUInt64* shiftCounters, + const cppfmu::FMIUInt64* resolutions) +{ + py_safe_run([this, &vr, nvr, &shiftCounters, &resolutions](PyGILState_STATE gilState) { + PyObject* vrs = PyList_New(nvr); + PyObject* refs1 = PyList_New(nvr); + PyObject* refs2 = PyList_New(nvr); + for (int i = 0; i < nvr; i++) { + PyList_SetItem(vrs, i, Py_BuildValue("i", vr[i])); + } + for (int i = 0; i < nvr; i++) { + PyList_SetItem(refs1, i, Py_BuildValue("K", shiftCounters[i])); + } + for (int i = 0; i < nvr; i++) { + PyList_SetItem(refs2, i, Py_BuildValue("K", resolutions[i])); + } + + auto f = PyObject_CallMethod(pInstance_, "set_shift_fraction", "(OO)", vrs, refs1, refs2); + Py_DECREF(vrs); + Py_DECREF(refs1); + Py_DECREF(refs2); + if (f == nullptr) { + handle_py_exception("[setShiftFraction] PyObject_CallMethod", gilState); + } + Py_DECREF(f); + clearLogBuffer(); + }); +} + +// ============== +// Helper methods + void PySlaveInstance::handle_py_exception(const std::string& what, PyGILState_STATE gilState) const { auto err = PyErr_Occurred(); @@ -862,7 +1299,10 @@ std::unique_ptr CppfmuInstantiateSlave( cppfmu::FMIFloat64, cppfmu::FMIBoolean visible, cppfmu::FMIBoolean, - const cppfmu::Logger& logger) + const cppfmu::Logger& logger, + cppfmu::FMIBoolean eventModeUsed, + cppfmu::FMIBoolean earlyReturnAllowed + ) { // Convert URI %20 to space @@ -885,7 +1325,7 @@ std::unique_ptr CppfmuInstantiateSlave( ensurePyStateAlive(); return std::make_unique( - instanceName, resources, logger, visible, pyState); + instanceName, resources, logger, visible, eventModeUsed, earlyReturnAllowed, pyState); } } diff --git a/pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.hpp b/src/pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.hpp similarity index 59% rename from pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.hpp rename to src/pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.hpp index 609ca61..70363a8 100644 --- a/pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.hpp +++ b/src/pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.hpp @@ -16,22 +16,36 @@ class PySlaveInstance : public cppfmu::SlaveInstance { public: - PySlaveInstance(std::string instanceName, std::string resources, const cppfmu::Logger& logger, bool visible, std::shared_ptr pyState); + PySlaveInstance( + std::string instanceName, + std::string resources, + const cppfmu::Logger& logger, + bool visible, + bool eventModeUsed, + bool earlyReturnAllowed, + std::shared_ptr pyState + ); void initialize(PyGILState_STATE gilState); - void SetupExperiment(cppfmu::FMIBoolean toleranceDefined, cppfmu::FMIFloat64 tolerance, cppfmu::FMIFloat64 tStart, cppfmu::FMIBoolean stopTimeDefined, cppfmu::FMIFloat64 tStop) override; - void EnterInitializationMode() override; + // not defined: void SetupExperiment(cppfmu::FMIBoolean toleranceDefined, cppfmu::FMIFloat64 tolerance, cppfmu::FMIFloat64 tStart, cppfmu::FMIBoolean stopTimeDefined, cppfmu::FMIFloat64 tStop) override; + void EnterInitializationMode( + cppfmu::FMIBoolean toleranceDefined, + cppfmu::FMIFloat64 tolerance, + cppfmu::FMIFloat64 startTime, + cppfmu::FMIBoolean stopTimeDefined, + cppfmu::FMIFloat64 stopTime) override; void ExitInitializationMode() override; void Terminate() override; void Reset() override; - cppfmu::FMIStatus DoStep(cppfmu::FMIFloat64 currentCommunicationPoint, - cppfmu::FMIFloat64 communicationStepSize, - cppfmu::FMIBoolean newStep, - cppfmu::FMIBoolean* eventHandlingNeeded, - cppfmu::FMIBoolean* terminateSimulation, - cppfmu::FMIBoolean* earlyReturn, - cppfmu::FMIFloat64& endOfStep) override; +// cppfmu::FMIStatus DoStep(cppfmu::FMIFloat64 currentCommunicationPoint, + void DoStep(cppfmu::FMIFloat64 currentCommunicationPoint, + cppfmu::FMIFloat64 communicationStepSize, + cppfmu::FMIBoolean noSetFMUStatePriorToCurrentPoint, + cppfmu::FMIBoolean* eventHandlingNeeded, + cppfmu::FMIBoolean* terminateSimulation, + cppfmu::FMIBoolean* earlyReturn, + cppfmu::FMIFloat64* lastSuccessfullTime) override; void SetFloat64(const cppfmu::FMIValueReference* vr, std::size_t nvr, const cppfmu::FMIFloat64* value, std::size_t nValues) override; void SetInt32(const cppfmu::FMIValueReference* vr, std::size_t nvr, const cppfmu::FMIInt32* value, std::size_t nValues) override; @@ -50,7 +64,48 @@ class PySlaveInstance : public cppfmu::SlaveInstance void GetFMUstate(fmi3FMUState& State) override; void SetFMUstate(const fmi3FMUState& State) override; void FreeFMUstate(fmi3FMUState& State) override; - + + // Event- and Clock-related methods + void EnterEventMode() override; + void EnterContinuousTimeMode() override; + void CompletedIntegratorStep( + cppfmu::FMIBoolean noSetFMUStatePriorToCurrentPoint, + cppfmu::FMIBoolean* enterEventMode, + cppfmu::FMIBoolean* terminateSimulation); + void EnterStepMode() override; + void GetClock(const cppfmu::FMIValueReference* vr, std::size_t nvr, cppfmu::FMIClock* values) const override; + void SetClock(const cppfmu::FMIValueReference* vr, std::size_t nvr, const cppfmu::FMIClock* values) override; + void GetIntervalDecimal( + const cppfmu::FMIValueReference* vr, + std::size_t nvr, + cppfmu::FMIFloat64* intervals, + cppfmu::FMIIntervalQualifier* qualifiers) const override; + void SetIntervalDecimal(const cppfmu::FMIValueReference* vr, std::size_t nvr, const cppfmu::FMIFloat64* intervals) override; + void GetShiftDecimal(const cppfmu::FMIValueReference* vr, std::size_t nvr, cppfmu::FMIFloat64* shifts) const override; + void SetShiftDecimal(const cppfmu::FMIValueReference* vr, std::size_t nvr, const cppfmu::FMIFloat64* shifts) override; + void GetIntervalFraction( + const cppfmu::FMIValueReference* vr, + std::size_t nvr, + cppfmu::FMIUInt64* intervalCounters, + cppfmu::FMIUInt64* resolutions, + cppfmu::FMIIntervalQualifier* qualifiers) const override; + void SetIntervalFraction( + const cppfmu::FMIValueReference* vr, + std::size_t nvr, + const cppfmu::FMIUInt64* intervalCounters, + const cppfmu::FMIUInt64* resolutions) override; + void GetShiftFraction( + const cppfmu::FMIValueReference* vr, + std::size_t nvr, + cppfmu::FMIUInt64* shiftCounters, + cppfmu::FMIUInt64* resolutions) const override; + void SetShiftFraction( + const cppfmu::FMIValueReference* vr, + std::size_t nvr, + const cppfmu::FMIUInt64* shiftCounters, + const cppfmu::FMIUInt64* resolutions) override; + + // Model Exchange methods void GetContinuousStates(cppfmu::FMIFloat64* continuousStates, std::size_t nStates) const override; void GetNumberOfContinuousStates(std::size_t& nStates) const override; @@ -84,10 +139,11 @@ class PySlaveInstance : public cppfmu::SlaveInstance PyObject* pMessages_{}; const bool visible_; + const bool eventModeUsed_; + const bool earlyReturnAllowed_; const std::string instanceName_; const std::string resources_; const cppfmu::Logger& logger_; - mutable std::vector strBuffer; mutable std::vector logStrBuffer; diff --git a/pythonfmu3/pythonfmu-export/src/pythonfmu/PyState.hpp b/src/pythonfmu3/pythonfmu-export/src/pythonfmu/PyState.hpp similarity index 95% rename from pythonfmu3/pythonfmu-export/src/pythonfmu/PyState.hpp rename to src/pythonfmu3/pythonfmu-export/src/pythonfmu/PyState.hpp index ae64364..b7bc1de 100644 --- a/pythonfmu3/pythonfmu-export/src/pythonfmu/PyState.hpp +++ b/src/pythonfmu3/pythonfmu-export/src/pythonfmu/PyState.hpp @@ -33,10 +33,10 @@ namespace pythonfmu private: - // In accordance to the documentation https://docs.python.org/3/c-api/init.html#c.Py_FinalizeEx + // In accordance to the documentation https://docs.python.org/3/c-api/init.html#c.Py_FinalizeEx // the Py_Initialize/Py_Finalize should be called from the same // thread. The FMI standard allows to call fmi functions from different threads, also different threads - // could be used for loading unloading the FMU libraries. There is a deadlock, when the simulation tool + // could be used for loading unloading the FMU libraries. There is a deadlock, when the simulation tool // unloads the FMU library from the thread which is differs from the thread where the Py_Initialize was called. // Create a new thread which is used for calling Py_Initialize and Py_Deinitialize. The thread waits for // notification from destructor and then calls Py_Deinitialize. @@ -82,4 +82,4 @@ namespace pythonfmu } // namespace pythonfmu -#endif //PYTHONFMU_PYTHONSTATE_HPP \ No newline at end of file +#endif //PYTHONFMU_PYTHONSTATE_HPP diff --git a/src/pythonfmu3/resources/binaries/x86_64-linux/libpythonfmu-export.so b/src/pythonfmu3/resources/binaries/x86_64-linux/libpythonfmu-export.so new file mode 100644 index 0000000..e1c64e0 Binary files /dev/null and b/src/pythonfmu3/resources/binaries/x86_64-linux/libpythonfmu-export.so differ diff --git a/src/pythonfmu3/resources/binaries/x86_64-windows/pythonfmu-export.dll b/src/pythonfmu3/resources/binaries/x86_64-windows/pythonfmu-export.dll new file mode 100644 index 0000000..673cbd1 Binary files /dev/null and b/src/pythonfmu3/resources/binaries/x86_64-windows/pythonfmu-export.dll differ diff --git a/src/pythonfmu3/unit.py b/src/pythonfmu3/unit.py new file mode 100644 index 0000000..58d30c0 --- /dev/null +++ b/src/pythonfmu3/unit.py @@ -0,0 +1,65 @@ +from xml.etree.ElementTree import Element + + +class BaseUnit: + tag = "BaseUnit" + base_units = { + "kg": 0, + "m": 0, + "s": 0, + "A": 0, + "K": 0, + "mol": 0, + "cd": 0, + "rad": 0, + } + + def __init__(self, factor=1.0, offset=0.0, **kwargs) -> None: + self._factor = factor + self._offset = offset + self._units = {**BaseUnit.base_units, **kwargs} + + @property + def units(self): + return {key: str(value) for key, value in self._units.items() if value != 0} + + def to_xml(self): + """Convert the variable to XML node. + + Returns + ------- + xml.etree.ElementTree.Element: XML node + """ + attrib = dict() + if self._factor != 1.0: + attrib["factor"] = str(self._factor) + if self._offset != 0.0: + attrib["offset"] = str(self._offset) + attrib.update(self.units) + ele = Element(self.tag, attrib) + return ele + + +class Unit: + tag = "Unit" + + def __init__(self, name, **kwargs): + self._name = name + self._base_unit = BaseUnit(**kwargs) + + @property + def name(self) -> str: + return self._name + + def to_xml(self) -> Element: + """Convert the variable to XML node. + + Returns + ------- + xml.etree.ElementTree.Element: XML node + """ + attrib = dict() + attrib["name"] = self._name + ele = Element(self.tag, attrib) + ele.append(self._base_unit.to_xml()) + return ele diff --git a/pythonfmu3/variable_types.py b/src/pythonfmu3/variable_types.py similarity index 78% rename from pythonfmu3/variable_types.py rename to src/pythonfmu3/variable_types.py index 34286e8..0108f3b 100644 --- a/pythonfmu3/variable_types.py +++ b/src/pythonfmu3/variable_types.py @@ -1,16 +1,15 @@ from enum import Enum -from typing import Optional from xml.etree.ElementTree import Element -class VariableType(object): +class VariableType: def __init__(self, tag, name, **kwargs): self._tag = tag self._attrs = { "name": name, } self._attrs.update(**kwargs) - + @property def name(self) -> str: """str: Variable name""" @@ -20,6 +19,7 @@ def to_xml(self) -> Element: """Convert the variable to XML node. Returns + ------- xml.etree.ElementTree.Element: XML node """ attrib = dict() @@ -28,6 +28,7 @@ def to_xml(self) -> Element: attrib[key] = str(value.name if isinstance(value, Enum) else value) return Element(self._tag, attrib) + class Float64Type(VariableType): tag = "Float64Type" @@ -35,15 +36,13 @@ def __init__(self, name, **kwargs): super().__init__(self.tag, name, **kwargs) -class Item(object): +class Item: + """Helper class for EnumerationType definitions.""" + tag = "Item" def __init__(self, name: str, value: int, description: str = "", **kwargs): - self.__attrs = { - "name": name, - "value": str(value), - "description": description - } + self.__attrs = {"name": name, "value": str(value), "description": description} def name(self) -> str: return self.__attrs["name"] @@ -53,13 +52,14 @@ def value(self) -> str: return self.__attrs["value"] @property - def description(self) -> Optional[str]: + def description(self) -> str | None: return self.__attrs["description"] def to_xml(self) -> Element: """Convert the variable to XML node. Returns + ------- xml.etree.ElementTree.Element: XML node """ attrib = dict() @@ -69,24 +69,22 @@ def to_xml(self) -> Element: return Element(self.tag, attrib) def __repr__(self) -> str: - return f"{self.__class__.__name__}" \ - f"(name={self.name}, " \ - f"value={self.value}, " \ - f"description={self.description})" + return f"{self.__class__.__name__}(name={self.name}, value={self.value}, description={self.description})" + class EnumerationType(VariableType): tag = "EnumerationType" - def __init__(self, name: str, values: Optional[Enum] = None, **kwargs): + def __init__(self, name: str, values: Enum | None = None, **kwargs): super().__init__(self.tag, name, **kwargs) self._items = {} - + for val in values: - self.add_value(name = val.name, value = val.value) + self.add_value(name=val.name, value=val.value) def add_value(self, name: str, value: int, description: str = "", **kwargs): self._items[name] = Item(name, value, description, **kwargs) - + def get_value(self, name): return self._items[name] @@ -94,9 +92,10 @@ def to_xml(self) -> Element: """Convert the variable to XML node. Returns + ------- xml.etree.ElementTree.Element: XML node """ parent = super().to_xml() for _, item in self._items.items(): parent.append(item.to_xml()) - return parent \ No newline at end of file + return parent diff --git a/src/pythonfmu3/variables.py b/src/pythonfmu3/variables.py new file mode 100644 index 0000000..3378925 --- /dev/null +++ b/src/pythonfmu3/variables.py @@ -0,0 +1,607 @@ +"""Classes describing interface variables.""" + +from __future__ import annotations +import importlib +from abc import ABC +from collections import ChainMap +from collections.abc import Iterable +from enum import Enum +from functools import reduce +import numpy as np +from typing import Any, TypeAlias +import sys +from xml.etree.ElementTree import Element + +from pythonfmu3.enums import Fmi3Causality, Fmi3Initial, Fmi3IntervalVariability, Fmi3Variability + +FMIScalar : TypeAlias = np.generic | bool | int | float | str + +MAX_LENGTH = 1000 + + +def flatten(lst): + for item in lst: + if isinstance(item, Iterable) and not isinstance(item, (str, bytes)): + yield from flatten(item) + else: + yield item + + +def check_numpy(): + try: + importlib.import_module("numpy") + except ModuleNotFoundError: + raise ModuleNotFoundError("Numpy is not installed, it is required for Array support") + +py_types: dict[str, type] = { + "Real": float, + "Integer": int, + "Boolean": bool, + "String": str, + "Float32": np.float32, + "Float64": np.float64, + "Int8": np.int8, + "UInt8": np.uint8, + "Int16": np.int16, + "UInt16": np.uint16, + "Int32": np.int32, + "UInt32": np.uint32, + "Int64": np.int64, + "UInt64": np.uint64, + "Enumeration": int, + "Clock": bool, +} + +def fmi_type_version( fmi_type_name:str, fmi_version:int=3) -> bool: + """Check whether the FMI type is valid in the given FMI version. + + Args: + fmi_type_name: name of a variable type as listed in py_types + fmi_version: main fmi version number of the FMU (as int) + """ + if fmi_type_name not in py_types: + return False + if fmi_version < 3 and fmi_type_name in ("Real", "Integer", "Boolean", "String", "Enumeration"): + return True + if fmi_version == 3 and fmi_type_name not in ("Real", "Integer"): + return True + return False + + +def fmi_type( fmi_type_name:str): + """Get the fmi type object from the fmi type str.""" + return getattr( sys.modules[__name__], fmi_type_name) + +class ModelVariable(ABC): + """Abstract FMI model variable definition. + + Args: + name (str): Variable name + causality (:obj:`Fmi3Causality`, optional): Variable causality + description (str, optional): Variable description + initial (:obj:`Fmi3Initial`, optional): Variable initial status + variability (:obj:`Fmi3Variability`, optional): Variable variability + declared_type: optional reference to a previously declared type (see VariableType) + getter: optional explicit definition of a getter function + setter: optional explicit definition of a setter function + canHandleMultipleSetPerTimeInstant: boolean flag. See FMI spec. + """ + + def __init__( + self, + name: str, + causality: Fmi3Causality | None = None, + description: str | None = None, + initial: Fmi3Initial | None = None, + variability: Fmi3Variability | None = None, + declared_type: str | None = None, + getter: Any = None, + setter: Any = None, + can_handle_multiple_set_per_time_instant: bool = True, + ): + self.getter = getter + self.setter = setter + self._type = None + self.local_name = name.rsplit(".", maxsplit=1)[-1] + + # demanagle names + self.local_name = self.local_name.lstrip("_") + + self.__attrs = { + "name": name, + "valueReference": None, + "description": description, + "causality": causality, + "variability": variability, + "initial": initial, + "declaredType": declared_type, + "canHandleMultipleSetPerTimeInstant": can_handle_multiple_set_per_time_instant, + } + self._extras = {} + + @property + def causality(self) -> Fmi3Causality | None: + """:obj:`Fmi3Causality` or None: Variable causality - None if not set""" + return self.__attrs["causality"] + + @property + def description(self) -> str | None: + """Str or None: Variable description - None if not set""" + return self.__attrs["description"] + + @property + def initial(self) -> Fmi3Initial | None: + """:obj:`Fmi3Initial` or None: Variable initial status - None if not set""" + return self.__attrs["initial"] + + @property + def name(self) -> str: + """str: Variable name""" + return self.__attrs["name"] + + @property + def value_reference(self) -> int: + """int: Variable reference index""" + return self.__attrs["valueReference"] + + @value_reference.setter + def value_reference(self, value: int): + if self.__attrs["valueReference"] is not None: + raise RuntimeError("Value reference already set.") + self.__attrs["valueReference"] = value + + @property + def declared_type(self) -> str: + """str: declared type""" + return self.__attrs["declaredType"] + + @declared_type.setter + def declared_type(self, value: str): + if self.__attrs["declaredType"] is not None: + raise RuntimeError("Declared type already set.") + self.__attrs["declaredType"] = value + + @property + def variability(self) -> Fmi3Variability | None: + """:obj:`Fmi3Variability` or None: Variable variability - None if not set""" + return self.__attrs["variability"] + + def requires_start(self) -> bool: + """Test if a variable requires a start attribute + + Returns + ------- + True if successful, False otherwise + """ + return ( + self.initial == Fmi3Initial.exact + or self.initial == Fmi3Initial.approx + or self.causality == Fmi3Causality.input + or self.causality == Fmi3Causality.parameter + or self.variability == Fmi3Variability.constant + ) + + def to_xml(self) -> Element: + """Convert the variable to XML node. + + Returns + ------- + xml.etree.ElementTree.Element: XML node + """ + attrib = dict() + for key, value in ChainMap(self._extras, self.__attrs).items(): + if value is not None: + attrib[key] = ModelVariable.to_str(value) + return Element(self._type, attrib) + + @staticmethod + def to_str(val: Any): + """Helper method to translate python values to proper strings for use in xml.""" + if isinstance(val, bool): + return str(val).lower() + if isinstance(val, float): + return f"{val:.16g}" + if isinstance(val, Enum): + return val.name + return str(val) + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(name={self.name}, causality={self.causality}, variability={self.variability})" + ) + + +class Start: + def __init__(self, startValue): + self.value = startValue + + def to_xml(self) -> Element: + attrib = dict() + attrib["value"] = ModelVariable.to_str(self.value) + return Element("Start", attrib) + + +class Dimension: + def __init__(self, start: str = "", valueReference: str = ""): + if start and valueReference and any((start, valueReference)): + raise RuntimeError("start and valueReference attributes are mutally exclusive for Dimension element") + + self.start = start + self.value_reference = valueReference + + def size(self, vars: list[ModelVariable]): + if self.start: + return self.start + result = next( + (value for vr, value in vars.items() if vr == int(self.value_reference)), + None, + ) + return result.getter() + + def to_xml(self) -> Element: + attrib = dict() + + if self.start: + attrib["start"] = str(self.start) + else: + attrib["valueReference"] = str(self.value_reference) + ele = Element("Dimension", attrib) + return ele + + +class Arrayable: + def __init__(self, dimensions: list[Dimension] = [], **kwargs): + if dimensions: + check_numpy() + self._dimensions = dimensions + + @property + def dimensions(self) -> list[Dimension]: + return self._dimensions + + def get_start_str(self, value, formatter=None): + if formatter is None: + formatter = ModelVariable.to_str + if len(self.dimensions) > 0: + output = " ".join([formatter(val) for val in flatten(value)]) + if len(output) > MAX_LENGTH: + output = output[0] + return output + return formatter(value) + + def dimensions_xml(self) -> list[Element]: + return [dim.to_xml() for dim in self._dimensions] + + def size(self, vars): + return reduce(lambda x, dim: x * int(dim.size(vars)), self._dimensions, 1) + + +class Float64(ModelVariable, Arrayable): + """Define a Float64 variable. Serves also as template for all other Float* if _type is adapted.""" + def __init__( + self, + name: str, + start: Any | None = None, + derivative: Any | None = None, + dimensions: list[Dimension] = [], + unit: str | None = None, + _type: str = "Float64", + **kwargs, + ): + ModelVariable.__init__(self, name, **kwargs) + Arrayable.__init__(self, dimensions) + self.__attrs = {"start": start, "derivative": derivative} + self._type = _type + self._unit = unit + + @property + def start(self) -> Any | None: + return self.__attrs["start"] + + @start.setter + def start(self, value: float): + self.__attrs["start"] = value + + @property + def unit(self) -> Any | None: + return self._unit + + @unit.setter + def unit(self, value: str): + self._unit = value + + @property + def derivative(self): + return self.__attrs["derivative"] + + def to_xml(self) -> Element: + attrib = dict() + for key, value in self.__attrs.items(): + if value is not None: + # In order to not loose precision, a number of this type should be + # stored on an XML file with at least 16 significant digits + output = self.get_start_str(value) + attrib[key] = output + + if self.unit: + attrib["unit"] = self.unit + + self._extras = attrib + parent = super().to_xml() + + parent.extend(self.dimensions_xml()) + + return parent + +class Float32(Float64): + def __init__( + self, + name: str, + **kwargs, + ): + super().__init__( name=name, _type="Float32", **kwargs) + +class Int64(ModelVariable, Arrayable): + """Define a Int32 variable. Serves also as template for all other Int* if _type is adapted.""" + def __init__( + self, + name: str, + start: Any | None = None, + dimensions: list[Dimension] = [], + _type: str = "Int64", + **kwargs, + ): + ModelVariable.__init__(self, name, **kwargs) + Arrayable.__init__(self, dimensions, **kwargs) + self.__attrs = {"start": start} + self._type = _type + + @property + def start(self) -> Any | None: + return self.__attrs["start"] + + @start.setter + def start(self, value: int): + self.__attrs["start"] = value + + def to_xml(self) -> Element: + attrib = dict() + for key, value in self.__attrs.items(): + if value is not None: + attrib[key] = self.get_start_str(value) + self._extras = attrib + parent = super().to_xml() + + parent.extend(self.dimensions_xml()) + + return parent + + +class Int32(Int64): + def __init__(self, name: str, **kwargs): + super().__init__(name=name, _type="Int32", **kwargs) + +class Int16(Int64): + def __init__(self,name: str, **kwargs): + super().__init__(name, _type="Int16", **kwargs) + +class Int8(Int64): + def __init__(self, name: str, **kwargs): + super().__init__(name=name, _type="Int8", **kwargs) + + +class UInt64(ModelVariable, Arrayable): + """Define a UInt64 variable. Serves also as template for all other UInt* if _type is adapted.""" + def __init__( + self, + name: str, + start: Any | None = None, + dimensions: list[Dimension] = [], + _type: str = "UInt64", + **kwargs, + ): + ModelVariable.__init__(self, name, **kwargs) + Arrayable.__init__(self, dimensions, **kwargs) + self.__attrs = {"start": start} + self._type = _type + + @property + def start(self) -> Any | None: + return self.__attrs["start"] + + @start.setter + def start(self, value: int): + self.__attrs["start"] = value + + def to_xml(self) -> Element: + attrib = dict() + for key, value in self.__attrs.items(): + if value is not None: + attrib[key] = self.get_start_str(value) + self._extras = attrib + parent = super().to_xml() + + parent.extend(self.dimensions_xml()) + + return parent + +class UInt32(UInt64): + def __init__(self, name:str, **kwargs): + super().__init__(name=name, _type="UInt32", **kwargs) + +class UInt16(UInt64): + def __init__(self, name:str, **kwargs): + super().__init__(name=name, _type="UInt16", **kwargs) + +class UInt8(UInt64): + def __init__(self, name:str, **kwargs): + super().__init__(name=name, _type="UInt8", **kwargs) + +class Boolean(ModelVariable, Arrayable): + def __init__( + self, + name: str, + start: Any | None = None, + dimensions: list[Dimension] = [], + **kwargs, + ): + ModelVariable.__init__(self, name, **kwargs) + Arrayable.__init__(self, dimensions, **kwargs) + self.__attrs = {"start": start} + self._type = "Boolean" + + @property + def start(self) -> Any | None: + return self.__attrs["start"] + + @start.setter + def start(self, value: float): + self.__attrs["start"] = value + + def to_xml(self) -> Element: + attrib = dict() + for key, value in self.__attrs.items(): + if value is not None: + attrib[key] = self.get_start_str(value) + self._extras = attrib + parent = super().to_xml() + + parent.extend(self.dimensions_xml()) + + return parent + + +class String(ModelVariable): + def __init__( + self, + name: str, + start: Any | None = None, + dimensions: list[Dimension] = [], + **kwargs, + ): + ModelVariable.__init__(self, name, **kwargs) + self.__attrs = dict() + self._type = "String" + self._start = Start(start) + + @property + def start(self) -> Any | None: + return self._start.value + + @start.setter + def start(self, value: float): + self._start.value = value + + def to_xml(self) -> Element: + attrib = dict() + for key, value in self.__attrs.items(): + if value is not None: + attrib[key] = str(value) + self._extras = attrib + parent = super().to_xml() + + if self.start is not None: + parent.append(self._start.to_xml()) + return parent + + +class Clock(ModelVariable): + """Clock variable definition. See also fmi3Variable.xsd and fmi3AttributeGroups.xsd/fmi3ClockAttributes + + Args: + name: name of the clock unique within FMU + can_be_deactivated: boolean flag + priority: optional explicit priority as unsigned int + interval_variability: required enumeration attribute, similar to variability + interval_decimal: optional initial specification of decimal interval + field + shift_decimal: optional delay of first clock activations. Default 0 + supports_fraction: optional possibility to provide shifts as integer fractions + resolution: optional initial denominator of interval fraction + interval_counter: optional initial nominator of interval fraction + shift_counter: optional initial nominator of shift (first clock activation) + """ + + def __init__( + self, + name: str, + can_be_deactivated: bool = False, + priority: int | None = None, + interval_variability: Fmi3IntervalVariability = Fmi3IntervalVariability.constant, + interval_decimal: float | None = None, + shift_decimal: float = 0.0, + supports_fraction: bool = False, + resolution: int | None = None, + interval_counter: int | None = None, + shift_counter: int = 0, + **kwargs, + ): + ModelVariable.__init__(self, name, **kwargs) + self.__attrs = { + "canBeDeactivated": can_be_deactivated, + "priority": priority, + "intervalVariability": interval_variability, + "intervalDecimal": interval_decimal, + "shiftDecimal": shift_decimal, + "supportsFraction": supports_fraction, + } + if supports_fraction: + self.__attrs.update( + { + "resolution": resolution, + "intervalCounter": interval_counter, + "shiftCounter": shift_counter, + } + ) + self._type = "Clock" + + def to_xml(self) -> Element: + attrib = dict() + for key, value in self.__attrs.items(): + if value is not None: + attrib[key] = ModelVariable.to_str(value) + self._extras = attrib + parent = super().to_xml() + + return parent + + +class Enumeration(ModelVariable, Arrayable): + def __init__( + self, + name: str, + start: Any | None = None, + declared_type: Any | None = None, + dimensions: list[Dimension] = [], + **kwargs, + ): + ModelVariable.__init__(self, name, **kwargs) + Arrayable.__init__(self, dimensions, **kwargs) + self.__attrs = {"start": start, "declaredType": declared_type} + self._type = "Enumeration" + + @property + def start(self) -> Any | None: + return self.__attrs["start"] + + @start.setter + def start(self, value: float) -> None: + self.__attrs["start"] = value + + @property + def declared_type(self) -> str | None: + return self.__attrs["declaredType"] + + @declared_type.setter + def declared_type(self, value: str) -> None: + self.__attrs["declaredType"] = value + + def to_xml(self) -> Element: + attrib : dict[str,str] = {} + for key, value in self.__attrs.items(): + if value is not None: + attrib[key] = str(value) + self._extras = attrib + parent = super().to_xml() + + return parent + diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..e29e585 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,30 @@ +from pathlib import Path +import pytest +import os, sys + +sys.path.insert(0, str(Path(__file__).parent.resolve())) +from simulation import _simulateCS + + +@pytest.fixture(scope="session", autouse=True) +def chdir(): + """ + Fixture that changes the current working directory to the 'test_working_directory' folder. + This fixture is automatically used for the entire session. + """ + original_cwd = Path.cwd() + os.chdir(Path(__file__).parent.absolute() / "test_working_directory") + try: + yield + finally: + os.chdir(original_cwd) # reset to original working directory after tests + +def pytest_addoption(parser: pytest.Parser): + """Define a parameter 'show', so that results can be shown when running tests 'manually'.""" + parser.addoption("--show", action="store", default=False) + + +@pytest.fixture(scope="session") +def show(request: pytest.FixtureRequest): + return request.config.getoption("--show") == "False" + diff --git a/pythonfmu3/tests/data/csvdemo.csv b/tests/data/csvdemo.csv similarity index 100% rename from pythonfmu3/tests/data/csvdemo.csv rename to tests/data/csvdemo.csv diff --git a/pythonfmu3/tests/data/hello.txt b/tests/data/hello.txt similarity index 100% rename from pythonfmu3/tests/data/hello.txt rename to tests/data/hello.txt diff --git a/tests/helpers.py b/tests/helpers.py new file mode 100644 index 0000000..1011b45 --- /dev/null +++ b/tests/helpers.py @@ -0,0 +1,8 @@ +"""Additional definitions for tests.""" + +from pathlib import Path + +import numpy as np + +EXAMPLES_DIR = Path(__file__).parent.resolve().parent / "examples" +W_DIR = Path(__file__).parent.resolve() / "test_working_directory" diff --git a/tests/simulation.py b/tests/simulation.py new file mode 100644 index 0000000..f6b6918 --- /dev/null +++ b/tests/simulation.py @@ -0,0 +1,227 @@ +from math import isclose +from time import time as current_communication_point + +from fmpy.fmi1 import * +from fmpy.fmi2 import * +from fmpy.simulation import ( + Input, + Recorder, + apply_start_values, + settable_in_initialization_mode, + settable_in_instantiated, +) +from fmpy.util import auto_interval + + +def _simulateCS( + model_description, + fmu, + start_time, + stop_time, + relative_tolerance, + start_values, + apply_default_start_values, + input_signals, + output, + output_interval, + timeout, + step_finished, + set_input_derivatives, + use_event_mode, + early_return_allowed, + validate, + initialize, + terminate, + set_stop_time, +): + """Copy of fmpy.simulation.simulateCS() function, + where we put in hooks to test the implemented event functions. + """ + print(f"RUNNING ADAPTED SIMULATE. events?{use_event_mode}") + nextEventTime: float | None = None + if set_input_derivatives and not model_description.coSimulation.canInterpolateInputs: + raise Exception("Parameter set_input_derivatives is True but the FMU cannot interpolate inputs.") + + if output_interval is None: + output_interval = auto_interval(stop_time - start_time) + + sim_start = current_communication_point() + + is_fmi1 = model_description.fmiVersion == "1.0" + is_fmi2 = model_description.fmiVersion == "2.0" + + can_handle_variable_step_size = model_description.coSimulation.canHandleVariableCommunicationStepSize + + input = Input( + fmu=fmu, modelDescription=model_description, signals=input_signals, set_input_derivatives=set_input_derivatives + ) + + time = start_time + + if initialize: + # initialize the model + if is_fmi1: + start_values = apply_start_values(fmu, model_description, start_values, settable=has_start_value) + input.apply(time) + fmu.initialize(tStart=time, stop_time=stop_time if set_stop_time else None) + elif is_fmi2: + fmu.setupExperiment( + tolerance=relative_tolerance, start_time=time, stop_time=stop_time if set_stop_time else None + ) + start_values = apply_start_values(fmu, model_description, start_values, settable=settable_in_instantiated) + fmu.enterInitializationMode() + start_values = apply_start_values( + fmu, model_description, start_values, settable=settable_in_initialization_mode + ) + input.apply(time) + fmu.exitInitializationMode() + else: + start_values = apply_start_values(fmu, model_description, start_values, settable=settable_in_instantiated) + fmu.enterInitializationMode( + tolerance=relative_tolerance, startTime=time, stopTime=stop_time if set_stop_time else None + ) +# fmu.enterInitializationMode(relative_tolerance, time, stop_time) + start_values = apply_start_values( + fmu, model_description, start_values, settable=settable_in_initialization_mode + ) + input.apply(time) + fmu.exitInitializationMode() + + if use_event_mode: + update_discrete_states = True + + while update_discrete_states: + (update_discrete_states, terminateSimulation, _, _, _nETD, _nET) = fmu.updateDiscreteStates() + + if terminateSimulation: + raise Exception("The FMU requested to terminate the simulation during initialization.") + if _nETD: + nextEventTime = time + _nET + fmu.enterStepMode() + + if validate and len(start_values) > 0: + raise Exception( + "The start values for the following variables could not be set: " + ", ".join(start_values.keys()) + ) + + recorder = Recorder(fmu=fmu, modelDescription=model_description, variableNames=output, interval=output_interval) + + recorder.sample(time, force=True) + + n_steps = 0 + + input_applied = False + + # simulation loop + while True: + if timeout is not None and (current_communication_point() - sim_start) > timeout: + break + + if time > stop_time or isclose(time, stop_time): + break + + next_regular_point = start_time + (n_steps + 1) * output_interval + + next_communication_point = next_regular_point + + next_input_event_time = input.nextEvent(time) + + if ( + can_handle_variable_step_size + and next_communication_point > next_input_event_time + and not isclose(next_communication_point, next_input_event_time) + ): + next_communication_point = next_input_event_time + + if next_communication_point > stop_time and not isclose(next_communication_point, stop_time): + if can_handle_variable_step_size: + next_communication_point = stop_time + else: + break + + input_event = isclose(next_communication_point, next_input_event_time) + + communication_step_size = next_communication_point - time + + if is_fmi1: + input.apply(time, continuous=True, discrete=True, after_event=True) + + fmu.doStep(current_communication_point=time, communication_step_size=communication_step_size) + + time = next_communication_point + + recorder.sample(time) + + elif is_fmi2: + input.apply(time, continuous=True, discrete=True, after_event=True) + + try: + fmu.doStep(current_communication_point=time, communication_step_size=communication_step_size) + + time = next_communication_point + + except FMICallException as exception: + if exception.status == fmi2Discard: + terminateSimulation = fmu.getBooleanStatus(fmi2Terminated) + + if terminateSimulation: + time = fmu.getRealStatus(fmi2LastSuccessfulTime) + recorder.sample(time, force=True) + break + else: + raise exception + + recorder.sample(time) + + else: + input.apply(time, continuous=not input_applied, discrete=not input_applied, after_event=not use_event_mode) + + (event_encountered, terminateSimulation, earlyReturn, last_successful_time) = fmu.doStep( + currentCommunicationPoint=time, + communicationStepSize=communication_step_size, + noSetFMUStatePriorToCurrentPoint=False + ) + if earlyReturn and not early_return_allowed: + raise Exception("FMU returned early from doStep() but Early Return is not allowed.") + + if earlyReturn and last_successful_time < next_communication_point: + time = last_successful_time + else: + time = next_communication_point + + recorder.sample(time) + + if terminateSimulation: + break + + if use_event_mode and (input_event or event_encountered): + fmu.enterEventMode() + + input.apply(time, after_event=True) + + update_discrete_states = True + + while update_discrete_states: + update_discrete_states, terminateSimulation, _, _, _, _ = fmu.updateDiscreteStates() + + if terminateSimulation: + break + + fmu.enterStepMode() + + recorder.sample(time) + + input_applied = True + else: + input_applied = False + + if isclose(time, next_regular_point): + n_steps += 1 + + if step_finished is not None and not step_finished(time, recorder): + break + + if terminate: + fmu.terminate() + + return recorder.result() diff --git a/tests/slaves/PythonSlaveWithException.py b/tests/slaves/PythonSlaveWithException.py new file mode 100644 index 0000000..22a20f1 --- /dev/null +++ b/tests/slaves/PythonSlaveWithException.py @@ -0,0 +1,27 @@ +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.enums import Fmi3Causality, Fmi3Variability +from pythonfmu3.variables import Float64 + +class PythonSlaveWithException(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + + self.realIn = 22.0 + self.realOut = 0.0 + self.time = 0 + + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + self.register_variable(Float64("realIn", causality=Fmi3Causality.input)) + self.register_variable(Float64("realOut", causality=Fmi3Causality.output)) + + def do_step(self, + currentCommunicationPoint: float, + communicationStepSize: float, + noSetFMUStatePriorToCurrentPoint: bool): + raise RuntimeError diff --git a/pythonfmu3/tests/slaves/localmodule.py b/tests/slaves/localmodule.py similarity index 79% rename from pythonfmu3/tests/slaves/localmodule.py rename to tests/slaves/localmodule.py index fc7f52a..ec14542 100644 --- a/pythonfmu3/tests/slaves/localmodule.py +++ b/tests/slaves/localmodule.py @@ -1,7 +1,5 @@ - - def get_amplitude(): - return 5. + return 5.0 def get_time_constant(): diff --git a/tests/slaves/pythonslave.py b/tests/slaves/pythonslave.py new file mode 100644 index 0000000..ae381f6 --- /dev/null +++ b/tests/slaves/pythonslave.py @@ -0,0 +1,81 @@ +from pythonfmu3.enums import Fmi3Causality, Fmi3Variability +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.model_returns import Fmi3StepResult +from pythonfmu3.variables import Boolean, Float64, Int32, String + + +class Container: + pass + + +class PythonSlave(Fmi3Slave): + author = "John Doe" + description = "A simple description" + + def __init__(self, + + **kwargs): + super().__init__(**kwargs) + + self.intParam = 42 + self.intOut = 23 + self.realOut = 3.0 + self.booleanVariable = True + self.stringVariable = "Hello World!" + self.realIn = 2.0 / 3.0 + self.booleanParameter = False + self.stringParameter = "dog" + self.time = 0 + + self.register_variable( + Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous) + ) + self.register_variable( + Int32("intParam", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable) + ) + self.register_variable(Float64("realIn", causality=Fmi3Causality.input)) + self.register_variable( + Boolean("booleanParameter", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable) + ) + self.register_variable( + String("stringParameter", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable) + ) + + self.register_variable(Int32("intOut", causality=Fmi3Causality.output)) + self.register_variable(Float64("realOut", causality=Fmi3Causality.output)) + self.register_variable(Boolean("booleanVariable", causality=Fmi3Causality.local)) + self.register_variable(String("stringVariable", causality=Fmi3Causality.local)) + + self.container = Container() + self.container.someReal = 99.0 + self.container.subContainer = sub = Container() + sub.someInteger = -15 + self.register_variable( + Float64("container.someReal", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable) + ) + self.register_variable( + Int32("container.subContainer.someInteger", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.tunable, + ) + ) + + def do_step( + self, current_time: float, step_size: float, no_set_fmu_state_prior_to_current_point: bool) -> Fmi3StepResult: + self.realOut = current_time + step_size + return True + +if __name__ == "__main__": + from pathlib import Path + from pythonfmu3.builder import FmuBuilder + from fmpy import read_model_description + + dest = FmuBuilder.build_FMU( + script_file = Path(__file__), + dest = Path(__file__).parent.resolve(), + #project_files: Iterable[FilePath] = set(), + #documentation_folder: Optional[FilePath] = None, + #terminals : Optional[FilePath] = None, + ) + read_model_description(dest, True, True, True) + print(f"Generated {dest}. Validated modelDescription.") diff --git a/tests/slaves/pythonslaveMX.py b/tests/slaves/pythonslaveMX.py new file mode 100644 index 0000000..68c117a --- /dev/null +++ b/tests/slaves/pythonslaveMX.py @@ -0,0 +1,53 @@ +from pythonfmu3.variables import Float64 +from pythonfmu3.enums import Fmi3Causality, Fmi3Initial, Fmi3Variability +from pythonfmu3.fmi3slave import Fmi3SlaveBase +from pythonfmu3.modelexchange import ModelExchange + + +class Dahlquist(Fmi3SlaveBase, ModelExchange): + def __init__(self, **kwargs): + super().__init__(**kwargs) + + self.author = "Stephen Smith" + self.description = "Dahlquist's test problem for model exchange FMUs" + + self.time = 0.0 + self.k = 1.0 + self.x = 1.0 + self.derx = 0.0 + + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + self.register_variable( + Float64( + "x", + causality=Fmi3Causality.output, + start=1, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ) + ) + self.register_variable( + Float64( + "derx", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=1, + ) + ) + self.register_variable( + Float64( + "k", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.fixed, + ) + ) + + def get_continuous_state_derivatives(self) -> list[float]: + self.derx = -self.k * self.x + return [self.derx] diff --git a/tests/slaves/pythonslaveMXCS.py b/tests/slaves/pythonslaveMXCS.py new file mode 100644 index 0000000..78de97b --- /dev/null +++ b/tests/slaves/pythonslaveMXCS.py @@ -0,0 +1,61 @@ +from pythonfmu3.cosimulation import CoSimulation +from pythonfmu3.enums import Fmi3Causality, Fmi3Initial, Fmi3Variability +from pythonfmu3.fmi3slave import Fmi3SlaveBase +from pythonfmu3.model_returns import Fmi3StepResult +from pythonfmu3.modelexchange import ModelExchange +from pythonfmu3.variables import Float64 + + +class Dahlquist(Fmi3SlaveBase, ModelExchange, CoSimulation): + def __init__(self, **kwargs): + super().__init__(**kwargs) + + self.author = "Stephen Smith" + self.description = "Dahlquist's test problem for model exchange FMUs" + + self.time = 0.0 + self.k = 1.0 + self.x = 1.0 + self.derx = 0.0 + + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + self.register_variable( + Float64( + "x", + causality=Fmi3Causality.output, + start=1, + variability=Fmi3Variability.continuous, + initial=Fmi3Initial.exact, + ) + ) + self.register_variable( + Float64( + "derx", + causality=Fmi3Causality.local, + variability=Fmi3Variability.continuous, + derivative=1, + ) + ) + self.register_variable( + Float64( + "k", + causality=Fmi3Causality.parameter, + variability=Fmi3Variability.fixed, + ) + ) + + def get_continuous_state_derivatives(self) -> list[float]: + self.derx = -self.k * self.x + return [self.derx] + + def do_step(self, current_time: float, step_size: float, noSetFMUStatePriorToCurrentPoint:bool) -> Fmi3StepResult: + self.time = current_time + step_size + self.derx = -self.k * self.x + self.x += self.derx * step_size + return True diff --git a/tests/slaves/pythonslave_arraytypes.py b/tests/slaves/pythonslave_arraytypes.py new file mode 100644 index 0000000..a179d17 --- /dev/null +++ b/tests/slaves/pythonslave_arraytypes.py @@ -0,0 +1,96 @@ +import numpy as np + +from pythonfmu3.enums import Fmi3Causality, Fmi3Status, Fmi3Variability +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.variables import Boolean, Dimension, Float64, Int32, Int64, UInt64 + +SIZE = 10 + +TYPES = [UInt64, Float64, Boolean, Int32, Int64] +CAUSALITY = [Fmi3Causality.output, Fmi3Causality.input] + +TYPE_MAP = { + UInt64: np.uint64, + Float64: np.float64, + Int32: np.int32, + Int64: np.int64, + Boolean: bool, +} + + +def var_names(var_type, causality): + return f"{var_type.__name__.lower()}_{causality.name.lower()}" + + +def init_var(var_type, causality, array=True): + if array: + return np.zeros(SIZE, dtype=TYPE_MAP[var_type]) + return TYPE_MAP[var_type]() + + +def create_vars(self): + dimensions = [Dimension(start=str(SIZE))] + for var_type in TYPES: + for causality in CAUSALITY: + name = var_names(var_type, causality) + if var_type == Float64: + var = var_type( + name, + causality=causality, + variability=Fmi3Variability.continuous, + dimensions=dimensions, + ) + else: + var = var_type( + name, + causality=causality, + variability=Fmi3Variability.discrete, + dimensions=dimensions, + ) + setattr(self, name, init_var(var_type, causality)) + self.register_variable(var) + + +def generate_data(self): + for var_type in TYPES: + causality = Fmi3Causality.output + name = var_names(var_type, causality) + var = getattr(self, name) + if var_type == Boolean: + data = [False, True, False, True, True, False, False, True, False, True] + setattr(self, name, np.array(data).astype(bool)) + elif var_type == Int32 or var_type == Int64 or var_type == UInt64: + data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + setattr(self, name, np.array(data).astype(TYPE_MAP[var_type])) + else: + data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] + setattr(self, name, np.array(data).astype(TYPE_MAP[var_type])) + + +class ArrayTypes(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + + self.author = "Tester" + self.description = "FMU with all basic types as arrays" + + self.time = 0.0 + + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + + create_vars(self) + + generate_data(self) + + def do_step(self, + currentCommunicationPoint: float, + communicationStepSize: float, + noSetFMUStatePriorToCurrentPoint: bool) -> Fmi3Status: + generate_data(self) + return True diff --git a/tests/slaves/pythonslave_read_file.py b/tests/slaves/pythonslave_read_file.py new file mode 100644 index 0000000..7a5429f --- /dev/null +++ b/tests/slaves/pythonslave_read_file.py @@ -0,0 +1,38 @@ +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.default_experiment import DefaultExperiment +from pythonfmu3.enums import Fmi3Causality, Fmi3Variability +from pythonfmu3.model_returns import Fmi3StepResult +from pythonfmu3.variables import Float64, String + +class PythonSlaveReadFile(Fmi3Slave): + default_experiment = DefaultExperiment(start_time=0) + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + with open(f"{self.resources}/hello.txt") as file: + data = file.read() + + self.time = 0 + + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + self.register_variable( + String( + "file_content", + getter=lambda: data, + causality=Fmi3Causality.output, + variability=Fmi3Variability.constant, + ) + ) + + def do_step(self, + currentCommunicationPoint: float, + communicationStepSize: float, + noSetFMUStatePriorToCurrentPoint: bool): + return Fmi3StepResult() diff --git a/tests/slaves/slavewithdep.py b/tests/slaves/slavewithdep.py new file mode 100644 index 0000000..d15ee53 --- /dev/null +++ b/tests/slaves/slavewithdep.py @@ -0,0 +1,34 @@ +import math + +from localmodule import get_amplitude, get_time_constant + +from pythonfmu3.enums import Fmi3Causality, Fmi3Variability +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.model_returns import Fmi3StepResult +from pythonfmu3.variables import Float64 + + +class PythonSlaveWithDep(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + + self.realIn = 22.0 + self.realOut = 0.0 + self.time = 0 + + self.register_variable( + Float64( + "time", + causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous, + ) + ) + self.register_variable(Float64("realIn", causality=Fmi3Causality.input)) + self.register_variable(Float64("realOut", causality=Fmi3Causality.output)) + + def do_step(self, + currentCommunicationPoint: float, + communicationStepSize: float, + noSetFMUStatePriorToCurrentPoint: bool): + self.realOut = self.realIn * get_amplitude() * math.exp((currentCommunicationPoint + communicationStepSize) / get_time_constant()) + return Fmi3StepResult() diff --git a/pythonfmu3/tests/test_builder.py b/tests/test_builder.py similarity index 59% rename from pythonfmu3/tests/test_builder.py rename to tests/test_builder.py index 09de7df..6eb7b22 100644 --- a/pythonfmu3/tests/test_builder.py +++ b/tests/test_builder.py @@ -1,3 +1,5 @@ +import argparse +from helpers import W_DIR import itertools import platform import tempfile @@ -5,9 +7,13 @@ from pathlib import Path import pytest +from attrs import asdict +from fmpy import read_model_description import pythonfmu3 -from pythonfmu3.builder import FmuBuilder, get_platform +from pythonfmu3.deploy import create_command_parser +from pythonfmu3.builder import FmuBuilder, get_platform, create_command_parser +from pythonfmu3.fmi3slave import Fmi3ModelOptionsCS PROJECT_TEST_CASES = [ ("dummy.txt",), @@ -16,17 +22,14 @@ ("dummy.py", "subdir/dummy.txt", "subdir2/dummy2.txt"), ] +lib_extension = ({"Darwin": "dylib", "Linux": "so", "Windows": "dll"}).get(platform.system()) -lib_extension = ({"Darwin": "dylib", "Linux": "so", "Windows": "dll"}).get( - platform.system(), None -) - -def test_zip_content(tmp_path): +def test_zip_content(): script_name = "pythonslave.py" script_file = Path(__file__).parent / "slaves" / script_name - fmu = FmuBuilder.build_FMU(script_file, dest=tmp_path) + fmu = FmuBuilder.build_FMU(script_file, dest=W_DIR) assert fmu.exists() assert zipfile.is_zipfile(fmu) @@ -40,10 +43,7 @@ def test_zip_content(tmp_path): nfiles = 20 if FmuBuilder.has_binary(): - assert ( - "/".join(("binaries", get_platform(), f"PythonSlave.{lib_extension}")) - in names - ) + assert "/".join(("binaries", get_platform(), f"PythonSlave.{lib_extension}")) in names else: nfiles -= 1 @@ -72,9 +72,10 @@ def test_zip_content(tmp_path): @pytest.mark.parametrize("pfiles", PROJECT_TEST_CASES) -def test_project_files(tmp_path, pfiles): +def test_project_files(pfiles): pfiles = map(Path, pfiles) script_file = Path(__file__).parent / "slaves/pythonslave.py" + def build(): with tempfile.TemporaryDirectory() as project_dir: project_dir = Path(project_dir) @@ -100,7 +101,7 @@ def build(): project_files.remove(to_remove) project_files.add(full_name.parent) - return FmuBuilder.build_FMU(script_file, dest=tmp_path, project_files=project_files) + return FmuBuilder.build_FMU(script_file, dest=W_DIR, project_files=project_files) fmu = build() with zipfile.ZipFile(fmu) as files: @@ -138,9 +139,7 @@ def build(): else: full_name.mkdir(parents=True, exist_ok=True) - return FmuBuilder.build_FMU( - script_file, dest=tmp_path, project_files=[script_file.parent] - ) + return FmuBuilder.build_FMU(script_file, dest=tmp_path, project_files=[script_file.parent]) fmu = build() with zipfile.ZipFile(fmu) as files: @@ -160,6 +159,7 @@ def build(): def test_documentation(tmp_path): script_file = Path(__file__).parent / "slaves/pythonslave.py" + def build(): with tempfile.TemporaryDirectory() as documentation_dir: doc_dir = Path(documentation_dir) @@ -180,6 +180,7 @@ def build(): def test_terminals(tmp_path): script_file = Path(__file__).parent / "slaves/pythonslave.py" + def build(): with tempfile.TemporaryDirectory() as terminals_dir: terminals_dir = Path(terminals_dir) @@ -191,5 +192,93 @@ def build(): fmu = build() with zipfile.ZipFile(fmu) as files: names = files.namelist() - assert "terminalsAndIcons/terminalsAndIcons.xml" in names + + +def test_cli(): + def default_execution(**kwargs): + print("A subcommand must be provided.\n") + parser.print_help() + + parser = argparse.ArgumentParser(prog="pythonfmu") + parser.add_argument("-V", "--version", action="version", version="9.9.9") + + parser.set_defaults(execute=default_execution) + + subparsers = parser.add_subparsers( + title="Subcommands", + description="Call `pythonfmu _command_ -h` to get more help.", + ) + + build_parser = subparsers.add_parser( + "build", + description="Build an FMU from a Python script.", + help="Build an FMU from a Python script.", + ) + create_command_parser(build_parser) + + deploy_parser = subparsers.add_parser( + "deploy", + description="""Deploy a Python FMU. + + The command will look in the `resources` folder for one of the following files: + `requirements.txt` or `environment.yml`. + + If you specify a environment file but no package manager, `conda` will be selected + for `.yaml` and `.yml` otherwise `pip` will be used. + + The tool assume the Python environment in which the FMU should be executed + is the current one. + """, + help="Install Python FMU dependencies.", + ) + create_command_parser(deploy_parser) + + options = vars(parser.parse_args()) + + py_file = Path(__file__).parent.resolve().parent / "examples/two_state.py" + # cmd = f" build -f {py_file}" + # print("CMD", cmd) + args = parser.parse_args(["build", "-f", str(py_file), "--hasEventMode", "--fixedInternalStepSize", "0.01"]) + assert args.script_file == str(py_file) + assert not args.needsExecutionTool + assert args.hasEventMode + + assert isinstance(vars(args), dict), "Arguments converted to dict, which is also used in cli" + + dest = FmuBuilder.build_FMU( + script_file=py_file, + dest=Path(__file__).parent.resolve() / "test_working_directory", + # project_files: Iterable[FilePath] = set(), + # documentation_folder: Optional[FilePath] = None, + # terminals : Optional[FilePath] = None, + options={"hasEventMode": False, "canHandleVariableCommunicationStepSize": False}, + ) + md = read_model_description(dest, True, True, True) + dct = asdict(md.coSimulation) + assert not dct["hasEventMode"], f"'hasEventMode' is {dct['hasEventMode']}!" + assert not dct["canHandleVariableCommunicationStepSize"], f"{dct['canHandleVariableCommunicationStepSize']}!" + print(f"Generated {dest}. Validated modelDescription.") + + +def test_model_options(): + mcs = Fmi3ModelOptionsCS(hasEventMode=True, fixedInternalStepSize=0.01) + assert mcs.hasEventMode + assert mcs.fixedInternalStepSize == 0.01 + assert not mcs.providesAdjointDerivatives + assert not mcs.to_dict()["needsExecutionTool"], "Can access all options as dict" + mcs = Fmi3ModelOptionsCS(hasEventMode=True) + assert "fixedInternalStepSize" not in mcs.to_dict(w_none=False), "Not listed because it is None" + assert "needsExecutionTool" in mcs.to_dict(), "Listed even if default value" + assert "needsExecutionTool" not in mcs.to_dict(w_default=False), "Not listed because default value" + + +if __name__ == "__main__": + """Possibility to run single or all tests from the IDE.""" + retcode = 1 + if retcode == 0: + retcode = pytest.main(["-rA", "-v", "--rootdir", "../", "--show", "False", __file__]) + assert retcode == 0, f"Non-zero return code {retcode}" + test_zip_content() + # test_cli() + # test_model_options() diff --git a/pythonfmu3/tests/test_deploy.py b/tests/test_deploy.py similarity index 85% rename from pythonfmu3/tests/test_deploy.py rename to tests/test_deploy.py index 90df2f3..8bffb36 100644 --- a/pythonfmu3/tests/test_deploy.py +++ b/tests/test_deploy.py @@ -9,9 +9,11 @@ PYTHON_SLAVE = Path(__file__).parent / "slaves/pythonslave.py" + @pytest.mark.parametrize("test_manager", [None, "pip", "conda"]) @pytest.mark.parametrize( - "requirements, test_requirements, expected", [ + "requirements, test_requirements, expected", + [ (None, None, ValueError), (None, "requirements.txt", ValueError), (None, "environment.yaml", ValueError), @@ -20,7 +22,7 @@ ("environment.yml", None, "conda"), ("req.txt", "req.txt", "pip"), ("env.yml", "env.yml", "conda"), - ] + ], ) def test_deploy(tmp_path, test_manager, requirements, test_requirements, expected): @@ -31,7 +33,13 @@ def test_deploy(tmp_path, test_manager, requirements, test_requirements, expecte with TemporaryDirectory() as tempd: requirements_file = Path(tempd) / requirements requirements_file.write_text(dummy_requirements) - fmu = FmuBuilder.build_FMU(PYTHON_SLAVE, dest=tmp_path, project_files=[requirements_file, ]) + fmu = FmuBuilder.build_FMU( + PYTHON_SLAVE, + dest=tmp_path, + project_files=[ + requirements_file, + ], + ) else: fmu = FmuBuilder.build_FMU(PYTHON_SLAVE, dest=tmp_path) assert fmu.exists() diff --git a/pythonfmu3/tests/test_docs.py b/tests/test_docs.py similarity index 50% rename from pythonfmu3/tests/test_docs.py rename to tests/test_docs.py index 2c8907c..4f2bcc7 100644 --- a/pythonfmu3/tests/test_docs.py +++ b/tests/test_docs.py @@ -1,31 +1,33 @@ -import pytest import pathlib import re -import tempfile + +import pytest + def extract_python_code_from_md(md_file): """Extract Python code blocks from markdown, excluding skip blocks""" content = pathlib.Path(md_file).read_text() - + # Find all python code blocks that aren't marked as skip python_blocks = [] - + # Pattern to match python blocks but not python skip - pattern = r'```python(?!\s+skip)(?:[^\n]*)\n(.*?)\n```' + pattern = r"```python(?!\s+skip)(?:[^\n]*)\n(.*?)\n```" matches = re.findall(pattern, content, re.DOTALL) - + for match in matches: # Skip blocks that are wrapped in skip-test comments - if '' not in content.split(match)[0][-100:]: + if "" not in content.split(match)[0][-100:]: python_blocks.append(match) - + return python_blocks + @pytest.mark.doc def test_readme(): - test_dir = pathlib.Path(__file__).parent - fpath = test_dir.parent.parent / "README.md" - + test_dir = pathlib.Path(__file__).parent.resolve() + fpath = test_dir.parent / "README.md" + # extract Python code code_blocks = extract_python_code_from_md(fpath) @@ -35,64 +37,73 @@ def test_readme(): for i, code in enumerate(code_blocks): try: exec(code, namespace) - print(f"✅ Code block {i+1} executed successfully") + print(f"✅ Code block {i + 1} executed successfully") except Exception as e: - pytest.fail(f"Code block {i+1} failed: {e}\nCode:\n{code}") - - + pytest.fail(f"Code block {i + 1} failed: {e}\nCode:\n{code}") @pytest.mark.doc def test_cosimulation_examples(): """Test that all Python examples in usage.md actually work""" - test_dir = pathlib.Path(__file__).parent - usage_file = test_dir.parent.parent / "docs" / "usage.md" - + test_dir = pathlib.Path(__file__).parent.resolve() + usage_file = test_dir.parent / "docs/source/usage.md" + # Extract Python code code_blocks = extract_python_code_from_md(usage_file) - + # Create a test namespace namespace = {} exec("from pythonfmu3 import *", namespace) - + # Execute each code block for i, code in enumerate(code_blocks): try: exec(code, namespace) - print(f"✅ Code block {i+1} executed successfully") + print(f"✅ Code block {i + 1} executed successfully") except Exception as e: - pytest.fail(f"Code block {i+1} failed: {e}\nCode:\n{code}") - - assert 'LinearTransform' in namespace, "LinearTransform class not found" - assert 'PIDController' in namespace, "PIDController class not found" + pytest.fail(f"Code block {i + 1} failed: {e}\nCode:\n{code}") + + assert "LinearTransform2x2" in namespace, "LinearTransform2x2 class not found" + assert "PIDController" in namespace, "PIDController class not found" # Test instantiation - lt = namespace['LinearTransform'](instance_name="test") - pc = namespace['PIDController'](instance_name="test") + lt = namespace["LinearTransform2x2"](instanceName="test") + pc = namespace["PIDController"](instanceName="test") @pytest.mark.doc def test_model_exchange_examples(): """Test Model Exchange examples""" - test_dir = pathlib.Path(__file__).parent - mx_file = test_dir.parent.parent / "docs" / "usageMX.md" - + test_dir = pathlib.Path(__file__).parent.resolve() + mx_file = test_dir.parent / "docs/source/usageMX.md" + code_blocks = extract_python_code_from_md(mx_file) - + namespace = {} exec("from pythonfmu3 import *", namespace) - + for i, code in enumerate(code_blocks): + print("CODE", i, code) try: exec(code, namespace) except Exception as e: - pytest.fail(f"MX Code block {i+1} failed: {e}") - + pytest.fail(f"MX Code block {i + 1} failed: {e}") + # Test that classes were actually created - assert 'VanDerPol' in namespace, "VanDerPol class not found" - assert 'BouncingBall' in namespace, "BouncingBall class not found" - + assert "VanDerPol" in namespace, "VanDerPol class not found" + assert "BouncingBall" in namespace, "BouncingBall class not found" + # Test instantiation - vdp = namespace['VanDerPol'](instance_name="test") - - bb = namespace['BouncingBall'](instance_name="test") \ No newline at end of file + vdp = namespace["VanDerPol"](instanceName="test") + bb = namespace["BouncingBall"](instanceName="test") + +if __name__ == "__main__": + """Possibility to run single or all tests from the IDE.""" + retcode = 0 + if retcode == 0: + retcode = pytest.main(["-rA", "-v", "--rootdir", "../", "--show", "False", __file__]) + assert retcode == 0, f"Non-zero return code {retcode}" + + test_readme() + # test_cosimulation_examples() + # test_model_exchange_examples() \ No newline at end of file diff --git a/tests/test_event_functions.py b/tests/test_event_functions.py new file mode 100644 index 0000000..85c2e1b --- /dev/null +++ b/tests/test_event_functions.py @@ -0,0 +1,45 @@ +# Example of co-simulation setup +from pathlib import Path + +import fmpy +import matplotlib.pyplot as plt +from fmpy import simulate_fmu +from helpers import EXAMPLES_DIR +from simulation import _simulateCS + +fmpy.simulation.simulateCS = _simulateCS + + +def test_run(show: bool): + # Simulate the PID controller FMU + result = simulate_fmu( + filename=EXAMPLES_DIR / "TwoState.fmu", + start_time=0.0, + stop_time=10.0, + step_size=0.01, + start_values={"mttf": 0.9005, "mttr": 0.0995, "seed": 1, "deterministic": True}, + output=["state"], + use_event_mode=True, + ) + + if show: + # Plot results + plt.figure(figsize=(12, 6)) + plt.subplot() + plt.plot(result["time"], result["state"], label="State") + # plt.plot(result['time'], result['measurement'], label='Measurement') + plt.ylabel("Value") + plt.legend() + plt.grid(True) + plt.show() + + assert result['time'][-1] == 10.0 + assert abs( sum(x for x in result['state'])/len(result['time']) - 0.8959537572254336) < 1e-10 + + +if __name__ == "__main__": + retcode = 1 + if retcode == 0: + retcode = pytest.main(["-rA", "-v", "--rootdir", "../", "--show", "False", __file__]) + assert retcode == 0, f"Non-zero return code {retcode}" + test_run(show=True) diff --git a/tests/test_fmi3slave.py b/tests/test_fmi3slave.py new file mode 100644 index 0000000..4c0f80d --- /dev/null +++ b/tests/test_fmi3slave.py @@ -0,0 +1,200 @@ +from importlib.metadata import version +import logging +import pytest + +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.modelexchange import ModelExchange +from pythonfmu3.variables import py_types, fmi_type, fmi_type_version + +LOGGER = logging.getLogger(__name__) +logging.basicConfig(level=logging.INFO) + +# TODO test xml + +implemented = ("Boolean","String","Float64","Int64","Int32","UInt64") # implement the others in cpp and fmi3slave + +def example( _type:str): + """Provide an example value for the FMI _type as str.""" + if _type=='Enumeration' or 'int' in _type.lower(): + return py_types[_type](3) + elif _type == "Real" or 'float' in _type.lower(): + return py_types[_type](9.9) + elif _type in ("Boolean", "Clock"): + return True + elif _type=='String': + return 'Hello World' + else: + raise KeyError(f"Unknown FMI type {_type}") + +@pytest.mark.parametrize("model", ["theModelName", None]) +def test_fmi3slave_constructor(model): + + class Slave(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + if model is not None: + self.modelName = model + + def do_step(self, t, dt): + return True + + if model is None: + slave = Slave(instanceName="slaveInstance") + assert slave.modelName == "Slave" + assert slave.instance_name == "slaveInstance" + else: + slave = Slave(instanceName="slaveInstance") + assert slave.modelName == model + assert slave.instance_name == "slaveInstance" + + +def test_fmi3slave_generation_tool(): + class Slave(Fmi3Slave): + def do_step(self, t, dt): + return True + + slave = Slave(instanceName="instance") + xml = slave.to_xml() + + assert xml.attrib["generationTool"] == f"PythonFMU3 {version('PythonFMU3')}" + + +def test_fmi3slave_getters(): + + class Slave(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.var = value + print("MAKE", fmi_typ) + self.register_variable(fmi_typ(name = "var")) + + def do_step(self, t, dt): + return True + + for fmi_type_name, py_type in py_types.items(): + if fmi_type_version(fmi_type_name, 3) and fmi_type_name not in implemented: + LOGGER.error(f"FMI type {fmi_type_name} is not yet fully implemented. Skip.") + elif fmi_type_version(fmi_type_name, 3): + value = example(fmi_type_name) + fmi_typ = fmi_type(fmi_type_name) + slave = Slave(instanceName="slaveInstance") + + if type(value) is py_type: + assert getattr(slave, f"get_{fmi_type_name.lower()}")([0]) == [value] + else: + with pytest.raises(TypeError): + getattr(slave, f"get_{fmi_type_name.lower()}")([0]) + + +def test_fmi3slave_setters(): + + class Slave(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.var = None + self.register_variable(fmi_typ(name="var")) + + def do_step(self, t, dt): + return True + + for fmi_type_name, py_type in py_types.items(): + if fmi_type_version(fmi_type_name, 3) and fmi_type_name not in implemented: + LOGGER.error(f"FMI type {fmi_type_name} is not yet fully implemented. Skip.") + elif fmi_type_version(fmi_type_name, 3): + value = example(fmi_type_name) + fmi_typ = fmi_type(fmi_type_name) + slave = Slave(instanceName="slaveInstance") + + if type(value) is py_type: + set_method = getattr(slave, f"set_{fmi_type_name.lower()}") + set_method([0], [value]) + assert getattr(slave, f"get_{fmi_type_name.lower()}")([0]) == [value] + else: + set_method = getattr(slave, f"set_{fmi_type_name.lower()}") + with pytest.raises(TypeError): + set_method([0], [value]) + + +def test_fmi3slave_log_categories(): + class Slave(Fmi3Slave): + def do_step(self, t, dt): + return True + + slave = Slave(instanceName="instance") + xml = slave.to_xml() + + categories = xml.find("LogCategories") + assert len(categories) == len(Slave.log_categories) + for category, description in Slave.log_categories.items(): + assert categories.find(f"Category[@name='{category}'][@description='{description}']") is not None + + +@pytest.mark.parametrize( + "new_categories", + [ + { + "logStatusWarning": "Log messages with fmi3Warning status.", + "logStatusError": "Log messages with fmi3Error status.", + "logStatusFatal": "Log messages with fmi3Fatal status.", + "logAll": "Log all messages.", + }, + { + "logCustom1": "My first custom log category", + "logCustom2": "My second custom log category", + }, + ], +) +def test_fmi3slave_customized_log_categories(new_categories): + class Slave(Fmi3Slave): + log_categories = new_categories + + def do_step(self, t, dt): + return True + + slave = Slave(instanceName="instance") + xml = slave.to_xml() + + categories = xml.find("LogCategories") + + if len(new_categories) > 0: + assert len(categories) == len(Slave.log_categories) + for category, description in Slave.log_categories.items(): + assert categories.find(f"Category[@name='{category}'][@description='{description}']") is not None + else: + assert categories is None + + +def test_fmi3slave_model_exchange(): + class Slave(Fmi3Slave, ModelExchange): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.time = 0.0 + + def get_continuous_state_derivatives(self, vals): + return [] + + slave = Slave(instanceName="instance") + xml = slave.to_xml() + + categories = xml.find("ModelExchange") + + assert categories is not None, "ModelExchange category should be present in the XML" + +if __name__ == "__main__": + """Possibility to run single or all tests from the IDE.""" + retcode = 0 + if retcode == 0: + retcode = pytest.main(["-rA", "-v", "--rootdir", "../", "--show", "False", __file__]) + assert retcode == 0, f"Non-zero return code {retcode}" + + # test_fmi3slave_constructor("theModelName") + # test_fmi3slave_constructor(None) + # test_fmi3slave_getters() + # test_fmi3slave_setters() + # test_fmi3slave_generation_tool() + # test_fmi3slave_log_categories() + # test_fmi3slave_customized_log_categories( + # {"logStatusWarning":"Log warning","logStatusError":"Log error","logStatusFatal":"Log fatal","logAll":"Log all"}) + #test_fmi3slave_customized_log_categories({"logCustom1": "Custom log 1", "logCustom2": "Custom log 2"}) + + diff --git a/tests/test_fmus.py b/tests/test_fmus.py new file mode 100644 index 0000000..0009e3e --- /dev/null +++ b/tests/test_fmus.py @@ -0,0 +1,275 @@ +"""Test some FMUs using fmpy.""" + +import logging +from pathlib import Path +import pytest + +import fmpy +import matplotlib.pyplot as plt +import numpy as np +from fmpy import simulate_fmu +from simulation import _simulateCS + +fmpy.simulation.simulateCS = _simulateCS + +logging.basicConfig(level=logging.INFO) +LOGGER = logging.getLogger(__name__) + +EXAMPLES_DIR = Path(__file__).resolve().parent.parent / "examples" + + +def do_show( + x: list | np.ndarray, + y: list | np.ndarray, + label: str, + x2: list | np.ndarray | None = None, + y2: list | np.ndarray | None = None, + label2: str = "", +): + plt.figure(figsize=(12, 6)) + plt.subplot(2, 1, 1) + plt.plot(x, y, label=label) + plt.xlabel("Time") + plt.ylabel("Value") + plt.legend() + plt.grid(True) + + if x2 is not None and y2 is not None: + plt.subplot(2, 1, 2) + plt.plot(x2, y2, label=label2) + plt.xlabel("Time") + plt.ylabel("Value2") + plt.legend() + plt.grid(True) + plt.show() + + +def test_function(*, show: bool): + """Test the Function.fmu in isolation.""" + fmu_file = EXAMPLES_DIR / "Function.fmu" + assert fmu_file.exists() + result = simulate_fmu( + filename=fmu_file, + start_time=0.0, + stop_time=10.0, + step_size=0.01, + start_values={ + "func_name": "sum", + "inputs": "1.0 5.0", + }, + # input= np.array( [(0.0, 0.0, 1.0), (1.0, 0.3, 1.0), (5.0, 0.8, 1.0), (10.0, 1.0, 1.0)], + # dtype=[('time', np.double),('inputs[0]', np.double), ('inputs[1]', np.double)]), + output=["output"], + ) + assert all(_sum == 6 for _sum in result["output"][2:]) + LOGGER.warning("TODO: find out how to provide input to array inputs") + if show: + do_show(result["time"], result["output"], label="Output") + + +def test_table(*, show: bool): + """Test the Table.fmu in isolation.""" + fmu_file = EXAMPLES_DIR / "Table.fmu" + assert fmu_file.exists() + result = simulate_fmu( + filename=fmu_file, + start_time=0.0, + stop_time=10.0, + step_size=0.01, + start_values={}, + # input= np.array( [(0.0, 0.0, 1.0), (1.0, 0.3, 1.0), (5.0, 0.8, 1.0), (10.0, 1.0, 1.0)], + # dtype=[('time', np.double),('inputs[0]', np.double), ('inputs[1]', np.double)]), + output=["outputs"], + use_event_mode=True, + ) + if show: + do_show(result["time"], result["outputs"], label="Outputs") + assert result['time'][-1] == 10.0 + assert abs( sum(x[0] for x in result['outputs'])/len(result['time']) - 4.563) < 1e-3 + assert abs( sum(x[1] for x in result['outputs'])/len(result['time']) - 29.166) < 1e-3 + +def test_function(*, show: bool): + """Test the Function.fmu in isolation.""" + fmu_file = EXAMPLES_DIR / "Function.fmu" + assert fmu_file.exists() + result = simulate_fmu( + filename=fmu_file, + start_time=0.0, + stop_time=10.0, + step_size=0.01, + start_values={ + "func_name": "sum", + "inputs": "1.0 5.0", + }, + # input= np.array( [(0.0, 0.0, 1.0), (1.0, 0.3, 1.0), (5.0, 0.8, 1.0), (10.0, 1.0, 1.0)], + # dtype=[('time', np.double),('inputs[0]', np.double), ('inputs[1]', np.double)]), + output=["output"], + ) + assert all(_sum == 6 for _sum in result["output"][2:]) + + +def test_linear_transform(): + fmu_file = EXAMPLES_DIR / "LinearTransform.fmu" + assert fmu_file.exists() + result = simulate_fmu( + filename=fmu_file, + start_time=0.0, + stop_time=10.0, + step_size=0.1, + start_values={ + "a": 2.0, + "b": 3.0, + "x": 9.0, + }, + output=["y"], + use_event_mode=True, + ) + assert all(_y == 2.0 + 3.0 * 9.0 for _y in result["y"][2:]) + + +def test_two_state(*, show: bool): + """Test the TwoState.fmu simulation in isolation through fmpy.""" + fmu_file = EXAMPLES_DIR / "TwoState.fmu" + assert fmu_file.exists() + result = simulate_fmu( + filename=fmu_file, + start_time=0.0, + stop_time=10.0, + step_size=0.1, + start_values={ + "mttf": 0.5, + "mttr": 0.1, + "deterministic": True, + "seed": 1, + }, + output=["state"], + use_event_mode=True, + ) + if show: + do_show(result["time"], result["state"], label="State") + assert result['time'][-1] == 10.0 + assert abs( sum(x for x in result['state'])/len(result['time']) - 0.8198) < 1e-3 + +def test_oscillator(*, show: bool): + """Test the TwoState.fmu simulation in isolation through fmpy.""" + fmu_file = EXAMPLES_DIR / "Oscillator.fmu" + assert fmu_file.exists() + result = simulate_fmu( + filename=fmu_file, + start_time=0.0, + stop_time=10.0, + step_size=0.1, + start_values={ + "c": "0.1 0.2 0.3", + "v": "1 2 3", + }, + output=["x","v"], + use_event_mode=False, + ) + if show: + do_show(result["time"], result["x"], label="pos/speed") + assert result['time'][-1] == 10.0 + assert np.allclose( sum(x for x in result['x'])/len(result['time']), [0.15228734,0.26645806,0.36340597]) + +def test_driving_force(*, show: bool): + """Test the TwoState.fmu simulation in isolation through fmpy.""" + fmu_file = EXAMPLES_DIR / "DrivingForce.fmu" + assert fmu_file.exists() + result = simulate_fmu( + filename=fmu_file, + start_time=0.0, + stop_time=10.0, + step_size=0.1, + start_values={ + "ampl" : "1 2 3", + "freq": "1 2 3", + "d_freq": 0.1, + }, + output=["f"], + use_event_mode=False, + ) + if show: + do_show(result["time"], result["f"], label="force") + assert result['time'][-1] == 10.0 + assert np.allclose( sum(x for x in result['f'])/len(result['time']), [0.01058458,0.00802318,0.00647999]) + +def test_bouncing_ball(*, show: bool): + """Test the TwoState.fmu simulation in isolation through fmpy.""" + fmu_file = EXAMPLES_DIR / "BouncingBall.fmu" + assert fmu_file.exists() + result = simulate_fmu( + filename=fmu_file, + start_time=0.0, + stop_time=10.0, + step_size=0.1, + start_values={ + "e" : 0.8, + }, + output=["h", "v"], + use_event_mode=False, + ) + if show: + do_show(result["time"], result["h"], label="height") + assert result['time'][-1] == 10.0 + print( sum(x for x in result['h'])/len(result['time'])) + assert abs( sum(x for x in result['h'])/len(result['time']) - 0.1113) < 1e-3 + + +def test_pid(*, show: bool): + fmu_file = EXAMPLES_DIR / "PIDController.fmu" + assert fmu_file.exists() + result = simulate_fmu( + filename=fmu_file, + start_time=0.0, + stop_time=10.0, + step_size=0.01, + start_values={"kp": 2.0, "ki": 0.5, "kd": 0.1, "setpoint": 1.0}, + input=np.array( + [(0.0, 0.0, 1.0), (1.0, 0.3, 1.0), (5.0, 0.8, 1.0), (10.0, 1.0, 1.0)], + dtype=[("time", np.double), ("measurement", np.double), ("setpoint", np.double)], + ), + output=["output", "setpoint", "measurement"], + ) + if show: + do_show( + result["time"], result["measurement"], "Measurement", result["time"], result["output"], "Control Output" + ) + +def test_linear_transform_2x2(*, show: bool): + fmu_file = EXAMPLES_DIR / "LinearTransform2x2.fmu" + assert fmu_file.exists() + result = simulate_fmu( + filename=fmu_file, + start_time=0.0, + stop_time=10.0, + step_size=0.01, + start_values={"scalar" : 2.0, + "A": "1.0 2.0 3.0 4.0", + "offset" : "4.0 5.0", + "u": "8.8 9.9"}, + output=["y"], + ) + if show: + do_show( + result["time"], result["y"], "Transform2x2" + ) + assert result['time'][-1] == 10.0 + y = 2.0 * np.array( (1,2,3,4), float).reshape(2,2).dot(np.array((8.8, 9.9), float)) + np.array((4,5),float) + assert np.allclose( result['y'][-1], y) + + + +if __name__ == "__main__": + retcode = 0 + if retcode == 0: + retcode = pytest.main(["-rA", "-v", "--rootdir", "../", "--show", "False", __file__]) + assert retcode == 0, f"Non-zero return code {retcode}" + # test_linear_transform() + # test_function(show=True) + # test_two_state(show=True) + # test_table(show=True) + # test_pid( show=True) + # test_oscillator( show=True) + # test_driving_force( show=True) + # test_bouncing_ball( show=True) + # test_linear_transform_2x2( show=True) diff --git a/pythonfmu3/tests/test_integration.py b/tests/test_integration.py similarity index 66% rename from pythonfmu3/tests/test_integration.py rename to tests/test_integration.py index cc8a1b7..134b774 100644 --- a/pythonfmu3/tests/test_integration.py +++ b/tests/test_integration.py @@ -1,17 +1,14 @@ +import ctypes +from helpers import W_DIR import math from pathlib import Path -import ctypes import pytest from pythonfmu3.builder import FmuBuilder -pytestmark = pytest.mark.skipif( - not FmuBuilder.has_binary(), reason="No binary available for the current platform." -) -fmpy = pytest.importorskip( - "fmpy", reason="fmpy is required for testing the produced FMU" -) +pytestmark = pytest.mark.skipif(not FmuBuilder.has_binary(), reason="No binary available for the current platform.") +fmpy = pytest.importorskip("fmpy", reason="fmpy is required for testing the produced FMU") def mapped(md): @@ -22,9 +19,9 @@ def mapped(md): @pytest.mark.integration -def test_integration_demo(tmp_path): +def test_integration_demo(): script_file = Path(__file__).parent / "slaves/pythonslave.py" - fmu = FmuBuilder.build_FMU(script_file, dest=tmp_path, needsExecutionTool="false") + fmu = FmuBuilder.build_FMU(script_file, dest=W_DIR, options={'needsExecutionTool':False}) assert fmu.exists() res = fmpy.simulate_fmu(str(fmu), stop_time=0.5) @@ -32,80 +29,82 @@ def test_integration_demo(tmp_path): @pytest.mark.integration -def test_integration_demo_MX(tmp_path): +def test_integration_demo_MX(): script_file = Path(__file__).parent / "slaves/pythonslaveMX.py" - fmu = FmuBuilder.build_FMU(script_file, dest=tmp_path, needsExecutionTool="false") + fmu = FmuBuilder.build_FMU(script_file, dest=W_DIR, options={'needsExecutionTool':False}) assert fmu.exists() res = fmpy.simulate_fmu(str(fmu), stop_time=0.5) -@pytest.mark.integration -def test_integration_solve_MX(tmp_path): +def test_integration_solve_MX(): script_file = Path(__file__).parent / "slaves/pythonslaveMX.py" - fmu = FmuBuilder.build_FMU(script_file, dest=tmp_path, needsExecutionTool="false") + fmu = FmuBuilder.build_FMU(script_file, dest=W_DIR, options={'needsExecutionTool':False}) assert fmu.exists() md = fmpy.read_model_description(str(fmu)) unzipdir = fmpy.extract(str(fmu)) - model = fmpy.fmi3.FMU3Model(guid=md.guid, - unzipDirectory=unzipdir, - modelIdentifier=md.modelExchange.modelIdentifier, - instanceName="instance" - ) + model = fmpy.fmi3.FMU3Model( + guid=md.guid, + unzipDirectory=unzipdir, + modelIdentifier=md.modelExchange.modelIdentifier, + instanceName="instance", + ) model.instantiate() - model.enterInitializationMode() + model.enterInitializationMode( tolerance=None, startTime=0.0, stopTime=10.0) model.exitInitializationMode() - + # forward euler t = 0.0 - step_size = 0.1 - + communication_step_size = 0.1 + values = (ctypes.c_double * 1)(0.0) - states = (ctypes.c_double *1)(0.0) + states = (ctypes.c_double * 1)(0.0) model.getContinuousStateDerivatives(values, 1) model.getContinuousStates(states, 1) - + assert values[0] == pytest.approx(-1.0, rel=1e-7) der = values[0] - new_state = states[0] + der * step_size + new_state = states[0] + der * communication_step_size model.setContinuousStates((ctypes.c_double * 1)(new_state), 1) - model.setTime(t + step_size) - + model.setTime(t + communication_step_size) + model.getContinuousStates(states, 1) - + assert states[0] == pytest.approx(new_state, rel=1e-7) + @pytest.mark.integration -def test_integration_demo_CS_MX(tmp_path): +def test_integration_demo_CS_MX(): script_file = Path(__file__).parent / "slaves/pythonslaveMXCS.py" - fmu = FmuBuilder.build_FMU(script_file, dest=tmp_path, needsExecutionTool="false") + fmu = FmuBuilder.build_FMU(script_file, dest=W_DIR, options={'needsExecutionTool':False}) assert fmu.exists() res = fmpy.simulate_fmu(str(fmu), stop_time=0.5, fmi_type="ModelExchange") - + res1 = fmpy.simulate_fmu(str(fmu), stop_time=0.5, fmi_type="CoSimulation") - + assert res[-1][0] == pytest.approx(res1[-1][0], rel=1e-7) assert res[-1][1] == pytest.approx(res1[-1][1], rel=0.1) @pytest.mark.integration -def test_integration_reset(tmp_path): +def test_integration_reset(): script_file = Path(__file__).parent / "slaves/pythonslave.py" - fmu = FmuBuilder.build_FMU(script_file, dest=tmp_path, needsExecutionTool="false") + fmu = FmuBuilder.build_FMU(script_file, dest=W_DIR, options={'needsExecutionTool':False}) assert fmu.exists() md = fmpy.read_model_description(str(fmu)) unzipdir = fmpy.extract(str(fmu)) - model = fmpy.fmi3.FMU3Slave(guid=md.guid, - unzipDirectory=unzipdir, - modelIdentifier=md.coSimulation.modelIdentifier, - instanceName="instance" - ) + model = fmpy.fmi3.FMU3Slave( + guid=md.guid, + unzipDirectory=unzipdir, + modelIdentifier=md.coSimulation.modelIdentifier, + instanceName="instance", + ) model.instantiate() - model.enterInitializationMode() + model.enterInitializationMode(tolerance=None, startTime=0.0, stopTime=10.0) model.exitInitializationMode() vars = mapped(md) @@ -126,24 +125,26 @@ def test_integration_reset(tmp_path): @pytest.mark.integration -def test_integration_get_state(tmp_path): +def test_integration_get_state(): script_file = Path(__file__).parent / "slaves/pythonslave.py" fmu = FmuBuilder.build_FMU( script_file, - dest=tmp_path, - needsExecutionTool="false", - canGetAndSetFMUstate="true") + dest=W_DIR, + options = {'needsExecutionTool':False, + 'canGetAndSetFMUstate':True} + ) assert fmu.exists() md = fmpy.read_model_description(str(fmu)) unzipdir = fmpy.extract(str(fmu)) - model = fmpy.fmi3.FMU3Slave(guid=md.guid, - unzipDirectory=unzipdir, - modelIdentifier=md.coSimulation.modelIdentifier, - instanceName="instance" - ) + model = fmpy.fmi3.FMU3Slave( + guid=md.guid, + unzipDirectory=unzipdir, + modelIdentifier=md.coSimulation.modelIdentifier, + instanceName="instance", + ) model.instantiate() - model.enterInitializationMode() + model.enterInitializationMode(tolerance=None, startTime=0.0, stopTime=10.0) model.exitInitializationMode() vars = mapped(md) @@ -172,14 +173,15 @@ def step_model(): @pytest.mark.integration -def test_integration_get_serialize_state(tmp_path): +def test_integration_get_serialize_state(): script_file = Path(__file__).parent / "slaves/pythonslave.py" fmu = FmuBuilder.build_FMU( script_file, - dest=tmp_path, - canGetAndSetFMUstate="true", - canSerializeFMUstate="true") + dest=W_DIR, + options = {'canGetAndSetFMUstate':True, + 'canSerializeFMUstate':True} + ) assert fmu.exists() md = fmpy.read_model_description(fmu) @@ -189,10 +191,11 @@ def test_integration_get_serialize_state(tmp_path): guid=md.guid, unzipDirectory=unzip_dir, modelIdentifier=md.coSimulation.modelIdentifier, - instanceName='instance1') + instanceName="instance1", + ) model.instantiate() - model.enterInitializationMode() + model.enterInitializationMode(tolerance=None, startTime=0.0, stopTime=10.0) model.exitInitializationMode() vars = mapped(md) @@ -228,9 +231,9 @@ def step_model(): @pytest.mark.integration -def test_integration_get(tmp_path): +def test_integration_get(): script_file = Path(__file__).parent / "slaves/pythonslave.py" - fmu = FmuBuilder.build_FMU(script_file, dest=tmp_path, needsExecutionTool="false") + fmu = FmuBuilder.build_FMU(script_file, dest=W_DIR, options={'needsExecutionTool':False}) assert fmu.exists() md = fmpy.read_model_description(fmu) @@ -240,10 +243,11 @@ def test_integration_get(tmp_path): guid=md.guid, unzipDirectory=unzip_dir, modelIdentifier=md.coSimulation.modelIdentifier, - instanceName='instance1') + instanceName="instance1", + ) model.instantiate() - model.enterInitializationMode() + model.enterInitializationMode(tolerance=None, startTime=0.0, stopTime=10.0) model.exitInitializationMode() to_test = { @@ -256,7 +260,7 @@ def test_integration_get(tmp_path): "booleanParameter": False, "stringParameter": "dog", "container.someReal": 99.0, - "container.subContainer.someInteger": -15 + "container.subContainer.someInteger": -15, } model_value = None @@ -280,10 +284,11 @@ def test_integration_get(tmp_path): model.terminate() model.freeInstance() + @pytest.mark.integration -def test_integration_get_array(tmp_path): +def test_integration_get_array(): script_file = Path(__file__).parent / "slaves/pythonslave_arraytypes.py" - fmu = FmuBuilder.build_FMU(script_file, dest=tmp_path, needsExecutionTool="false") + fmu = FmuBuilder.build_FMU(script_file, dest=W_DIR, options={'needsExecutionTool':False}) assert fmu.exists() md = fmpy.read_model_description(fmu) @@ -293,18 +298,30 @@ def test_integration_get_array(tmp_path): guid=md.guid, unzipDirectory=unzip_dir, modelIdentifier=md.coSimulation.modelIdentifier, - instanceName='instance1') + instanceName="instance1", + ) model.instantiate() - model.enterInitializationMode() + model.enterInitializationMode(tolerance=None, startTime=0.0, stopTime=10.0) model.exitInitializationMode() to_test = { - "int32_output": [1,2,3,4,5,6,7,8,9,10], - "int64_output": [1,2,3,4,5,6,7,8,9,10], - "uint64_output": [1,2,3,4,5,6,7,8,9,10], - "float64_output": [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0], - "boolean_output": [False, True, False, True, True, False, False, True, False, True] + "int32_output": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + "int64_output": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + "uint64_output": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + "float64_output": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], + "boolean_output": [ + False, + True, + False, + True, + True, + False, + False, + True, + False, + True, + ], } model_value = None @@ -327,16 +344,21 @@ def test_integration_get_array(tmp_path): assert len(model_values) == len(value) assert model_values == value - + model.terminate() model.freeInstance() @pytest.mark.integration -def test_integration_read_from_file(tmp_path): +def test_integration_read_from_file(): script_file = Path(__file__).parent / "slaves/pythonslave_read_file.py" project_file = Path(__file__).parent / "data/hello.txt" - fmu = FmuBuilder.build_FMU(script_file, project_files=[project_file], dest=tmp_path, needsExecutionTool="false") + fmu = FmuBuilder.build_FMU( + script_file, + project_files=[project_file], + dest=W_DIR, + options={'needsExecutionTool':False}, + ) assert fmu.exists() md = fmpy.read_model_description(fmu) @@ -346,17 +368,18 @@ def test_integration_read_from_file(tmp_path): guid=md.guid, unzipDirectory=unzip_dir, modelIdentifier=md.coSimulation.modelIdentifier, - instanceName='instance1') + instanceName="instance1", + ) model.instantiate() - model.enterInitializationMode() + model.enterInitializationMode(tolerance=None, startTime=0.0, stopTime=10.0) model.exitInitializationMode() variables = mapped(md) var = variables["file_content"] model_value = model.getString([var.valueReference])[0] - with (open(project_file, 'r')) as file: + with open(project_file) as file: data = file.read() assert model_value == data @@ -366,9 +389,9 @@ def test_integration_read_from_file(tmp_path): @pytest.mark.integration -def test_integration_set(tmp_path): +def test_integration_set(): script_file = Path(__file__).parent / "slaves/pythonslave.py" - fmu = FmuBuilder.build_FMU(script_file, dest=tmp_path, needsExecutionTool="false") + fmu = FmuBuilder.build_FMU(script_file, dest=W_DIR, options={'needsExecutionTool':False}) assert fmu.exists() md = fmpy.read_model_description(fmu) @@ -378,10 +401,11 @@ def test_integration_set(tmp_path): guid=md.guid, unzipDirectory=unzip_dir, modelIdentifier=md.coSimulation.modelIdentifier, - instanceName='instance1') + instanceName="instance1", + ) model.instantiate() - model.enterInitializationMode() + model.enterInitializationMode(tolerance=None, startTime=0.0, stopTime=10.0) model.exitInitializationMode() to_test = { @@ -390,7 +414,7 @@ def test_integration_set(tmp_path): "booleanParameter": True, "stringParameter": "cat", "container.someReal": 42.0, - "container.subContainer.someInteger": 421 + "container.subContainer.someInteger": 421, } model_value = None @@ -418,10 +442,11 @@ def test_integration_set(tmp_path): model.terminate() model.freeInstance() + @pytest.mark.integration -def test_integration_set_array(tmp_path): +def test_integration_set_array(): script_file = Path(__file__).parent / "slaves/pythonslave_arraytypes.py" - fmu = FmuBuilder.build_FMU(script_file, dest=tmp_path, needsExecutionTool="false") + fmu = FmuBuilder.build_FMU(script_file, dest=W_DIR, options={'needsExecutionTool':False}) assert fmu.exists() md = fmpy.read_model_description(fmu) @@ -431,18 +456,30 @@ def test_integration_set_array(tmp_path): guid=md.guid, unzipDirectory=unzip_dir, modelIdentifier=md.coSimulation.modelIdentifier, - instanceName='instance1') + instanceName="instance1", + ) model.instantiate() - model.enterInitializationMode() + model.enterInitializationMode(tolerance=None, startTime=0.0, stopTime=10.0) model.exitInitializationMode() to_test = { - "int32_input": [1,2,3,4,5,6,7,8,9,10], - "int64_input": [1,2,3,4,5,6,7,8,9,10], - "uint64_input": [1,2,3,4,5,6,7,8,9,10], - "float64_input": [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0], - "boolean_input": [False, True, False, True, True, False, False, True, False, True] + "int32_input": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + "int64_input": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + "uint64_input": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + "float64_input": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], + "boolean_input": [ + False, + True, + False, + True, + True, + False, + False, + True, + False, + True, + ], } model_value = None @@ -461,13 +498,13 @@ def test_integration_set_array(tmp_path): model_value = model.getUInt64(vrs, nValues=10) elif var.type == "Float64": model.setFloat64(vrs, value) - model_value = model.getFloat64(vrs,nValues=10) + model_value = model.getFloat64(vrs, nValues=10) elif var.type == "Boolean": model.setBoolean(vrs, value) model_value = model.getBoolean(vrs, nValues=10) else: pytest.xfail("Unsupported type") - + assert list(model_value) == value model.terminate() @@ -475,10 +512,10 @@ def test_integration_set_array(tmp_path): @pytest.mark.integration -def test_simple_integration_fmpy(tmp_path): +def test_simple_integration_fmpy(): script_file = Path(__file__).parent / "slaves/pythonslave.py" - fmu = FmuBuilder.build_FMU(script_file, dest=tmp_path) + fmu = FmuBuilder.build_FMU(script_file, dest=W_DIR) assert fmu.exists() res = fmpy.simulate_fmu(str(fmu), stop_time=2.0) @@ -486,32 +523,49 @@ def test_simple_integration_fmpy(tmp_path): @pytest.mark.integration -def test_integration_has_local_dep(tmp_path): +def test_integration_has_local_dep(): script_file = Path(__file__).parent / "slaves/slavewithdep.py" local_file = Path(__file__).parent / "slaves/localmodule.py" fmu = FmuBuilder.build_FMU( script_file, - dest=tmp_path, + dest=W_DIR, project_files=[local_file], - needsExecutionTool="false", + options = {'needsExecutionTool':False}, ) assert fmu.exists() res = fmpy.simulate_fmu(str(fmu), stop_time=0.5) - assert res["realOut"][-1] == pytest.approx( - 22.0 * 5.0 * math.exp(res["time"][-1] / 0.1), rel=1e-7 - ) + assert res["realOut"][-1] == pytest.approx(22.0 * 5.0 * math.exp(res["time"][-1] / 0.1), rel=1e-7) @pytest.mark.integration -def test_integration_throw_py_error(tmp_path): +def test_integration_throw_py_error(): script_file = Path(__file__).parent / "slaves/PythonSlaveWithException.py" - fmu = FmuBuilder.build_FMU(script_file, dest=tmp_path) + fmu = FmuBuilder.build_FMU(script_file, dest=W_DIR) assert fmu.exists() with pytest.raises(Exception): fmpy.simulate_fmu(str(fmu), stop_time=1.0) + +if __name__ == "__main__": + """Possibility to run single or all tests from the IDE.""" + retcode = 1 + if retcode == 0: + retcode = pytest.main(["-rA", "-v", "--rootdir", "../", "--show", "False", __file__]) + assert retcode == 0, f"Non-zero return code {retcode}" + + # test_integration_demo() + test_integration_solve_MX() + # test_integration_demo_CS_MX() + # test_integration_get_serialize_state() + # test_integration_get_array() + # test_integration_read_from_file() + # test_integration_set_array() + # test_integration_has_local_dep() + + + \ No newline at end of file diff --git a/pythonfmu3/tests/test_logger.py b/tests/test_logger.py similarity index 72% rename from pythonfmu3/tests/test_logger.py rename to tests/test_logger.py index 3dbcee0..ce00865 100644 --- a/pythonfmu3/tests/test_logger.py +++ b/tests/test_logger.py @@ -1,18 +1,14 @@ -import sys import itertools +from unittest.mock import MagicMock, call + import pytest -from unittest.mock import call, MagicMock from pythonfmu3.builder import FmuBuilder from pythonfmu3.enums import Fmi3Status from pythonfmu3.fmi3slave import Fmi3Slave -fmpy = pytest.importorskip( - "fmpy", reason="fmpy is not available for testing the produced FMU" -) -pytestmark = pytest.mark.skipif( - not FmuBuilder.has_binary(), reason="No binary available for the current platform." -) +fmpy = pytest.importorskip("fmpy", reason="fmpy is not available for testing the produced FMU") +pytestmark = pytest.mark.skipif(not FmuBuilder.has_binary(), reason="No binary available for the current platform.") if True: pytest.skip("This test needs to be manually enabled", allow_module_level=True) @@ -26,17 +22,11 @@ def test_logger(tmp_path, debug_logging): message = "log message" log_calls = [ - ( - f"{status.name.upper()} - {debug} - {message}", - status, - category, - debug - ) for debug, status in itertools.product([True, False], Fmi3Status) + (f"{status.name.upper()} - {debug} - {message}", status, category, debug) + for debug, status in itertools.product([True, False], Fmi3Status) ] - fmu_calls = "\n".join([ - ' self.log("{}", Fmi3Status.{}, "{}", {})'.format(c[0], c[1].name, c[2], c[3]) for c in log_calls - ]) + fmu_calls = "\n".join([f' self.log("{c[0]}", Fmi3Status.{c[1].name}, "{c[2]}", {c[3]})' for c in log_calls]) slave_code = f"""from pythonfmu3.Fmi3Slave import Fmi3Slave, Fmi3Status, Fmi3Causality, Int32, Float64, Boolean, String @@ -52,7 +42,7 @@ def __init__(self, **kwargs): self.register_variable(Float64("realOut", causality=Fmi3Causality.output)) - def do_step(self, current_time, step_size): + def do_step(self, current_communication_point, communication_step_size): {fmu_calls} return True """ @@ -71,7 +61,7 @@ def do_step(self, current_time, step_size): stop_time=1e-3, output_interval=1e-3, logger=logger, - debug_logging=debug_logging + debug_logging=debug_logging, ) expected_calls = [ @@ -80,10 +70,11 @@ def do_step(self, current_time, step_size): bytes(name, encoding="utf-8"), int(c[1]), bytes(c[2], encoding="utf-8"), - bytes(c[0], encoding="utf-8") - ) for c in filter(lambda c: debug_logging or not c[3], log_calls) + bytes(c[0], encoding="utf-8"), + ) + for c in filter(lambda c: debug_logging or not c[3], log_calls) ] - + assert logger.call_count == len(Fmi3Status) * (1 + int(debug_logging)) logger.assert_has_calls(expected_calls) @@ -96,16 +87,11 @@ def test_log_categories(tmp_path, debug_logging, categories): message = "log message" log_calls = [ - ( - f"{status.name.upper()} - {debug} - {message}", - status, - debug - ) for debug, status in itertools.product([True, False], Fmi3Status) + (f"{status.name.upper()} - {debug} - {message}", status, debug) + for debug, status in itertools.product([True, False], Fmi3Status) ] - fmu_calls = "\n".join([ - ' self.log("{}", Fmi3Status.{}, None, {})'.format(c[0], c[1].name, c[2]) for c in log_calls - ]) + fmu_calls = "\n".join([f' self.log("{c[0]}", Fmi3Status.{c[1].name}, None, {c[2]})' for c in log_calls]) slave_code = f"""from pythonfmu3.Fmi3Slave import Fmi3Slave, Fmi3Status, Fmi3Causality, Int32, Float64, Boolean, String @@ -121,7 +107,7 @@ def __init__(self, **kwargs): self.register_variable(Float64("realOut", causality=Fmi3Causality.output)) - def do_step(self, current_time, step_size): + def do_step(self, current_communication_point, communication_step_size): {fmu_calls} return True """ @@ -148,7 +134,8 @@ def do_step(self, current_time, step_size): guid=model_description.guid, unzipDirectory=unzip_dir, modelIdentifier=model_description.coSimulation.modelIdentifier, - instanceName='instance1') + instanceName="instance1", + ) # Instantiate the model model.instantiate(callbacks=callbacks) model.setDebugLogging(debug_logging, categories) @@ -156,7 +143,7 @@ def do_step(self, current_time, step_size): model.enterInitializationMode() model.exitInitializationMode() # Execute the model - model.doStep(0., 0.1) + model.doStep(0.0, 0.1) # Clean the model model.terminate() @@ -166,13 +153,15 @@ def do_step(self, current_time, step_size): if category not in Fmi3Slave.log_categories: category = "logAll" if len(categories) == 0 or category in categories: - expected_calls.append(call( - logger.call_args[0][0], # Don't test the first argument - b'instance1', - int(c[1]), - bytes(category, encoding="utf-8"), - bytes(c[0], encoding="utf-8") - )) + expected_calls.append( + call( + logger.call_args[0][0], # Don't test the first argument + b"instance1", + int(c[1]), + bytes(category, encoding="utf-8"), + bytes(c[0], encoding="utf-8"), + ) + ) n_calls = len(Fmi3Status) if len(categories) == 0 else len(categories) diff --git a/pythonfmu3/tests/test_multiple_fmus.py b/tests/test_multiple_fmus.py similarity index 55% rename from pythonfmu3/tests/test_multiple_fmus.py rename to tests/test_multiple_fmus.py index 93e621c..fae2142 100644 --- a/pythonfmu3/tests/test_multiple_fmus.py +++ b/tests/test_multiple_fmus.py @@ -1,15 +1,14 @@ +"""Simulation of two independent FMUs.""" +from helpers import W_DIR import math + import pytest from pythonfmu3.builder import FmuBuilder -pytestmark = pytest.mark.skipif( - not FmuBuilder.has_binary(), reason="No binary available for the current platform." -) +pytestmark = pytest.mark.skipif(not FmuBuilder.has_binary(), reason="No binary available for the current platform.") -fmpy = pytest.importorskip( - "fmpy", reason="fmpy is not available for testing the produced FMU" -) +fmpy = pytest.importorskip("fmpy", reason="fmpy is not available for testing the produced FMU") def mapped(md): @@ -19,10 +18,13 @@ def mapped(md): return m + @pytest.mark.integration -def test_integration_multiple_fmus(tmp_path): +def test_integration_multiple_fmus(): slave1_code = """import math -from pythonfmu3 import Fmi3Slave, Fmi3Causality, Fmi3Variability, Int32, Float64, Boolean, String +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.enums import Fmi3Causality, Fmi3Variability +from pythonfmu3.variables import Int32, Float64, Boolean, String class Slave1(Fmi3Slave): @@ -37,14 +39,16 @@ def __init__(self, **kwargs): self.register_variable(Float64("realIn", causality=Fmi3Causality.input)) self.register_variable(Float64("realOut", causality=Fmi3Causality.output)) - def do_step(self, current_time, step_size): + def do_step(self, current_communication_point, communication_step_size, noSetFMUStatePriorToCurrentPoint): self.log("Do step on Slave1.") - self.realOut = self.realIn * 5.0 * (1.0 - math.exp(-1.0 * (current_time + step_size) / 0.1)) + self.realOut = self.realIn * 5.0 * (1.0 - math.exp(-1.0 * (current_communication_point + communication_step_size) / 0.1)) return True """ - slave2_code = """from pythonfmu3 import Fmi3Slave, Fmi3Causality, Fmi3Variability, Int32, Float64, Boolean, String - + slave2_code = """ +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.enums import Fmi3Causality, Fmi3Variability +from pythonfmu3.variables import Int32, Float64, Boolean, String class Slave2(Fmi3Slave): @@ -58,31 +62,23 @@ def __init__(self, **kwargs): self.register_variable(Float64("realIn", causality=Fmi3Causality.input)) self.register_variable(Float64("realOut", causality=Fmi3Causality.output)) - def do_step(self, current_time, step_size): + def do_step(self, current_communication_point, communication_step_size, noSetFMUStatePriorToCurrentPoint): self.log("Do step on Slave2.") self.realOut = -2.0 * self.realIn return True """ - script1_file = tmp_path / "orig" / "slave1.py" + script1_file = W_DIR / "orig" / "slave1.py" script1_file.parent.mkdir(parents=True, exist_ok=True) script1_file.write_text(slave1_code) - fmu1 = FmuBuilder.build_FMU( - script1_file, - dest=tmp_path, - needsExecutionTool="false" - ) + fmu1 = FmuBuilder.build_FMU(script1_file, dest=W_DIR, options={'needsExecutionTool':False}) assert fmu1.exists() - script2_file = tmp_path / "orig" / "slave2.py" + script2_file = W_DIR / "orig" / "slave2.py" script2_file.write_text(slave2_code) - fmu2 = FmuBuilder.build_FMU( - script2_file, - dest=tmp_path, - needsExecutionTool="false" - ) + fmu2 = FmuBuilder.build_FMU(script2_file, dest=W_DIR, options={'needsExecutionTool':False}) assert fmu2.exists() md1 = fmpy.read_model_description(fmu1) @@ -92,10 +88,11 @@ def do_step(self, current_time, step_size): guid=md1.guid, unzipDirectory=unzip_dir, modelIdentifier=md1.coSimulation.modelIdentifier, - instanceName='instance1') + instanceName="instance1", + ) model1.instantiate() - model1.enterInitializationMode() + model1.enterInitializationMode(tolerance=None, startTime=0.0, stopTime=10.0) model1.exitInitializationMode() md2 = fmpy.read_model_description(fmu2) @@ -105,7 +102,8 @@ def do_step(self, current_time, step_size): guid=md2.guid, unzipDirectory=unzip_dir, modelIdentifier=md2.coSimulation.modelIdentifier, - instanceName='instance2') + instanceName="instance2", + ) variables1 = mapped(md1) variables2 = mapped(md2) @@ -114,7 +112,7 @@ def do_step(self, current_time, step_size): realIn = variables2["realIn"] model2.instantiate() - model2.enterInitializationMode() + model2.enterInitializationMode(tolerance=None, startTime=0.0, stopTime=10.0) value = model1.getFloat64([realOut.valueReference])[0] model2.setFloat64([realIn.valueReference], [value]) @@ -123,19 +121,26 @@ def do_step(self, current_time, step_size): time = 0 stop_time = 0.1 - step_size = 0.025 + communication_step_size = 0.025 while time < stop_time: - model2.setFloat64([realIn.valueReference], [value]) - model1.doStep(time, step_size) - model2.doStep(time, step_size) + model1.doStep(time, communication_step_size, True) + model2.doStep(time, communication_step_size, noSetFMUStatePriorToCurrentPoint=True) value = model1.getFloat64([realOut.valueReference])[0] - time += step_size + time += communication_step_size + + assert value == pytest.approx(22.0 * 5.0 * (1.0 - math.exp(-1.0 * time / 0.1)), rel=1e-7) + +if __name__ == "__main__": + """Possibility to run single or all tests from the IDE.""" + retcode = 1 + if retcode == 0: + retcode = pytest.main(["-rA", "-v", "--rootdir", "../", "--show", "False", __file__]) + assert retcode == 0, f"Non-zero return code {retcode}" + + test_integration_multiple_fmus() - assert value == pytest.approx( - 22.0 * 5.0 * (1.0 - math.exp(-1.0 * time / 0.1)), rel=1e-7 - ) diff --git a/tests/test_oscillator3.py b/tests/test_oscillator3.py new file mode 100644 index 0000000..9cf30fd --- /dev/null +++ b/tests/test_oscillator3.py @@ -0,0 +1,97 @@ +"""Test oscillator and driver using fmpy.""" + +import logging +from pathlib import Path + +import fmpy +import matplotlib.pyplot as plt +import numpy as np +import pytest +from fmpy import simulate_fmu +from simulation import _simulateCS + +fmpy.simulation.simulateCS = _simulateCS + +logging.basicConfig(level=logging.INFO) +LOGGER = logging.getLogger(__name__) + +EXAMPLES_DIR = Path(__file__).resolve().parent.parent / "examples" + + +def do_show( + x: list | np.ndarray, + y: list | np.ndarray, + label: str, + x2: list | np.ndarray | None = None, + y2: list | np.ndarray | None = None, + label2: str = "", +): + plt.figure(figsize=(12, 6)) + plt.subplot(2, 1, 1) + plt.plot(x, y, label=label) + plt.xlabel("Time") + plt.ylabel("Value") + plt.legend() + plt.grid(True) + + if x2 is not None and y2 is not None: + plt.subplot(2, 1, 2) + plt.plot(x2, y2, label=label2) + plt.xlabel("Time") + plt.ylabel("Value2") + plt.legend() + plt.grid(True) + plt.show() + + +def test_oscillator(*, show: bool): + """Test the Function.fmu in isolation.""" + fmu_file = EXAMPLES_DIR / "Oscillator.fmu" + assert fmu_file.exists() + result = simulate_fmu( + filename=fmu_file, + start_time=0.0, + stop_time=100.0, + step_size=0.01, + start_values={ + "c": "0.1 0 0", + "x": "1.0 0 0", + "v": "0 0 0", + }, + output=["x", "v"], + ) + if show: + do_show(result["time"], result["x"], label="Position", x2=result["time"], y2=result["v"], label2="Speed") + + +def test_driving_force(*, show: bool): + """Test the DrivingForce.fmu in isolation.""" + fmu_file = EXAMPLES_DIR / "DrivingForce.fmu" + assert fmu_file.exists() + result = simulate_fmu( + filename=fmu_file, + start_time=0.0, + stop_time=100.0, + step_size=0.01, + start_values={ + "ampl": "1 1 1", + "freq": "0.1 0.1 0.1", + "d_freq": 0.1, + }, + output=["f"], + ) + if show: + do_show( + result["time"], + result["f"], + label="Force", + ) + + +if __name__ == "__main__": + retcode = 1 + if retcode == 0: + retcode = pytest.main(["-rA", "-v", "--rootdir", "../", "--show", "False", __file__]) + assert retcode == 0, f"Non-zero return code {retcode}" + test_oscillator(show=True) + # test_driving_force(show=True) diff --git a/tests/test_variables.py b/tests/test_variables.py new file mode 100644 index 0000000..0907da8 --- /dev/null +++ b/tests/test_variables.py @@ -0,0 +1,437 @@ +import xml.etree.ElementTree as ET +from enum import Enum +from random import randint + +import pytest + +from pythonfmu3.fmi3slave import Fmi3Slave +from pythonfmu3.enums import Fmi3Causality, Fmi3Initial, Fmi3Variability +from pythonfmu3.variables import ( + py_types, + Boolean, + Dimension, + Float64, + Float32, + Int64, + Int32, + Int16, + Int8, + ModelVariable, + String, + UInt64, + UInt32, + UInt16, + UInt8, + flatten, +) + +MODEL_VARIABLE_ATTRIBUTES = [ + "name", + "valueReference", + "description", + "causality", + "variability", + "initial", +] + + +def test_ModelVariable_reference_set_once_only(): + v = ModelVariable("variable") + v.value_reference = 22 + + with pytest.raises(RuntimeError): + v.value_reference = 33 + + +@pytest.mark.parametrize("causality", list(Fmi3Causality) + [None]) +@pytest.mark.parametrize("initial", list(Fmi3Initial) + [None]) +@pytest.mark.parametrize("variability", list(Fmi3Variability) + [None]) +@pytest.mark.parametrize( + "name, description", + [ + ("var", None), + ("var", "description of var"), + ], +) +def test_ModelVariable_constructor(causality, initial, variability, name, description): + var = ModelVariable(name, causality, description, initial, variability) + + assert var.name == name + assert var.value_reference is None + assert var.causality == causality + assert var.description == description + assert var.initial == initial + assert var.variability == variability + + +@pytest.mark.parametrize( + "fmi_type,value", + [ + (Boolean, False), + (Int64, -64), + (Int32, -32), + (Int16, -16), + (Int8, -8), + (UInt64, py_types['UInt64'](23)), + (UInt32, py_types['UInt32'](23)), + (UInt16, py_types['UInt16'](23)), + (UInt8, py_types['UInt8'](23)), + (Float64, 4.0 / 6.0), + (Float32, 2.0 / 3.0), + (String, "hello_world"), + ], +) +def test_ModelVariable_getter(fmi_type, value): + + class Slave(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.var = [value] + self.register_variable(fmi_type("var", getter=lambda: self.var[0])) + + def do_step(self, t, dt): + return True + + fmi_type_name = fmi_type.__qualname__.lower() + + slave = Slave(instanceName="slaveInstance") + assert [getattr(val, "value", val) for val in getattr(slave, f"get_{fmi_type_name}")([0])] == [value] + + +@pytest.mark.parametrize( + "fmi_type,value", + [ + (Boolean, False), + (Int32, 22), + (UInt64, py_types['UInt64'](23)), + (Float64, 2.0 / 3.0), + (String, "hello_world"), + ], +) +def test_ModelVariable_setter(fmi_type, value): + + class Slave(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.var = [None] + self.register_variable( + fmi_type( + "var", + getter=lambda: self.var[0], + setter=lambda v: self.var.__setitem__(0, v), + ) + ) + + def do_step(self, t, dt): + return True + + slave = Slave(instanceName="slaveInstance") + fmi_type_name = fmi_type.__qualname__.lower() + + set_method = getattr(slave, f"set_{fmi_type_name}") + set_method([0], [value]) + assert [getattr(val, "value", val) for val in getattr(slave, f"get_{fmi_type_name}")([0])] == [value] + + +@pytest.mark.parametrize( + "fmi_type,value,dims", + [ + (Float64, [1.0, 2.0, 3.0, 4.0], [4]), + (Float64, [1.0, 2.0, 3.0, 4.0], [2, 2]), + ], +) +def test_ModelVariable_getter_array(fmi_type, value, dims): + + class Slave(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.var = value + dimensions = [Dimension(start=val) for val in dims] + self.register_variable(fmi_type("var", getter=lambda: self.var, dimensions=dimensions)) + + def do_step(self, t, dt): + return True + + fmi_type_name = fmi_type.__qualname__.lower() + + slave = Slave(instanceName="slaveInstance") + assert [getattr(val, "value", val) for val in getattr(slave, f"get_{fmi_type_name}")([0])] == value + + +@pytest.mark.parametrize( + "fmi_type,value,dims", + [ + (Float64, [1.0, 2.0, 3.0, 4.0], [4]), + (Float64, [1.0, 2.0, 3.0, 4.0], [2, 2]), + ], +) +def test_ModelVariable_setter_array(fmi_type, value, dims): + + class Slave(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.var = [None] * len(value) + dimensions = [Dimension(start=val) for val in dims] + self.register_variable( + fmi_type( + "var", + getter=lambda: self.var, + setter=lambda v: setattr(self, "var", v), + dimensions=dimensions, + ) + ) + + def do_step(self, t, dt): + return True + + slave = Slave(instanceName="slaveInstance") + fmi_type_name = fmi_type.__qualname__.lower() + + set_method = getattr(slave, f"set_{fmi_type_name}") + set_method( + [ + 0, + ], + value, + ) + assert [getattr(val, "value", val) for val in getattr(slave, f"get_{fmi_type_name}")([0])] == value + + +@pytest.mark.parametrize("causality", list(Fmi3Causality) + [None]) +@pytest.mark.parametrize("initial", list(Fmi3Initial) + [None]) +@pytest.mark.parametrize("variability", list(Fmi3Variability) + [None]) +@pytest.mark.parametrize( + "name, description", + [ + ("var", None), + ("var", "description of var"), + ], +) +def test_ModelVariable_to_xml(causality, initial, variability, name, description): + var = ModelVariable(name, causality, description, initial, variability) + valueReference = randint(0, 25000) + var.value_reference = valueReference + + node = var.to_xml() + assert node.tag == None + args = locals() + for attr in MODEL_VARIABLE_ATTRIBUTES: + value = args[attr] + if value is not None: + if isinstance(value, Enum): + assert node.attrib[attr] == value.name + else: + assert node.attrib[attr] == str(value) + + +@pytest.mark.parametrize( + "var_type, value", + [ + (Boolean, True), + (Int32, 23), + (UInt64, py_types['UInt64'](23)), + (Float64, 15.0), + (String, "hello"), + ], +) +@pytest.mark.parametrize("causality", list(Fmi3Causality) + [None]) +@pytest.mark.parametrize("initial", list(Fmi3Initial) + [None]) +@pytest.mark.parametrize("variability", list(Fmi3Variability) + [None]) +def test_ModelVariable_start(var_type, value, causality, initial, variability): + var_obj = var_type( + "var", + causality=causality, + description="a variable", + initial=initial, + variability=variability, + ) + + class PySlave(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.var = value + self.register_variable(var_obj) + + def do_step(self, current_communication_point: float, communication_step_size: float): + return True + + slave = PySlave(instanceName="testInstance") + + xml = slave.to_xml() + var_node = xml.find(f".//{var_obj._type}[@name='var']") + + assert var_node is not None + + if ModelVariable.requires_start(var_obj): + assert var_obj.start == value + else: + assert var_obj.start is None + + +@pytest.mark.parametrize( + "name,start", + [ + ("boolean_name", None), + ("boolean_another_name", False), + ], +) +def test_Boolean_constructor(name, start): + r = Boolean(name, start) + + assert r.start == start + + +@pytest.mark.parametrize( + "name,start", + [ + ("boolean_name", None), + ("boolean_another_name", True), + ("boolean_yet_another", False), + ], +) +def test_Boolean_to_xml(name, start): + r = Boolean(name, start) + xml = r.to_xml() + if start is not None: + assert xml.attrib["start"] == str(start).lower() + + +@pytest.mark.parametrize( + "name,start", + [ + ("integer_name", None), + ("integer_another_name", 42), + ], +) +def test_Integer_constructor(name, start): + for obj in (Int64, Int32, Int16, Int8, UInt64, UInt32, UInt16, UInt8): + r = obj(name, start=start) + assert r.start == start + +@pytest.mark.parametrize( + "name,start", + [ + ("integer_name", None), + ("integer_another_name", 42), + ], +) +def test_Integer_to_xml(name, start): + for obj in (Int64, Int32, Int16, Int8, UInt64, UInt32, UInt16, UInt8): + r = obj(name, start=start) + xml = r.to_xml() + if start is not None: + assert xml.attrib["start"] == str(start) + + +@pytest.mark.parametrize( + "name,start", + [ + ("real_name", None), + ("real_another_name", 22.0), + ], +) +def test_Real_constructor(name, start): + r = Float64(name, start) + + assert r.start == start + + +@pytest.mark.parametrize( + "name,start", + [ + ("real_name", None), + ("real_another_name", 22.0), + ], +) +def test_Real_to_xml(name, start): + r = Float64(name, start) + xml = r.to_xml() + if start is not None: + assert xml.attrib["start"] == f"{start:.16g}" + + +@pytest.mark.parametrize( + "name,start", + [ + ("string_name", None), + ("string_another_name", "dummy"), + ], +) +def test_String_constructor(name, start): + r = String(name, start) + + assert r.start == start + + +@pytest.mark.parametrize( + "name,start", + [ + ("string_name", None), + ("string_another_name", "dummy"), + ], +) +def test_String_to_xml(name, start): + r = String(name, start) + xml = r.to_xml() + if start is not None: + start_elements = xml.findall(".//Start") + assert len(start_elements) == 1 + assert start_elements[0].attrib["value"] == str(start) + + +@pytest.mark.parametrize( + "name,start,dims", + [("array1", [1.0, 2.0, 3.0, 4.0], [4]), ("array2", [1.0, 2.0, 3.0, 4.0], [2, 2])], +) +def test_array_to_xml(name, start, dims): + r = Float64(name, start, dimensions=[Dimension(start=val) for val in dims]) + xml = r.to_xml() + if start is not None: + assert xml.attrib["start"] == " ".join([f"{val:.16g}" for val in flatten(start)]) + if dims is not None: + xml_dims = xml.findall(".//Dimension") + assert len(xml_dims) == len(dims) + assert [int(xml_dim.attrib["start"]) for xml_dim in xml_dims] == dims + + +@pytest.mark.parametrize( + "name,start,dims", + [ + ("array1", [1.0, 2.0, 3.0, 4.0], [4]), + ("array2", [1.0, 2.0, 3.0, 4.0], [2, 2]), + ("array3", [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], [2, 2, 2]), + ], +) +def test_array_output_to_xml(name, start, dims): + import numpy as np + + start = np.reshape(start, shape=dims) + r = Float64( + name, + start, + dimensions=[Dimension(start=val) for val in dims], + causality=Fmi3Causality.output, + ) + xml = r.to_xml() + if start is not None: + assert xml.attrib["start"] == " ".join([f"{val:.16g}" for val in flatten(start)]) + if dims is not None: + xml_dims = xml.findall(".//Dimension") + assert len(xml_dims) == len(dims) + assert [int(xml_dim.attrib["start"]) for xml_dim in xml_dims] == dims + +if __name__ == "__main__": + retcode = 0 + if retcode == 0: + retcode = pytest.main(["-rA", "-v", "--rootdir", "../", "--show", "False", __file__]) + assert retcode == 0, f"Non-zero return code {retcode}" + # test_Integer_constructor("myInt", start=-2) + # test_ModelVariable_getter_array(Float64, [1.0, 2.0, 3.0, 4.0], [2, 2]) + # test_array_to_xml("array1", [1.0, 2.0, 3.0, 4.0], [4]) + # test_array_to_xml("array2", [1.0, 2.0, 3.0, 4.0], [2, 2]) + # test_array_output_to_xml("array1", [1.0, 2.0, 3.0, 4.0], [4]) + # test_array_output_to_xml("array2", [1.0, 2.0, 3.0, 4.0], [2, 2]) + # test_array_output_to_xml("array3", [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], [2, 2, 2]) + # test_ModelVariable_getter(Boolean, False) + # test_ModelVariable_getter(UInt64, py_types['UInt64'](23)) + # test_ModelVariable_setter(UInt64, py_types['UInt64'](23)) \ No newline at end of file diff --git a/tests/test_working_directory/.gitignore b/tests/test_working_directory/.gitignore new file mode 100644 index 0000000..53f6747 --- /dev/null +++ b/tests/test_working_directory/.gitignore @@ -0,0 +1,4 @@ +*test*.pdf +*.xml +*.fmu +*.dat