Giter VIP home page Giter VIP logo

fmpy's Introduction

Build Status PyPI Conda Read the Docs

FMPy

FMPy is a free Python library to simulate Functional Mock-up Units (FMUs) that...

Installation

Several options are available:

  • Install with conda: conda install -c conda-forge fmpy
  • Install with from PyPI: python -m pip install fmpy[complete]
  • Install a development build

If you don't have Python on your machine you can install Miniforge.

Start the Graphical User Interface

You can start the FMPy GUI with python -m fmpy.gui

FMPy GUI

Simulate an FMU in Python

To follow this example download Rectifier.fmu for your platform by clicking on the respective link: Linux, macOS, Windows. Change to the folder where you've saved the FMU and open a Python prompt.

>>> from fmpy import *
>>> fmu = 'Rectifier.fmu'
>>> dump(fmu)  # get information

Model Info

  FMI Version       2.0
  Model Name        Rectifier
  Description       Model Rectifier
  Platforms         win64
  Continuous States 4
  Event Indicators  6
  Variables         63
  Generation Tool   MapleSim (1267140/1267140/1267140)
  Generation Date   2017-10-04T12:07:10Z

Default Experiment

  Stop Time         0.1
  Step Size         1e-07

Variables (input, output)

Name                Causality          Start Value  Unit     Description
outputs             output        282.842712474619  V        Rectifier1.Capacitor1.v
>>> result = simulate_fmu(fmu)         # simulate the FMU
>>> from fmpy.util import plot_result  # import the plot function
>>> plot_result(result)                # plot two variables

Rectifier Result

Simulate an FMU on the command line

To get information about an FMU directly from the command line change to the folder where you've saved the FMU and enter

fmpy info Rectifier.fmu

Simulate the FMU and plot the results

fmpy simulate Rectifier.fmu --show-plot

Get more information about the available options

fmpy --help

Create a Jupyter Notebook

To create a Jupyter Notebook open an FMU in the FMPy GUI and select Tools > Create Jupyter Notebook... or run

fmpy create-jupyter-notebook Rectifier.fmu

on the command line and open the notebook in Jupyter with

jupyter notebook Rectifier.ipynb

Web App

Start the Web App

The FMPy Web App is built with Dash and a great way to share your FMUs with anyone that has a web browser. To start it run

python -m fmpy.webapp Rectifier.fmu

on the command line or use --help for more options.

Web App

Advanced Usage

To learn more about how to use FMPy in you own scripts take a look at the coupled_clutches.py, custom_input.py and parameter_variation.py examples.

Commercial Support

You're starting a project, need training or professional support? Our partners at LTX Simulation are ready to help you. Please send an e-mail to [email protected] for a quote.


© 2023 Dassault Systèmes

fmpy's People

Contributors

m-kessler avatar mjclarke94 avatar nl78 avatar t-sommer avatar thorade avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fmpy's Issues

Change parameter values and modify variables for output

Within the Modelica model one can set some default values for parameters. Also, one can define variables for output. However, for a very complicated model, sometimes it is very difficult to output every desired variable, e.g., protected variables. Therefore, is it possible to modify parameter values and add output variables using Python code or the fmpy.gui?

FMPy and Dymola parallelization

I'm generating a Co-Simulation FMU using Dymola. The FMU is consumed by FMPy. There are external thermodynamic calls in the model.

When the Dymola flag Advanced.ParallelizeCode is set to false, the FMU can be run using FMPy and Dymola. When the Dymola flag Advanced.ParallelizeCode is set to true, the FMU can be run using Dymola but not using FMPy.

What can be causing this issue?

Thanks!

Changing parameter values in the modeldescription.xml-file is dangerous

