Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
844 views
in Technique[技术] by (71.8m points)

modelica - How to co-simulate fmu with a Python function?

With Python libraries like FMPy I am able to simulate fmus (using fmpy.simulate_fmu) for given start_time and stop_time. In such case, the function simulate_fmu completes the simulation and return the time-series results.

However, I want to create a closed loop between fmu and a Python function (i.e. in a Python script initialize the fmu, get the results from fmu after every 0.1s and based on that update the input value to the fmu for the next timestep). Is there a way to achieve this using existing libraries like fmpy or pyfmi?

question from:https://stackoverflow.com/questions/66051450/how-to-co-simulate-fmu-with-a-python-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The short answer is yes the tools you mention are set up to do what you are asking.

A long answer can be found for FMPy:

But the gist is to perform changes during simulation like you are asking the approach you want you need to go a layer deeper than simulate_fmu and use doStep and associated setup. The functions/approach needed for these are defined by the FMI standard while highler level implmentations like simulate_fmu are not and are therefore tool dependent implementations of the standard.

The cliff notes are:

  • Prep the Simulation Inputs
    • e.g., unzip the FMU, define simulation setup, and instantiate the FMU
from fmpy import read_model_description, extract
from fmpy.fmi2 import FMU2Slave

# extract the FMU
unzipdir = extract(fmu_filename)

fmu = FMU2Slave(guid=model_description.guid,
                unzipDirectory=unzipdir,
                modelIdentifier=model_description.coSimulation.modelIdentifier,
                instanceName='instance1')

# initialize
fmu.instantiate()
fmu.setupExperiment(startTime=start_time)
fmu.enterInitializationMode()
fmu.exitInitializationMode()
  • Simulation Loop
    • Set/Get values (can do this before and/or after timestep): fmu.setReal and fmu.getReal
    • Solve the time step (fmu.doStep)
    • Store values
    • Loop until complete
  • Terminate Simulation: fmu.terminate() and fmu.freeInstance
  • Plot results
  • Celebrate!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...