pythonmodelicafmipyfmi

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?


Solution

  • 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:

    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()