In FMPy 0.2.3., writing new parameter values to the xml file has been introduced.
However, this is dangerous, as it is not specified, whether an importing tool should consider these values or the hard coded values, see this discussion: [https://trac.fmi-standard.org/ticket/387].
Strictly speaking, changing the modeldescription.xml could even invalidate the FMU (consistency of xml and binary could be checked by creating a GUID with by a checksum.
The clean way to support changed parameter and even different parameter sets is the coming SSP standard.

Number of Samples

Looking at the source code for command_line.py, (specifically this line), I don't see how this command line parameter has any effect. It doesn't appear as though the value extracted from the command line is used anywhere.

Am I missing something?

Permission Error with DYMOLA FMU

Hi,

I am facing an issue (dll not unlinked, see error message below) with FMUs generated with Dymola (tested with Versions 2017FD01, 2018FD01). The simple example below works fine, when using the FMU provided by the following link:

https://trac.fmi-standard.org/browser/branches/public/Test_FMUs/FMI_2.0/ModelExchange/win64/Dymola/2017/CoupledClutches/CoupledClutches.fmu

I am working with Python 3.6.2 (see installed packages below) and I am using the FMPy develop branch (the problem also occurs on the master branch release 0.2.1).

It seems that the dll is not unlinked properly. Inspecting threads I found the following line:

Modelica_Mechanics_Rotational_Examples_CoupledClutches_DYMOLA2017FD01.dll!fmi2GetStringStatus+0x5bbec

Thanks!
Alexander

Export FMU (checked settings):

Type: Model Exchange
Version: 2.0
Binaries: 32-bit, 64-bit
Model description filters: Protected variables
Options: Copy resources to FMU, Show dialog when exporting

Simple example:

from fmpy import simulate_fmu

#filename = 'fmus/Modelica_Mechanics_Rotational_Examples_CoupledClutches_DYMOLA2018FD01.fmu'
filename = 'fmus/Modelica_Mechanics_Rotational_Examples_CoupledClutches_DYMOLA2017FD01.fmu'
# filename = 'fmus/Dymola2017/CoupledClutches.fmu'

simulate_fmu(
    filename=filename,
    start_time=0,
    stop_time=1.5,
    solver='CVode',
    step_size=1e-2,
    output_interval=2e-2,
    input=None,
    output=None,
    validate=False,
    fmi_logging=False)

Error message:

---------------------------------------------------------------------------
PermissionError                           Traceback (most recent call last)
<ipython-input-11-a27bbb9b9121> in <module>()
     17     output=None,
     18     validate=False,
---> 19     fmi_logging=False)

c:\users\opa2si1\documents\git_projects\fmpy\fmpy\simulation.py in simulate_fmu(filename, validate, start_time, stop_time, solver, step_size, relative_tolerance, output_interval, fmi_type, use_source_code, start_values, input, output, timeout, fmi_logging, logger, step_finished)
    435 
    436     # clean up
--> 437     shutil.rmtree(unzipdir)
    438 
    439     return result

~\AppData\Local\conda\conda\envs\FMPy_issue_PermissionError\lib\shutil.py in rmtree(path, ignore_errors, onerror)
    492             os.close(fd)
    493     else:
--> 494         return _rmtree_unsafe(path, onerror)
    495 
    496 # Allow introspection of whether or not the hardening against symlink

~\AppData\Local\conda\conda\envs\FMPy_issue_PermissionError\lib\shutil.py in _rmtree_unsafe(path, onerror)
    382             mode = 0
    383         if stat.S_ISDIR(mode):
--> 384             _rmtree_unsafe(fullname, onerror)
    385         else:
    386             try:

~\AppData\Local\conda\conda\envs\FMPy_issue_PermissionError\lib\shutil.py in _rmtree_unsafe(path, onerror)
    382             mode = 0
    383         if stat.S_ISDIR(mode):
--> 384             _rmtree_unsafe(fullname, onerror)
    385         else:
    386             try:

~\AppData\Local\conda\conda\envs\FMPy_issue_PermissionError\lib\shutil.py in _rmtree_unsafe(path, onerror)
    387                 os.unlink(fullname)
    388             except OSError:
--> 389                 onerror(os.unlink, fullname, sys.exc_info())
    390     try:
    391         os.rmdir(path)

~\AppData\Local\conda\conda\envs\FMPy_issue_PermissionError\lib\shutil.py in _rmtree_unsafe(path, onerror)
    385         else:
    386             try:
--> 387                 os.unlink(fullname)
    388             except OSError:
    389                 onerror(os.unlink, fullname, sys.exc_info())

PermissionError: [WinError 5] Access is denied: 'C:\\Users\\xxxxxxx\\AppData\\Local\\Temp\\tmp4v696d0o\\binaries\\win64\\Modelica_Mechanics_Rotational_Examples_CoupledClutches_DYMOLA2017FD01.dll'

requirements (platform: win-64):

bleach=1.5.0=py36_0
ca-certificates=2018.1.18=0
certifi=2016.2.28=py36_0
colorama=0.3.9=py36_0
decorator=4.1.2=py36_0
entrypoints=0.2.3=py36_0
html5lib=0.9999999=py36_0
icu=58.2=vc14_0
ipykernel=4.6.1=py36_0
ipython=6.1.0=py36_0
ipython_genutils=0.2.0=py36_0
ipywidgets=6.0.0=py36_0
jedi=0.10.2=py36_2
jinja2=2.9.6=py36_0
jpeg=9b=vc14_2
jsonschema=2.6.0=py36_0
jupyter=1.0.0=py36_3
jupyter_client=5.1.0=py36_0
jupyter_console=5.2.0=py36_0
jupyter_core=4.3.0=py36_0
libpng=1.6.34=vc14_0
lxml=3.8.0=py36_0
markupsafe=1.0=py36_0
mistune=0.7.4=py36_0
mkl=2017.0.3=0
nbconvert=5.2.1=py36_0
nbformat=4.4.0=py36_0
notebook=5.0.0=py36_0
numpy=1.13.1=py36_0
openssl=1.0.2n=vc14_0
pandocfilters=1.4.2=py36_0
path.py=10.3.1=py36_0
pathlib=1.0.1=py36_0
pickleshare=0.7.4=py36_0
pip=9.0.1=py36_1
prompt_toolkit=1.0.15=py36_0
pygments=2.2.0=py36_0
pyqt=5.6.0=py36_2
python=3.6.2=0
python-dateutil=2.6.1=py36_0
pywin32=220=py36_2
pyzmq=16.0.2=py36_0
qt=5.6.2=vc14_1
qtconsole=4.3.1=py36_0
setuptools=36.4.0=py36_1
simplegeneric=0.8.1=py36_1
sip=4.18=py36_0
six=1.10.0=py36_0
testpath=0.3.1=py36_0
tornado=4.5.2=py36_0
traitlets=4.3.2=py36_0
vc=14=0
vs2015_runtime=14.0.25420=0
wcwidth=0.1.7=py36_0
wheel=0.29.0=py36_0
widgetsnbextension=3.0.2=py36_0
wincertstore=0.2=py36_0
zlib=1.2.11=vc14_0

list.clear() method is not available under Python 2.x

self.rootItem.children.clear()

Can't use fmpy.gui under Python 2.7.12 due to:

Traceback (most recent call last):
  File "/home/user/.local/lib/python2.7/site-packages/fmpy/gui/__main__.py", line 468, in open
    self.load(filename)
  File "/home/user/.local/lib/python2.7/site-packages/fmpy/gui/__main__.py", line 399, in load
    self.treeModel.setModelDescription(md)
  File "/home/user/.local/lib/python2.7/site-packages/fmpy/gui/model.py", line 197, in setModelDescription
    self.rootItem.children.clear()
AttributeError: 'list' object has no attribute 'clear'
Aborted (core dumped)

Misleading error message in case of wrong fmi_type argument

If the user specifies an invalid fmi_type, e.g. fmi_type='CoSimulation for a ME-only FMU, this is not caught during the argument checks below:

FMPy/fmpy/simulation.py

Lines 355 to 360 in 35245dd

if fmi_type is None:
# determine the FMI type automatically
fmi_type = 'CoSimulation' if modelDescription.coSimulation is not None else 'ModelExchange'
if fmi_type not in ['ModelExchange', 'CoSimulation']:
raise Exception('fmi_type must be one of "ModelExchange" or "CoSimulation"')

You will get another error from some later code where fmi_type is used (even if it is wrong).

Sorry, I can't provide a PR yet, but the fix is easy by checking if the FMU really supports the given mode, e.g.:

if fmi_type is not None:
    if (fmi_type == 'CoSimulation' and not modelDescription.coSimulation) or \
            (fmi_type == 'ModelExchange' and not modelDescription.modelExchange):
        raise ValueError("Invalid choice. FMU doesn't support fmi_type=%r" % fmi_type)

model_description.py typeDefinitions Fail to Support Enumerations

There is a comment in the model_description.py file that notes:
#TODO: add enumeration items

While at first glance this appears to be a relatively insignificant feature, it would absolutely be a benefit to users if it could be added.

As an example, I am working on a tool to run FMUs within Python using FMPy, and then present the results to a user who may not be familiar with the code/architecture of the FMU. To provide clear results to the user, it is important to be able to display enumeration values not only as their integer values but also as their 'name' or 'description' strings so that the user gains insight.

I am still just learning Python or I would try to tackle this problem myself, but I would appreciate if you have the time to work at this feature.

Thank you,
Justin

install without internet connection?

Is there a possibility to install the package without needing an interent connection? I have tried all the possible ways to install (apart from PIP) and all have failed due to connect timeouts. I suppose the problem in my case lies in the firewall of the company or in a proxy setting.
What is an aternative to this? Can one download the package and just install it?
Thanks in advance for any hint.

Emmanuel

Citing FMPy

Hi,
I'm using FMPy for my research. Is there a specific format to cite this tool? For example in BibTex format?

serialize FMU state

Hey
i realized that FMPy doesn't bring the option to serialize an FMU state. It would be really nice if you implement this feature FMI Feature (fmi2SerializeFMUstate) because the FMU states couldn't be stored by pickle. Or do you have any other idea how to store them?

Setup start value for the custom input example

Hi, in the coupled_clutches.py example one can set the start value using the simulate_fmu functionality. Is there a similar way to modify the start value (of a parameter) for an FMU instance? For example, how to modify the start value for the FMU in the custom_input.py example? To be specific, the parameter might have the following property, and I would like to modify the value 1.
<ScalarVariable name="friction" valueReference="111" description="Friction coefficient" causality="parameter" variability="tunable"> <Real start="1"/>

Cannot simulate example parameter_variation.py on Linux

https://trac.fmi-standard.org does not contain Rectifier.fmu for linux64/Dymola.
When I try to simulate parameter_variation.py on Linux I get the following error:

Exception: Failed to download https://trac.fmi-standard.org/export/HEAD/branches/public/Test_FMUs/FMI_2.0/CoSimulation/linux64/Dymola/2017/Rectifier/Rectifier.fmu (status code: 404)

Other examples run fine. It would be helpful to mark OS-dependent tests and maybe disable them on unsupported platforms.

(Thanks for your work on this package 👍 )

Simulating an FMU with no outputs produced by OpenModelica 0.13 nightly results in 'Bad file descriptor' exception in Ubuntu 16.04 with Python 2.7

I notice that simulating an FMU with no outputs creates a 'Bad file descriptor' exception in Ubuntu 16.04, and it leaves the interpreter hanging.

To replicate the problem, this is the FMU file (renamed to .fmu.zip to comply to GitHub's restrictions on attaching files to issues) NoOutputSystem.fmu.zip that is creating the problem, that was generated using OpenModelica from this Modelica model:

model NoOutputSystem
  Real x "An unknown";
initial equation
  x = 0.9 "Used before simulation to compute initial values";
equation
  der(x) = -x+x*x*x;
  annotation(experiment(StartTime=0,StopTime=10));
end NoOutputSystem;

This is the error:

traversaro@turati:~/: ipython
Python 2.7.12 (default, Nov 20 2017, 18:23:56) 
In [1]: import fmpy

In [2]: fmu = "NoOutputSystem.fmu"

In [3]: fmpy.simulate_fmu(fmu)
Out[3]: 
array([(0.02,), (0.04,), (0.08,), (0.1,), (0.12000000000000001,), (0.14,),
       (0.18,), (0.21999999999999997,), (0.25999999999999995,),
       (0.27999999999999997,), (0.3,), (0.32,), (0.34,),
       (0.36000000000000004,), (0.38000000000000006,),
       (0.4000000000000001,), (0.4200000000000001,), (0.4400000000000001,),
       (0.46000000000000013,), (0.48000000000000015,),
       (0.5200000000000001,), (0.5400000000000001,), (0.5600000000000002,),
       (0.5800000000000002,), (0.6000000000000002,), (0.6200000000000002,),
       (0.6400000000000002,), (0.6600000000000003,), (0.6800000000000003,),
       (0.7000000000000003,), (0.7200000000000003,), (0.7400000000000003,),
       (0.7600000000000003,), (0.7800000000000004,), (0.8000000000000004,),
       (0.8200000000000004,), (0.8400000000000004,), (0.8600000000000004,),
       (0.8800000000000004,), (0.9000000000000005,), (0.9200000000000005,),
       (0.9400000000000005,), (0.9600000000000005,), (0.9800000000000005,),
       (1.0200000000000005,), (1.0400000000000005,), (1.0600000000000005,),
       (1.0800000000000005,), (1.1000000000000005,), (1.1200000000000006,),
       (1.1400000000000006,), (1.1600000000000006,), (1.1800000000000006,),
       (1.2000000000000006,), (1.2200000000000006,), (1.2400000000000007,),
       (1.2600000000000007,), (1.2800000000000007,), (1.3000000000000007,),
       (1.3200000000000007,), (1.3400000000000007,), (1.3600000000000008,),
       (1.3800000000000008,), (1.4000000000000008,), (1.4200000000000008,),
       (1.4400000000000008,), (1.4600000000000009,), (1.4800000000000009,),
       (1.5000000000000009,), (1.520000000000001,), (1.540000000000001,),
       (1.560000000000001,), (1.580000000000001,), (1.600000000000001,),
       (1.620000000000001,), (1.640000000000001,), (1.660000000000001,),
       (1.680000000000001,), (1.700000000000001,), (1.720000000000001,),
       (1.740000000000001,), (1.7600000000000011,), (1.7800000000000011,),
       (1.8000000000000012,), (1.8200000000000012,), (1.8400000000000012,),
       (1.8600000000000012,), (1.8800000000000012,), (1.9000000000000012,),
       (1.9200000000000013,), (1.9400000000000013,), (1.9600000000000013,),
       (1.9800000000000013,), (2.0000000000000013,), (2.0200000000000014,),
       (2.0400000000000014,), (2.0600000000000014,), (2.0800000000000014,),
       (2.1000000000000014,), (2.1200000000000014,), (2.1400000000000015,),
       (2.1600000000000015,), (2.1800000000000015,), (2.2000000000000015,),
       (2.2200000000000015,), (2.2400000000000015,), (2.2600000000000016,),
       (2.2800000000000016,), (2.3000000000000016,), (2.3200000000000016,),
       (2.3400000000000016,), (2.3600000000000017,), (2.3800000000000017,),
       (2.4000000000000017,), (2.4200000000000017,), (2.4400000000000017,),
       (2.4600000000000017,), (2.4800000000000018,), (2.5000000000000018,),
       (2.520000000000002,), (2.540000000000002,), (2.560000000000002,),
       (2.580000000000002,), (2.600000000000002,), (2.620000000000002,),
       (2.640000000000002,), (2.660000000000002,), (2.680000000000002,),
       (2.700000000000002,), (2.720000000000002,), (2.740000000000002,),
       (2.760000000000002,), (2.780000000000002,), (2.800000000000002,),
       (2.820000000000002,), (2.840000000000002,), (2.860000000000002,),
       (2.880000000000002,), (2.900000000000002,), (2.920000000000002,),
       (2.940000000000002,), (2.960000000000002,), (2.980000000000002,),
       (3.000000000000002,), (3.0200000000000022,), (3.0400000000000023,),
       (3.0600000000000023,), (3.0800000000000023,), (3.1000000000000023,),
       (3.1200000000000023,), (3.1400000000000023,), (3.1600000000000024,),
       (3.1800000000000024,), (3.2000000000000024,), (3.2200000000000024,),
       (3.2400000000000024,), (3.2600000000000025,), (3.2800000000000025,),
       (3.3000000000000025,), (3.3200000000000025,), (3.3400000000000025,),
       (3.3600000000000025,), (3.3800000000000026,), (3.4000000000000026,),
       (3.4200000000000026,), (3.4400000000000026,), (3.4600000000000026,),
       (3.4800000000000026,), (3.5000000000000027,), (3.5200000000000027,),
       (3.5400000000000027,), (3.5600000000000027,), (3.5800000000000027,),
       (3.6000000000000028,), (3.6200000000000028,), (3.640000000000003,),
       (3.660000000000003,), (3.680000000000003,), (3.700000000000003,),
       (3.720000000000003,), (3.740000000000003,), (3.760000000000003,),
       (3.780000000000003,), (3.800000000000003,), (3.820000000000003,),
       (3.840000000000003,), (3.860000000000003,), (3.880000000000003,),
       (3.900000000000003,), (3.920000000000003,), (3.940000000000003,),
       (3.960000000000003,), (3.980000000000003,), (4.020000000000002,),
       (4.060000000000001,), (4.1000000000000005,), (4.14,),
       (4.179999999999999,), (4.219999999999998,), (4.259999999999997,),
       (4.299999999999996,), (4.339999999999995,), (4.379999999999995,),
       (4.419999999999994,), (4.459999999999993,), (4.499999999999992,),
       (4.539999999999991,), (4.57999999999999,), (4.6199999999999894,),
       (4.659999999999989,), (4.699999999999988,), (4.739999999999987,),
       (4.779999999999986,), (4.819999999999985,), (4.859999999999984,),
       (4.8999999999999835,), (4.939999999999983,), (4.979999999999982,),
       (5.019999999999981,), (5.05999999999998,), (5.099999999999979,),
       (5.139999999999978,), (5.1799999999999775,), (5.219999999999977,),
       (5.259999999999976,), (5.299999999999975,), (5.339999999999974,),
       (5.379999999999973,), (5.419999999999972,), (5.4599999999999715,),
       (5.499999999999971,), (5.53999999999997,), (5.579999999999969,),
       (5.619999999999968,), (5.659999999999967,), (5.699999999999966,),
       (5.739999999999966,), (5.779999999999965,), (5.819999999999964,),
       (5.859999999999963,), (5.899999999999962,), (5.939999999999961,),
       (5.9799999999999605,), (6.01999999999996,), (6.059999999999959,),
       (6.099999999999958,), (6.139999999999957,), (6.179999999999956,),
       (6.219999999999955,), (6.2599999999999545,), (6.299999999999954,),
       (6.339999999999953,), (6.379999999999952,), (6.419999999999951,),
       (6.45999999999995,), (6.499999999999949,), (6.5399999999999485,),
       (6.579999999999948,), (6.619999999999947,), (6.659999999999946,),
       (6.699999999999945,), (6.739999999999944,), (6.779999999999943,),
       (6.8199999999999426,), (6.859999999999942,), (6.899999999999941,),
       (6.93999999999994,), (6.979999999999939,), (7.019999999999938,),
       (7.059999999999937,), (7.099999999999937,), (7.139999999999936,),
       (7.179999999999935,), (7.219999999999934,), (7.259999999999933,),
       (7.299999999999932,), (7.3399999999999315,), (7.379999999999931,),
       (7.41999999999993,), (7.459999999999929,), (7.499999999999928,),
       (7.539999999999927,), (7.579999999999926,), (7.6199999999999255,),
       (7.659999999999925,), (7.699999999999924,), (7.739999999999923,),
       (7.779999999999922,), (7.819999999999921,), (7.85999999999992,),
       (7.8999999999999195,), (7.939999999999919,), (7.979999999999918,),
       (8.019999999999918,), (8.059999999999917,), (8.099999999999916,),
       (8.139999999999915,), (8.179999999999914,), (8.219999999999914,),
       (8.259999999999913,), (8.299999999999912,), (8.339999999999911,),
       (8.37999999999991,), (8.41999999999991,), (8.459999999999908,),
       (8.499999999999908,), (8.539999999999907,), (8.579999999999906,),
       (8.619999999999905,), (8.659999999999904,), (8.699999999999903,),
       (8.739999999999903,), (8.779999999999902,), (8.8199999999999,),
       (8.8599999999999,), (8.899999999999899,), (8.939999999999898,),
       (8.979999999999897,), (9.019999999999897,), (9.059999999999896,),
       (9.099999999999895,), (9.139999999999894,), (9.179999999999893,),
       (9.219999999999892,), (9.259999999999891,), (9.29999999999989,),
       (9.33999999999989,), (9.379999999999889,), (9.419999999999888,),
       (9.459999999999887,), (9.499999999999886,), (9.539999999999885,),
       (9.579999999999885,), (9.619999999999884,), (9.659999999999883,),
       (9.699999999999882,), (9.739999999999881,), (9.77999999999988,),
       (9.81999999999988,), (9.859999999999879,), (9.899999999999878,),
       (9.939999999999877,), (9.979999999999876,), (10.0,), (10.0,)], 
      dtype=[('time', '<f8')])

In [4]: Exception in thread Thread-38:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/local/lib/python2.7/dist-packages/prompt_toolkit/eventloop/inputhook.py", line 68, in thread
    input_is_ready_func(wait=True)
  File "/usr/local/lib/python2.7/dist-packages/prompt_toolkit/eventloop/posix.py", line 101, in ready
    return self._ready_for_reading(current_timeout[0] if wait else 0) != []
  File "/usr/local/lib/python2.7/dist-packages/prompt_toolkit/eventloop/posix.py", line 188, in _ready_for_reading
    fds = self.selector.select(timeout)
  File "/usr/local/lib/python2.7/dist-packages/prompt_toolkit/eventloop/select.py", line 100, in select
    return self._select_selector.select(timeout)
  File "/usr/local/lib/python2.7/dist-packages/prompt_toolkit/eventloop/select.py", line 182, in select
    return select.select(self._fds, [], [], timeout)[0]
error: (9, 'Bad file descriptor')

^[[70;1R

The same example works fine by turning "x" in a output variable.

Closed loop simulation

I see that one can simulate several FMUs with SSP. Is there a similar procedure for closed loop simulation? For example, a controller designed directly in Python and an FMU plant?

No module named fmpy.gui

Hi,

When trying to open the gui, it gives the following error.
No module named fmpy.gui.

Also, in the installation folder, there is no gui folder as the one in github.

Any idea why?

Thanks in advance.

Plot with matplotlib hangs on MacOS

While exploring the examples a ran into the following issue:

python -m fmpy.examples.coupled_clutches

Hangs at:

  Downloading https://trac.fmi-standard.org/export/HEAD/branches/public/Test_FMUs/FMI_2.0/ModelExchange/darwin64/Maple
  Sim/2016.2/CoupledClutches/CoupledClutches.fmu
  Downloading https://trac.fmi-standard.org/export/HEAD/branches/public/Test_FMUs/FMI_2.0/ModelExchange/darwin64/Maple
  Sim/2016.2/CoupledClutches/CoupledClutches_in.csv
  Loading input...
  Simulating CoupledClutches.fmu (FMI 2.0, ModelExchange, CVode)...
  Plotting results...

I added an extra import statement and matplotlib.use() call like suggested here which solved the issue.

...
import matplotlib
matplotlib.use('TkAgg')
...

Running Mac OS 10.13.2 (17C205)

Documenting input signals

The simulate_fmu function has a named input argument. However, it isn't clear what type of data is required there. The in-source documentation simple says a structured numpy array that contains the input, but that doesn't mean much to me.

I eventually figured out by tracing back through the Input class and the np.genfromtxt functions. But it would be nice to have something more explicit for how to build the data that is required.

ValueError: need more than 0 values to unpack

Hi,

While trying to run the example with the option "Simulate an FMU in Python", it gives the following error.

plot_result(result)
Traceback (most recent call last):
File "", line 1, in
File "C:\Python27\lib\site-packages\fmpy\util.py", line 299, in plot_result
fig.set_size_inches(w=8, h=1.5 * len(names), forward=True)
File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 667, in set_size_inches
w, h = args
ValueError: need more than 0 values to unpack

API Documentation?

Hi,

Though I am looking through the examples and source codes, it'd be great to read through actual API documentation, but I can't find one.

Thanks!

Tolerances for CVode

It would be beneficial to be able to set the absolute and relative tolerances for the CVode Solver and not use default values.

separation of initialization, simulation and termination

Hi Torsten,

in the current implementation, during every call of 'simulate_fmu()', the fmu is unzipped, intialized and after the run terminated and the temporary folder is deleted.
This is problematic for several (thousand) runs with the same fmu, e.g. Monte-Carlo. Would it be possible to re-structure and split the simulation in a init-, a run- and a terminate call, e.g. as a class:

class simulate_with_fmu(object):

   def __init__(self):
     unzipdir = extract(filename)
     fmu.initialize()
     ...

   def run():
      return simulateME()

   def __exit__(self):
       fmu.terminate()
       fmu.freeInstance()
       shutil.rmtree(unzipdir)

Can not simulate fmu file generated by OpenModelica

Hi,

I'm trying to control the simulation progress with Python, so I generated a fmu file of StableBouncingBall and import with FMPy. When I run simulate_fmu, I got an error "The current platform (win32) is not supported by the FMU". Then I read some lines of source file and added "use_source_code=True", hoping that FMPy will simulate with source-code. Then I got another error "No source files specified in the model description." But I unziped the fmu file and found .c and .h source file in the model.

The fmu file works fine in Matlab 2018 for both Co-Simulation and Model Exchange. Is there any way to solve this problem?

Best regards,
XY Fan

Simulation of Model Exchange FMUs on Raspberry Pi

Hello,

I simulated ModelCosimulation on Raspberry Pi and it work's very well. Now I tried to simulate a ModelExchange on Raspberry and it doesn't work.

I used following file /FMI_2.0/ModelExchange/c-code/Dymola/2017/CoupledClutches.fmu

Compilation worked with

fmpy compile CoupledClutches.fmu
By simulation I get some error

$ fmpy simulate CoupledClutches.fmu --show-plot
Traceback (most recent call last):
  File "/usr/local/bin/fmpy", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python3.5/dist-packages/fmpy/command_line.py", line 114, in main
    fmi_call_logger=fmi_call_logger)
  File "/usr/local/lib/python3.5/dist-packages/fmpy/simulation.py", line 507, in simulate_fmu
    result = simulateME(model_description, fmu_args, start_time, stop_time, solver, step_size, relative_tolerance, start_values, apply_default_start_values, input, output, output_interval, record_events, timeout, callbacks, debug_logging, step_finished)
  File "/usr/local/lib/python3.5/dist-packages/fmpy/simulation.py", line 595, in simulateME
    from .sundials import CVodeSolver
  File "/usr/local/lib/python3.5/dist-packages/fmpy/sundials/__init__.py", line 16, in <module>
    sundials_nvecserial = cdll.LoadLibrary(os.path.join(library_dir, 'sundials_nvecserial' + sharedLibraryExtension))
  File "/usr/lib/python3.5/ctypes/__init__.py", line 425, in LoadLibrary
    return self._dlltype(name)
  File "/usr/lib/python3.5/ctypes/__init__.py", line 347, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: /usr/local/lib/python3.5/dist-packages/fmpy/sundials/linux32/sundials_nvecserial.so: cannot open shared object file: No such file or directory

This is my directory:

pi@server:/usr/local/lib/python3.5/dist-packages/fmpy/sundials $ tree
.
├── darwin64
│   ├── sundials_cvode.dylib
│   └── sundials_nvecserial.dylib
├── __init__.py
├── linux64
│   ├── sundials_cvode.so
│   └── sundials_nvecserial.so
├── __pycache__
│   └── __init__.cpython-35.pyc
├── win32
│   ├── sundials_cvode.dll
│   └── sundials_nvecserial.dll
└── win64
    ├── sundials_cvode.dll
    └── sundials_nvecserial.dll

I googled to sundials_cvode.so and sundials_nvecserial.so for Linux 32Bit but didn't find it.
How could I solve this problem?

Best regards

Results not on a regular time grid

Hi,

I need the results to reside on a regular grid and I was expecting this behaviour since I explicitly specified the output_interval. Observing the actual output I found three issues, where I am not sure if this is intended by the author:

  1. doesn't start at t=0s,
  2. some samples are droped, e.g. at t=0.06s,
  3. grid is shifted starting after t=0.42s.

Could you please clarify? Thanks.

Simple example:

from fmpy import simulate_fmu

filename = 'fmus/Dymola2017/CoupledClutches.fmu'

print(filename)
results = simulate_fmu(
    filename=filename,
    start_time=0,
    stop_time=1.5,
    solver='CVode',
    step_size=1e-2,
    output_interval=2e-2,
    input=None,
    output=None,
    validate=False,
    fmi_logging=False)

print(results['time'])

Output:

[ 0.02        0.04        0.08        0.1         0.12        0.14        0.18
  0.22        0.26        0.28        0.3         0.32        0.34        0.36
  0.38        0.4         0.42        0.44565285  0.46565285  0.49740768
  0.53740768  0.55740768  0.57740768  0.59740768  0.63429745  0.65429745
  0.67429745  0.70976556  0.72976556  0.74976556  0.76976556  0.78976556
  0.82000019  0.85116724  0.87116724  0.89619621  0.92065559  0.94296037
  0.96296037  0.98296037  1.00355202  1.03929382  1.05929382  1.07929382
  1.11029498  1.13029498  1.15733956  1.17733956  1.21676477  1.23676477
  1.27071325  1.29071325  1.31071325  1.33071325  1.3697638   1.3897638
  1.4097638   1.4297638   1.4497638   1.4701323   1.4901323   1.5       ]

Problems with multiple Inputs

I'm currently trying to simulate a MIMO systems with varying inputs and wrapped FMPy inside a simple class.

However, if I assign more than one input value to a model exchange simulation via a structured numpy array, I get the following error message:

ValueError                                Traceback (most recent call last)
<ipython-input-11-6f1be21121d8> in <module>()
----> 1 simulation.simulate_exchange(use_inputs=True)

/media/jmartensen/Data/general/test/fmu_test/FMPY_Wrapper.py in simulate_exchange(self, plot, use_inputs)
     75             input = self.input_array if use_inputs else None ,
     76             output = self.outputs,
---> 77             fmi_type = 'ModelExchange'
     78         )
     79 

~/miniconda3/envs/python36/lib/python3.6/site-packages/fmpy/simulation.py in simulate_fmu(filename, validate, start_time, stop_time, solver, step_size, relative_tolerance, output_interval, record_events, fmi_type, use_source_code, start_values, apply_default_start_values, input, output, timeout, debug_logging, logger, fmi_call_logger, step_finished, model_description)
    474     if fmi_type == 'ModelExchange' and model_description.modelExchange is not None:
    475         fmu_args['modelIdentifier'] = model_description.modelExchange.modelIdentifier
--> 476         result = simulateME(model_description, fmu_args, start_time, stop_time, solver, step_size, relative_tolerance, start_values, apply_default_start_values, input, output, output_interval, record_events, timeout, callbacks, debug_logging, step_finished)
    477     elif fmi_type == 'CoSimulation' and model_description.coSimulation is not None:
    478         fmu_args['modelIdentifier'] = model_description.coSimulation.modelIdentifier

~/miniconda3/envs/python36/lib/python3.6/site-packages/fmpy/simulation.py in simulateME(model_description, fmu_kwargs, start_time, stop_time, solver_name, step_size, relative_tolerance, start_values, apply_default_start_values, input_signals, output, output_interval, record_events, timeout, callbacks, debug_logging, step_finished)
    529 
    530     input = Input(fmu, model_description, input_signals)
--> 531     input.apply(time)
    532 
    533     if is_fmi1:

~/miniconda3/envs/python36/lib/python3.6/site-packages/fmpy/simulation.py in apply(self, time, continuous, discrete, after_event)
    192                              cast(self.boolean_values, POINTER(self._bool_type)))
    193 
--> 194         return Input.nextEvent(time, t)
    195 
    196     @staticmethod

~/miniconda3/envs/python36/lib/python3.6/site-packages/fmpy/simulation.py in nextEvent(time, t)
    201 
    202 
--> 203         i = np.argmax(t_events > time)
    204 
    205         if t_events[i] > time:

~/miniconda3/envs/python36/lib/python3.6/site-packages/numpy/core/fromnumeric.py in argmax(a, axis, out)
   1002 
   1003     """
-> 1004     return _wrapfunc(a, 'argmax', axis=axis, out=out)
   1005 
   1006 

~/miniconda3/envs/python36/lib/python3.6/site-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
     50 def _wrapfunc(obj, method, *args, **kwds):
     51     try:
---> 52         return getattr(obj, method)(*args, **kwds)
     53 
     54     # An AttributeError occurs if the object does not have

ValueError: attempt to get argmax of an empty sequence

This happens as well if I try to simulate the fmu via fmpy.simulate_fmu(..., inputs = ...) .

Maybe I do not define the input array right?

input_array = np.array(np.zeros_like(time), dtype = {'names': ['time']+inputs, 'formats': ['<f8' for i in range(4)]})
for i,times in enumerate(time):
    input_array[i] = (times ,np.random.randint(1,5), np.random.randint(1,5), np.random.randint(1,5)) 

Thanks in advance!

I attached the jupyter notebook / python scripts and the fmu ( linux64) .
input_problems.zip

What solvers are supported?

Hi,

Currently I export an FMU for co-simulation with the solver being Cvode, but now I would like to try a different solver. So I'm wondering what solvers are supported for co-simulation and model exchange, respectively? How can one configure the parameters for those solvers, e.g. changing tolerance?

Best regards,
Francis

Values for time == start_time not in result for model-exchange

For model exchange the values at time == start_time are not recorded.

from fmpy.examples.coupled_clutches import simulate_coupled_clutches

result = simulate_coupled_clutches(fmi_type='ModelExchange', show_plot=False)

print(result['time'][:5])

Output:

...
Simulating CoupledClutches.fmu (FMI 2.0, ModelExchange, CVode)...
Done.
[ 0.02  0.04  0.08  0.1   0.12]

Set communication step size for CS FMU in GUI

It would be nice to be able to set the (commication) step size for CS FMUs in the GUI.
Currently the field "step size" is greyed out, and one can only enter "Max. samples" which seems to be the number of equidistant communication timesteps.

FMU 1.0 on Raspberry pi

Hello,
Thanks for FMPy.
Is it possible to simulate a FMU 1.0 on Raspi. I have tried it and i get an error.

Error in setInteger method (FMI2)

The method setInteger (FMI2) contains the implementation of setString:

fmi2.py - v0.0.8.

def setInteger(self, vr, value):
    value = map(lambda s: s.encode('utf-8'), value)
    value = (fmi2String * len(vr))(*value)
    self.fmi2SetString(self.component, vr, len(vr), value)

fmi2.py - correction

def setInteger(self, vr, value):
    vr = (fmi2ValueReference * len(vr))(*vr)
    value = (fmi2Integer * len(vr))(*value)
    self.fmi2SetInteger(self.component, vr, len(vr), value) 

Problems with multiprocessing caused by the zipfile module

I was investigating on a really strange issue today: I was using fmpy in our project together with a larger multiprocessing setup (doing parallel simulations) and I encountered a strange error (which was hard to debug due to multiprocess stuff) when running on Linux (funnily, Windows worked). The result was a BrokenProcessPool error or a queue.Full error.
After several hours of slicing away code line by code line, I ended up with the following script:

def use_fmpy(*args):
    import fmpy
    return fmpy.read_model_description('bouncingBall_me.fmu') 

if __name__ == "__main__":
    import tables  ##### TRIGGER HERE

    import concurrent.futures as cf
    with cf.ProcessPoolExecutor(max_workers=2) as pool:
        futures = []
        for i in range(10):
            future = pool.submit(use_fmpy, None)
            futures.append(future)
        cf.wait(futures)

What made it even harder was the fact that the import tables line triggered the error in the multiprocessing subprocesses. With the pytables import I got the error, without pytables, the error wasn't appearing.

So I first suspected pytables for being the source of the problem, but after a while I took a closer look at the read_model_description function. (BTW I tried out all available fmpy versions) The first lines of this function look like this:

with zipfile.ZipFile(filename, 'r') as zf:
xml = zf.open('modelDescription.xml')
tree = etree.parse(xml)

It uses the zipfile module to read the modelDescription.xml file from the FMU file. Putting a return just before this code block made my example above work in all cases, so it must have had to do with the zipfile use.

Googling brought immediately a possible issue: It seems that the zipfile module is not threadsafe. So my idea was to replace the zipfile use by a call to unzip:

import subprocess
root = etree.fromstring(subprocess.check_output(
    ['unzip', '-p', filename, 'modelDescription.xml'])) 

And surprise: it worked! No more problems with BrokenProcessPool or queue.Full errors.

So my question here: would it be possible that you replace all the zipfile usages by something more robust? I would really love to use fmpy instead of pyfmi, but this issue cost me already 5 hours of debugging and it is currently a blocker for us.

Not enough storage error

Hi, I have a very complicated FMU model. Sometimes when I simulate the model using the template custom_input.py, it gives some errors. However, when I reopen the Spyder console, the errors disappeared. Anyway, part of the errors are as follows.

File "D:\Software\Miniconda3\envs\py36_32\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)

File "D:\Software\Miniconda3\envs\py36_32\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "D:\Software\Miniconda3\envs\py36_32\lib\site-packages\fmpy\fmi2.py", line 386, in init
super(FMU2Slave, self).init(**kwargs)

File "D:\Software\Miniconda3\envs\py36_32\lib\site-packages\fmpy\fmi2.py", line 84, in init
super(_FMU2, self).init(**kwargs)

File "D:\Software\Miniconda3\envs\py36_32\lib\site-packages\fmpy\fmi1.py", line 131, in init
self.dll = cdll.LoadLibrary(libraryPath)

File "D:\Software\Miniconda3\envs\py36_32\lib\ctypes_init_.py", line 426, in LoadLibrary
return self._dlltype(name)

File "D:\Software\Miniconda3\envs\py36_32\lib\ctypes_init_.py", line 348, in init
self._handle = _dlopen(self._name, mode)

OSError: [WinError 8] Not enough storage is available to process this command

Problem with pypiwin32 dependency

Hi, as we are using conda for managing package dependency, fmpy gets installed as conda package with a dependency to pywin32. So far so good.

But when I run python setup.py develop in my project (which requires fmpy in its setuptools config), setuptools fails because it cannot find the dependency pypiwin32 (there is only pywin32 installed).

Any reason why the dependency is on pypiwin32 and not on pywin32 ? It seems that the original pywin32 project has been very active recently, see latest release is just 4 weeks old (https://pypi.python.org/pypi/pywin32). Would it be possible to switch back to pywin32 instead of pypiwin32 ? This would make my life much easier.

The only workaround I am currently seeing for my project is to remove fmpy from the requirements list (so that setuptools doesn't check for it) and manually make sure that fmpy and dependencies are installed correctly.

Incomplete path to fmuResourceLocation

fmi2Instantiate is called with the wrong path for the fmuRessourceLocation,
since self.fmuLocation points to the unzipped FMU, but the fmuRessourceLocation should point to the resources directory of the unzipped FMU.

fmi2.py

self.component = self.fmi2Instantiate(self.instanceName.encode('utf-8'), kind, self.guid.encode('utf-8'), self.fmuLocation.encode('utf-8'), # fix e.g.: + b'/resources' byref(callbacks), visible, loggingOn)

specify fmu parameter values

How can I specify the values of (static) parameters in an FMU? By "parameter" I mean, causality == parameter.

Thanks!

Output interval specification

Currently one can only specify a fixed output interval for ME simulation.
It would be beneficial to have a possibility to to also get output values at events.
So it would be best to have the following options:

  • constant output interval (current implementation)
  • all output values
  • Constant output interval + event points

FMPy on RPI3

Hi,
I tried to launch FMPy on a Raspberry Pi model b. The installation was successful and I managed to load the 32bit LINUX FMU (Model Exchange). I can also display the model information. As soon as I start simulating, I get the error message that the shared object file cannot be found.
image
But i can see the unzipped *.so file in that folder ? Any ideas?

Mike

CVode Error depending on combination of output_interval and stop_time

For the bouncingBall.fmu (64bit Windows) from the FMU-SDK 2.0.5 I get an error with FMPy when simulating (tested with the development branch for certain combinations of output_interval and stop_time.
For example for

result = simulate_fmu(fmu, output_interval=0.01, stop_time=1)

I get:
[CVODE ERROR] CVode
At t = 0.996514, mxstep steps taken before reaching tout.

....
However for

result = simulate_fmu(fmu, output_interval=0.001, stop_time=1)
There is no error.

bouncingBall.zip

Typos in util.py documentation

I have the changes in the branch https://github.com/traversaro/FMPy/tree/patch-1 , but I did not open a PR given that, citing the contributing guide:

For legal reasons we're currently not accepting pull requests. Please create an issue if you have suggestions for improvements.

Changing tolerance of a CS FMU?

When simulating a 2.0 CS FMU, the relative_tolerance argutment of simulate_fmu is not used (this parameter is only currently intended for the CVODE Solver of ME FMUs):
in

result = simulateCS(model_description, fmu_args, start_time, stop_time, start_values, apply_default_start_values, input, output, output_interval, timeout, callbacks, debug_logging, step_finished)
, no tolerance is passed to a CS FMU.

Do I understand

fmu.setupExperiment(tolerance=None, startTime=start_time)
right, that even a tolerance present in the default experiment of an FMU is ignored and overwritten by none?

It would be good, if it were possible to set the tolerance for simulating a 2.0 CS FMU explicitly, perhaps be using the relative_tolerance parameter currently only used for ME FMUS with CVODE.

An example of co-simulation?

Hi,

I just started learning this FMI world and FMPy seems to be the best opensource option that I could use right now. Do you have any example code of cosimulation? I plan to do it for building physics and control operations from different frameworks and would like to use FMI and FMPy to execute them.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.