{"id":26891989,"url":"https://github.com/dnv-opensource/component-model","last_synced_at":"2025-10-15T02:26:34.247Z","repository":{"id":259430829,"uuid":"863945674","full_name":"dnv-opensource/component-model","owner":"dnv-opensource","description":"Python package to build component models as FMUs following DNV-RP-0513","archived":false,"fork":false,"pushed_at":"2025-03-30T20:17:09.000Z","size":3791,"stargazers_count":2,"open_issues_count":5,"forks_count":2,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-03-30T21:24:39.660Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dnv-opensource.png","metadata":{"files":{"readme":"README.rst","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-09-27T07:53:48.000Z","updated_at":"2024-11-13T10:23:13.000Z","dependencies_parsed_at":"2024-10-25T10:19:44.398Z","dependency_job_id":"301759f6-5621-4014-bed9-0730ae699c10","html_url":"https://github.com/dnv-opensource/component-model","commit_stats":null,"previous_names":["dnv-opensource/component-model"],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dnv-opensource%2Fcomponent-model","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dnv-opensource%2Fcomponent-model/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dnv-opensource%2Fcomponent-model/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dnv-opensource%2Fcomponent-model/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dnv-opensource","download_url":"https://codeload.github.com/dnv-opensource/component-model/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246552882,"owners_count":20795838,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-03-31T22:48:47.586Z","updated_at":"2025-10-15T02:26:29.212Z","avatar_url":"https://github.com/dnv-opensource.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"Introduction\n============\nThe package extends the `PythonFMU package \u003chttps://github.com/NTNU-IHB/PythonFMU\u003e`_.\nIt includes the necessary modules to construct a component model according to the fmi, OSP and DNV-RP-0513 standards\nwith focus on the following features:\n\n* seamless translation of a Python model to an FMU package with minimal overhead (definition of FMU interface)\n* support of vector variables (numpy)\n* support of variable units and display units\n* support of range checking of variables\n\nFeatures which facilitate `Assurance of Simulation Models, DNV-RP-0513 \u003chttps://standards.dnv.com/explorer/document/6A4F5922251B496B9216572C23730D33/2\u003e`_\nshall have a special focus in this package.\n\nInstallation\n------------\n\n``pip install component-model``\n\n\nGetting Started\n---------------\nA new model can consist of any python code. To turn the python code into an FMU the following is necessary\n\n#. The model code is wrapped into a Python class which inherits from `Model`\n#. The exposed interface variables (model parameters, input- and output connectors) are defined as `Variable` objects\n#. The `(model).do_step( time, dt)` function of the model class is extended with model internal code,\n   i.e. model evolves from `time` to `time+dt`.\n#. Calling the method `Model.build()` will then compile the FMU and package it into a suitable FMU file.\n\nSee the files `example_models/bouncing_ball.py` and `tests/test_make_bouncingBall.py` supplied with this package\nas a simple example of this process. The first file defines the model class\nand the second file demonstrates the process of making the FMU and using it within fmpy and OSP.\n\n\nUsage example\n-------------\nThis is another BouncingBall example, using 3D vectors and units.\n\n.. code-block:: python\n\n   from math import sqrt\n\n   import numpy as np\n\n   from component_model.model import Model\n   from component_model.variable import Variable\n\n\n   class BouncingBall3D(Model):\n      \"\"\"Another Python-based BouncingBall model, using PythonFMU to construct a FMU.\n\n      Special features:\n\n      * The ball has a 3-D vector as position and speed\n      * As output variable the model estimates the next bouncing point\n      * As input variables, the restitution coefficient `e`, the gravitational acceleration `g`\n         and the initial speed can be changed.\n      * Internal units are SI (m,s,rad)\n\n      Args:\n         pos (np.array)=(0,0,1): The 3-D position in of the ball at time [m]\n         speed (np.array)=(1,0,0): The 3-D speed of the ball at time [m/s]\n         g (float)=9.81: The gravitational acceleration [m/s^2]\n         e (float)=0.9: The coefficient of restitution (dimensionless): |speed after| / |speed before| collision\n         min_speed_z (float)=1e-6: The minimum speed in z-direction when bouncing stops [m/s]\n      \"\"\"\n\n      def __init__(\n         self,\n         name: str = \"BouncingBall3D\",\n         description=\"Another Python-based BouncingBall model, using Model and Variable to construct a FMU\",\n         pos: tuple = (\"0 m\", \"0 m\", \"10 inch\"),\n         speed: tuple = (\"1 m/s\", \"0 m/s\", \"0 m/s\"),\n         g: float = \"9.81 m/s^2\",\n         e: float = 0.9,\n         min_speed_z: float = 1e-6,\n         **kwargs,\n      ):\n         super().__init__(name, description, author=\"DNV, SEACo project\", **kwargs)\n         self._pos = self._interface(\"pos\", pos)\n         self._speed = self._interface(\"speed\", speed)\n         self._g = self._interface(\"g\", g)\n         self.a = np.array((0, 0, -self.g), float)\n         self._e = self._interface(\"e\", e)\n         self.min_speed_z = min_speed_z\n         self.stopped = False\n         self.time = 0.0\n         self._p_bounce = self._interface(\"p_bounce\", (\"0m\", \"0m\", \"0m\"))  # Note: 3D, but z always 0\n         self.t_bounce, self.p_bounce = (-1.0, self.pos)  # provoke an update at simulation start\n\n      def do_step(self, _, dt):\n         \"\"\"Perform a simulation step from `self.time` to `self.time + dt`.\n\n         With respect to bouncing (self.t_bounce should be initialized to a negative value)\n         .t_bounce \u003c= .time: update .t_bounce\n         .time \u003c .t_bounce \u003c= .time+dt: bouncing happens within time step\n         .t_bounce \u003e .time+dt: no bouncing. Just advance .pos and .speed\n         \"\"\"\n         if not super().do_step(self.time, dt):\n               return False\n         if self.t_bounce \u003c self.time:  # calculate first bounce\n               self.t_bounce, self.p_bounce = self.next_bounce()\n         while self.t_bounce \u003c= self.time + dt:  # bounce happens within step or at border\n               dt1 = self.t_bounce - self.time\n               self.pos = self.p_bounce\n               self.speed += self.a * dt1  # speed before bouncing\n               self.speed[2] = -self.speed[2]  # speed after bouncing if e==1.0\n               self.speed *= self.e  # speed reduction due to coefficient of restitution\n               if self.speed[2] \u003c self.min_speed_z:\n                  self.stopped = True\n                  self.a[2] = 0.0\n                  self.speed[2] = 0.0\n                  self.pos[2] = 0.0\n               self.time += dt1  # jump to the exact bounce time\n               dt -= dt1\n               self.t_bounce, self.p_bounce = self.next_bounce()  # update to the next bounce\n         if dt \u003e 0:\n               # print(f\"pos={self.pos}, speed={self.speed}, a={self.a}, dt={dt}\")\n               self.pos += self.speed * dt + 0.5 * self.a * dt**2\n               self.speed += self.a * dt\n               self.time += dt\n         if self.pos[2] \u003c 0:\n               self.pos[2] = 0\n         return True\n\n      def next_bounce(self):\n         \"\"\"Calculate time of next bounce and position where the ground will be hit,\n         based on .time, .pos and .speed.\n         \"\"\"\n         if self.stopped:  # stopped bouncing\n               return (1e300, np.array((1e300, 1e300, 0), float))\n         else:\n               dt_bounce = (self.speed[2] + sqrt(self.speed[2] ** 2 + 2 * self.g * self.pos[2])) / self.g\n               p_bounce = self.pos + self.speed * dt_bounce  # linear. not correct for z-direction!\n               p_bounce[2] = 0\n               return (self.time + dt_bounce, p_bounce)\n\n      def setup_experiment(self, start: float):\n         \"\"\"Set initial (non-interface) variables.\"\"\"\n         super().setup_experiment(start)\n         self.stopped = False\n         self.time = start\n\n      def exit_initialization_mode(self):\n         \"\"\"Initialize the model after initial variables are set.\"\"\"\n         super().exit_initialization_mode()\n         self.a = np.array((0, 0, -self.g), float)\n\n      def _interface(self, name: str, start: float | tuple):\n         \"\"\"Define a FMU2 interface variable, using the variable interface.\n\n         Args:\n               name (str): base name of the variable\n               start (str|float|tuple): start value of the variable (optionally with units)\n\n         Returns:\n               the variable object. As a side effect the variable value is made available as self.\u003cname\u003e\n         \"\"\"\n         if name == \"pos\":\n               return Variable(\n                  self,\n                  name=\"pos\",\n                  description=\"The 3D position of the ball [m] (height in inch as displayUnit example.\",\n                  causality=\"output\",\n                  variability=\"continuous\",\n                  initial=\"exact\",\n                  start=start,\n                  rng=((0, \"100 m\"), None, (0, \"10 m\")),\n               )\n         elif name == \"speed\":\n               return Variable(\n                  self,\n                  name=\"speed\",\n                  description=\"The 3D speed of the ball, i.e. d pos / dt [m/s]\",\n                  causality=\"output\",\n                  variability=\"continuous\",\n                  initial=\"exact\",\n                  start=start,\n                  rng=((0, \"1 m/s\"), None, (\"-100 m/s\", \"100 m/s\")),\n               )\n         elif name == \"g\":\n               return Variable(\n                  self,\n                  name=\"g\",\n                  description=\"The gravitational acceleration (absolute value).\",\n                  causality=\"parameter\",\n                  variability=\"fixed\",\n                  start=start,\n                  rng=(),\n               )\n         elif name == \"e\":\n               return Variable(\n                  self,\n                  name=\"e\",\n                  description=\"The coefficient of restitution, i.e. |speed after| / |speed before| bounce.\",\n                  causality=\"parameter\",\n                  variability=\"fixed\",\n                  start=start,\n                  rng=(),\n               )\n         elif name == \"p_bounce\":\n               return Variable(\n                  self,\n                  name=\"p_bounce\",\n                  description=\"The expected position of the next bounce as 3D vector\",\n                  causality=\"output\",\n                  variability=\"continuous\",\n                  start=start,\n                  rng=(),\n               )\n\n\n\nThe following might be noted:\n\n- The interface variables are defined in a separate local method ``_interface_variables``,\n  keeping it separate from the model code.\n- The ``do_step()`` method contains the essential code, describing how the ball moves through the air.\n  It calls the ``super().do_step()`` method, which is essential to link it to ``Model``.\n  The `return True` statement is also essential for the working of the emerging FMU.\n- The ``next_bounce()`` method is a helper method.\n- In addition to the extension of ``do_step()``, here also the ``setup_experiment()`` method is extended.\n  Local (non-interface) variables can thus be initialized in a convenient way.\n\nIt should be self-evident that thorough testing of any model is necessary **before** translation to a FMU.\nThe simulation orchestration engine (e.g. OSP) used to run FMUs obfuscates error messages,\nsuch that first stage assurance of a model should aways done using e.g. ``pytest``.\nThe minimal code to make the FMU file package is\n\n\n.. code-block:: python\n\n   from component_model.model import Model\n   from fmpy.util import fmu_info\n\n   asBuilt = Model.build(\"../component_model/example_models/bouncing_ball.py\")\n   info = fmu_info(asBuilt.name)  # not necessary, but it lists essential properties of the FMU\n\n\nThe model can then be run using `fmpy \u003chttps://pypi.org/project/FMPy/\u003e`_\n\n.. code-block:: python\n\n   from fmpy import plot_result, simulate_fmu\n\n   result = simulate_fmu(\n      \"BouncingBall.fmu\",\n      stop_time=3.0,\n      step_size=0.1,\n      validate=True,\n      solver=\"Euler\",\n      debug_logging=True,\n      logger=print,\n      start_values={\"pos[2]\": 2}, # optional start value settings\n   )\n   plot_result(result)\n\n\nSimilarly, the model can be run using `OSP \u003chttps://opensimulationplatform.com/\u003e`_\n(or rather `libcosimpy \u003chttps://pypi.org/project/libcosimpy/\u003e`_ - OSP wrapped into Python):\n\n.. code-block:: Python\n\n   from libcosimpy.CosimEnums import CosimExecutionState\n   from libcosimpy.CosimExecution import CosimExecution\n   from libcosimpy.CosimSlave import CosimLocalSlave\n\n   sim = CosimExecution.from_step_size(step_size=1e7)  # empty execution object with fixed time step in nanos\n   bb = CosimLocalSlave(fmu_path=\"./BouncingBall.fmu\", instance_name=\"bb\")\n\n   print(\"SLAVE\", bb, sim.status())\n\n   ibb = sim.add_local_slave(bb)\n   assert ibb == 0, f\"local slave number {ibb}\"\n\n   reference_dict = {var_ref.name.decode(): var_ref.reference for var_ref in sim.slave_variables(ibb)}\n\n   sim.real_initial_value(ibb, reference_dict[\"pos[2]\"], 2.0)  # Set initial values\n\n   sim_status = sim.status()\n   assert sim_status.current_time == 0\n   assert CosimExecutionState(sim_status.state) == CosimExecutionState.STOPPED\n   infos = sim.slave_infos()\n   print(\"INFOS\", infos)\n\n   sim.simulate_until(target_time=3e9)  # Simulate for 1 second\n\n\nThis is admittedly more complex than the ``fmpy`` example,\nbut it should be emphasised that fmpy is made for single component model simulation (testing),\nwhile OSP is made for multi-component systems.\n\n\nDevelopment Setup\n-----------------\n\n1. Install uv\n^^^^^^^^^^^^^\nThis project uses `uv` as package manager.\n\nIf you haven't already, install `uv \u003chttps://docs.astral.sh/uv/\u003e`_, preferably using it's `\"Standalone installer\" \u003chttps://docs.astral.sh/uv/getting-started/installation/#__tabbed_1_2/\u003e`_ method:\n\n..on Windows:\n\n``powershell -ExecutionPolicy ByPass -c \"irm https://astral.sh/uv/install.ps1 | iex\"``\n\n..on MacOS and Linux:\n\n``curl -LsSf https://astral.sh/uv/install.sh | sh``\n\n(see `docs.astral.sh/uv \u003chttps://docs.astral.sh/uv/getting-started/installation//\u003e`_ for all / alternative installation methods.)\n\nOnce installed, you can update `uv` to its latest version, anytime, by running:\n\n``uv self update``\n\n2. Install Python\n^^^^^^^^^^^^^^^^^\nThis project requires Python 3.10 or later.\n\nIf you don't already have a compatible version installed on your machine, the probably most comfortable way to install Python is through ``uv``:\n\n``uv python install``\n\nThis will install the latest stable version of Python into the uv Python directory, i.e. as a uv-managed version of Python.\n\nAlternatively, and if you want a standalone version of Python on your machine, you can install Python either via ``winget``:\n\n``winget install --id Python.Python``\n\nor you can download and install Python from the `python.org \u003chttps://www.python.org/downloads//\u003e`_ website.\n\n3. Clone the repository\n^^^^^^^^^^^^^^^^^^^^^^^\nClone the component-model repository into your local development directory:\n\n``git clone https://github.com/dnv-opensource/component-model path/to/your/dev/component-model``\n\n4. Install dependencies\n^^^^^^^^^^^^^^^^^^^^^^^\nRun ``uv sync`` to create a virtual environment and install all project dependencies into it:\n\n``uv sync``\n\n5. (Optional) Activate the virtual environment\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nWhen using ``uv``, there is in almost all cases no longer a need to manually activate the virtual environment.\n\n``uv`` will find the ``.venv`` virtual environment in the working directory or any parent directory, and activate it on the fly whenever you run a command via `uv` inside your project folder structure:\n\n``uv run \u003ccommand\u003e``\n\nHowever, you still *can* manually activate the virtual environment if needed.\nWhen developing in an IDE, for instance, this can in some cases be necessary depending on your IDE settings.\nTo manually activate the virtual environment, run one of the \"known\" legacy commands:\n\n..on Windows:\n\n``.venv\\Scripts\\activate.bat``\n\n..on Linux:\n\n``source .venv/bin/activate``\n\n6. Install pre-commit hooks\n^^^^^^^^^^^^^^^^^^^^^^^^^^^\nThe ``.pre-commit-config.yaml`` file in the project root directory contains a configuration for pre-commit hooks.\nTo install the pre-commit hooks defined therein in your local git repository, run:\n\n``uv run pre-commit install``\n\nAll pre-commit hooks configured in ``.pre-commit-config.yam`` will now run each time you commit changes.\n\n7. Test that the installation works\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nTo test that the installation works, run pytest in the project root folder:\n\n``uv run pytest``\n\n\nMeta\n----\nCopyright (c) 2025 `DNV \u003chttps://www.dnv.com/\u003e`_ AS. All rights reserved.\n\nSiegfried Eisinger - siegfried.eisinger@dnv.com\n\nDistributed under the MIT license. See `LICENSE \u003cLICENSE.md/\u003e`_ for more information.\n\n`https://github.com/dnv-opensource/component-model \u003chttps://github.com/dnv-opensource/component-model/\u003e`_\n\nContribute\n----------\nAnybody in the FMU and OSP community is welcome to contribute to this code, to make it better,\nand especially including other features from model assurance,\nas we firmly believe that trust in our models is needed\nif we want to base critical decisions on the support from these models.\n\nTo contribute, follow these steps:\n\n1. Fork it `\u003chttps://github.com/dnv-opensource/component-model/fork/\u003e`_\n2. Create an issue in your GitHub repo\n3. Create your branch based on the issue number and type (``git checkout -b issue-name``)\n4. Evaluate and stage the changes you want to commit (``git add -i``)\n5. Commit your changes (``git commit -am 'place a descriptive commit message here'``)\n6. Push to the branch (``git push origin issue-name``)\n7. Create a new Pull Request in GitHub\n\nFor your contribution, please make sure you follow the `STYLEGUIDE \u003cSTYLEGUIDE.md/\u003e`_ before creating the Pull Request.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdnv-opensource%2Fcomponent-model","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdnv-opensource%2Fcomponent-model","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdnv-opensource%2Fcomponent-model/lists"}