예제 #1
0
 def make_fmu():
     '''Create an FMU from the Modelica model to use for testing
     '''
     # Setup the Modelica session and load the module
     omc = OMCSessionZMQ()
     model_path = (omc.sendExpression('getInstallationDirectoryPath()')
                   + '/share/doc/omc/testmodels/')
     mod = ModelicaSystem(model_path + 'BouncingBall.mo', 'BouncingBall')
     # Convert model to FMU 'BouncingBall.fmu'
     mod.convertMo2Fmu()
 def from_modelica(cls, model_info: ModelicaModelInfo):
     if not model_info.location.exists():
         raise ValueError('No such file: ' + str(model_info.location))
     modelica_model = ModelicaSystem(str(model_info.location),
                                     model_info.name, ["Modelica"],
                                     commandLineOptions="--fmiFlags=s:cvode -d=initialization")
     modelica_model.setSimulationOptions(["startTime=0", "stopTime=0"])
     modelica_model.simulate()
     fmu_path = modelica_model.convertMo2Fmu(fmuType='cs')
     if not len(fmu_path):
         raise RuntimeError("Couldn't compile FMU")
     return FmuSource(Path(fmu_path))
예제 #3
0
def run_ModelicaSystem(fileName,
                       modelName,
                       solutions,
                       stepSize=1,
                       stopTime=60,
                       parameters=dict(),
                       list_models=[],
                       make_FMU=False,
                       HP_dict=dict()):
    """Run the simulation with OpenModelica.

    Create a ``ModelicaSystem`` object which provides functions to
    load, configure and simulate a model.

    Args:
        fileName (str): Name (including path) of a *.mo file with the model

        modelName (str): Name of the model

        solutions (dict): Dict of all solutions (column names) to load
        from the results

        stepSize (int): Simulation step in seconds

        stopTime (int): Simulation lenth in seconds

        parameters (dict): Key, value pairs handed to ``setParameters()``

        list_models (list): List of file paths to additional *.mo that need
        to be loaded

        make_FMU (boolean): Should we create an FMU from the model?

        HP_dict (dict): Dict with settings for replacing the simulated heatpump

    Returns:
        data (DataFrame): Pandas DataFrame with the requested ``solutions``

    .. note::
        OMPython changed the input style for ``setSimulationOptions()``,
        ``setParameters()``, etc. dramatically after v3.1.2.
        As of 2019-12-04 this script requires the latest version from
        https://github.com/OpenModelica/OMPython

    """
    from OMPython import ModelicaSystem  # import only if necessary

    # If we want to simulate with some other than the default heatpump,
    # we have to include the record database for that heatpump.
    # For this, we need to load the *.mo file of that database into
    # the ModelicaSystem, via the argument ``lmodel``.
    if HP_dict.get('path', False):
        # Add to the list of additionally loaded modules
        list_models.append(HP_dict['path'].replace("\\", "/"))

    # Setup the Modelica session and load the module
    mod = ModelicaSystem(fileName=fileName,
                         modelName=modelName,
                         lmodel=list_models)

    if HP_dict.get('replace_expressions', False):
        # This part is tricky! If we want to change the heat pump that is
        # used in the simulation, we cannot simply use setParameters(),
        # because we are replacing the reference to a "record".
        # Instead we have to modify the component value directly...
        for expression in HP_dict['replace_expressions']:
            answer = mod.sendExpression(expression)
            logger.debug(expression)
            logger.debug(answer)
        # ... and re-build the model afterwards, for the changes to take effect
        mod.buildModel()

    # Set some simulation options (valid until v3.1.2)
#    mod.setSimulationOptions(stepSize=stepSize, stopTime=stopTime)

# Attention! For the current master branch of OMPython, we need the
# following style (https://github.com/OpenModelica/OMPython)
    text = ["stepSize={}".format(stepSize), "stopTime={}".format(stopTime)]
    mod.setSimulationOptions(text)  # current master branch of OMPython

    # Print some useful information
    quantities = pd.DataFrame(mod.getQuantities())

    # Use this code snippet to find out of which kind (parameter, continuous)
    # a given quantity is:
    search_str = None
    if search_str is not None:
        mask = [search_str in quantity for quantity in quantities['name']]
        logger.debug('Results for "{}":'.format(search_str))
        if logger.isEnabledFor(logging.DEBUG):
            print(quantities[mask].to_string())

    # Set simulation parameters
    text = ["{}={}".format(key, value) for (key, value) in parameters.items()]
    mod.setParameters(text)  # current master branch of OMPython
    #    mod.setParameters(**parameters)  # Until v3.1.2

    # Run simulations
    mod.simulate()

    # Get list of simulation variables for which results are available
    solution_vars = mod.getSolutions()

    # List required evaluation values:
    solution_list = ['time']
    for items in solutions.values():
        for item in items:
            if item not in solution_vars:
                logger.error('Skipping requested column "{}", since it'
                             ' is not among the solutions'.format(item))
            else:
                solution_list.append(item)

    # Read the results from your harddrive (this can take quite a long time)
    solution_data = mod.getSolutions(solution_list)

    # Create DataFrame from results
    data = pd.DataFrame(data=solution_data.T, columns=solution_list)

    if make_FMU:
        # Convert model to FMU 'modelName.fmu' in the current working directory
        mod.convertMo2Fmu()

        # Alternative: Try to produce Windows and Linux FMU at the same time
        # The platforms argument does not seem to have an effect


#        platforms = '{"x86_64-linux-gnu", "x86_64-w64-mingw32"}'
#        expr = ('buildModelFMU({}, version="2.0", fmuType="me_cs",'
#                'platforms={})'.format(modelName, platforms))
#        mod.getconn.sendExpression(expr)

    return data