コード例 #1
0
    def __init__(self, path_fmu):
        # define the model name and simulation parameters
        start_time = 0.0
        stop_time = 10.0
        self.step_size = 1e-2

        # read the model description
        model_description = read_model_description(path_fmu)

        # collect the value references
        vrs = {}
        for variable in model_description.modelVariables:
            vrs[variable.name] = variable.valueReference

        # get the value references for the variables we want to get/set
        self.vr_inputs = vrs['u']
        self.vr_output = vrs['Out1']

        # extract the FMU
        unzipdir = extract(path_fmu)
        self.fmu = FMU2Slave(
            guid=model_description.guid,
            unzipDirectory=unzipdir,
            modelIdentifier=model_description.coSimulation.modelIdentifier,
            instanceName='instance1')

        # initialize
        self.fmu.instantiate()
        self.fmu.setupExperiment(startTime=start_time)
        self.fmu.enterInitializationMode()
        self.fmu.exitInitializationMode()

        self.time = start_time
コード例 #2
0
def instantiate_fmu(component, ssp_unzipdir, start_time, parameters={}):

    fmu_filename = os.path.join(ssp_unzipdir, component.source)

    component.unzipdir = extract(fmu_filename)

    # read the model description
    model_description = read_model_description(fmu_filename, validate=False)

    # collect the value references
    component.variables = {}
    for variable in model_description.modelVariables:
        # component.vrs[variable.name] = variable.valueReference
        component.variables[variable.name] = variable

    fmu_kwargs = {
        'guid': model_description.guid,
        'unzipDirectory': component.unzipdir,
        'modelIdentifier': model_description.coSimulation.modelIdentifier,
        'instanceName': component.name
    }

    if model_description.fmiVersion == '1.0':
        component.fmu = FMU1Slave(**fmu_kwargs)
        component.fmu.instantiate()
        set_parameters(component, parameters)
        component.fmu.initialize()
    else:
        component.fmu = FMU2Slave(**fmu_kwargs)
        component.fmu.instantiate()
        component.fmu.setupExperiment(startTime=start_time)
        set_parameters(component, parameters)
        component.fmu.enterInitializationMode()
        component.fmu.exitInitializationMode()
コード例 #3
0
    def get_fmu(self):

        import shutil
        from fmpy import read_model_description, extract
        from fmpy.fmi2 import FMU2Slave

        shutil.copyfile(self.orig_fmu_path, self.dest_fmu_path)

        # read the model description
        self.model_description = read_model_description(self.dest_fmu_path)

        # collect the value references
        self.vrs = {}
        for variable in self.model_description.modelVariables:
            self.vrs[variable.name] = variable.valueReference

        #print(variable)

        # extract the FMU
        self.unzipdir = extract(self.dest_fmu_path)

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

        #print(self.contr_sys)

        self.contr_sys.instantiate()
        self.contr_sys.setupExperiment(startTime=0.0)
        self.contr_sys.enterInitializationMode()
        self.contr_sys.exitInitializationMode()
コード例 #4
0
def simulate_with_input():
    # os.chdir(r"C:\arash\PHD\IEA Projects\Annex\common exercise\ajab")
    os.chdir(path="C:/Users/gerar/PycharmProjects/untitled1/venv/Scripts")
    fmuf = 'TwinHouses71_new.fmu'
    start_time = 30463200
    # stop_time = 31676400
    # step_size = 3600
    #dump(fmuf)
    model_description = read_model_description(fmuf)
    vrs = {}
    for variable in model_description.modelVariables:
        vrs[variable.name] = variable.valueReference
        # print(variable)

    vr_output1 = vrs['Tav']  # temperature
    vr_output2 = vrs['hp_el']  # heat pump consumption
    vr_input1 = vrs['hp_s']  # heat pump status
    vr_input2 = vrs['hp_wt']  # heat water temperature
    #vr_outputs2 =vrs['lagtemp'] #hourly lagged temperature
    unzipdir = extract(fmuf)
    fmu = FMU2Slave(
        guid=model_description.guid,
        modelIdentifier=model_description.coSimulation.modelIdentifier,
        unzipDirectory=unzipdir,
        instanceName='instance1')
    fmu.instantiate()
    fmu.setupExperiment(startTime=start_time)
    fmu.enterInitializationMode()
    fmu.exitInitializationMode()
    # fmu.callbacks
    # output1=20

    return fmu, vr_input1, vr_input2, vr_output1, vr_output2
コード例 #5
0
    def test_get_directional_derivative(self):

        fmu_filename = 'Rectifier.fmu'

        download_test_file('2.0', 'CoSimulation', 'Dymola', '2017',
                           'Rectifier', fmu_filename)

        model_description = read_model_description(filename=fmu_filename)

        unzipdir = extract(fmu_filename)

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

        fmu.instantiate()
        fmu.setupExperiment()
        fmu.enterInitializationMode()

        # get the partial derivative for an initial unknown
        unknown = model_description.initialUnknowns[1]

        self.assertEqual('iAC[1]', unknown.variable.name)

        vrs_unknown = [unknown.variable.valueReference]
        vrs_known = [v.valueReference for v in unknown.dependencies]
        dv_known = [1.0] * len(unknown.dependencies)

        partial_der = fmu.getDirectionalDerivative(vUnknown_ref=vrs_unknown,
                                                   vKnown_ref=vrs_known,
                                                   dvKnown=dv_known)

        self.assertEqual([-2.0], partial_der)

        fmu.exitInitializationMode()

        # get the partial derivative for three output variables
        unknowns = model_description.outputs[4:7]

        self.assertEqual(['uAC[1]', 'uAC[2]', 'uAC[3]'],
                         [u.variable.name for u in unknowns])

        vrs_unknown = [u.variable.valueReference for u in unknowns]
        vrs_known = [v.valueReference for v in unknowns[0].dependencies]
        dv_known = [1.0] * len(vrs_known)

        partial_der = fmu.getDirectionalDerivative(vUnknown_ref=vrs_unknown,
                                                   vKnown_ref=vrs_known,
                                                   dvKnown=dv_known)

        self.assertAlmostEqual(-1500, partial_der[0])
        self.assertAlmostEqual(0, partial_der[1])
        self.assertAlmostEqual(1500, partial_der[2])

        fmu.terminate()
        fmu.freeInstance()
        rmtree(unzipdir)
コード例 #6
0
ファイル: env_fmu.py プロジェクト: bsl546/energym
    def initialize(self):
        """Initializes simulation object.

        Instantiates FMPy FMUSalve1 or FMUSlave2 object based on FMI
        version detected.
        """
        init_time = str(time.time())[0:10]
        random_id = str(uuid.uuid4().fields[-1])[:7]
        fmu_path = os.path.join(self.runs_path, init_time + "_" + random_id)
        os.mkdir(fmu_path)
        self.unzipdir = extract(self.fmu_file, unzipdir=fmu_path)
        weather_folder = Path(self.unzipdir) / "resources"
        possible_weather_files = list(weather_folder.rglob("*.mos")) + list(
            weather_folder.rglob("*.epw")
        )
        weather_default_file_path = weather_folder / possible_weather_files[0]
        try:
            os.remove(weather_default_file_path)
            shutil.copy(self.weather_file_path, weather_default_file_path)
        except BaseException as e:
            logging.error(e)
            logging.error("Problem with the weather file handling")
        # initialize
        instance_name = "instance" + init_time

        # model identifier
        if self.fmi_type == "modex":
            model_id = self.model_description.modelExchange.modelIdentifier
        else:
            model_id = self.model_description.coSimulation.modelIdentifier

        kwargs = dict(
            guid=self.model_description.guid,
            unzipDirectory=self.unzipdir,
            modelIdentifier=model_id,
            instanceName=instance_name,
        )

        if self.fmi_version == "1.0":
            if self.fmi_type == "cosim":
                self.fmu = FMU1Slave(**kwargs)
            else:
                self.fmu = FMU1Model(**kwargs)
        elif self.fmi_version == "2.0":
            if self.fmi_type == "cosim":
                self.fmu = FMU2Slave(**kwargs)
            else:
                self.fmu = FMU2Model(**kwargs)

        self.fmu.instantiate(loggingOn=True)
        if self.fmi_version == "2.0":
            self.fmu.setupExperiment(startTime=self.start_time, stopTime=self.stop_time)

        # Initialize time and the last_output values
        self.time = self.start_time
コード例 #7
0
def load_fmu(instance_name, path):
    """A function to read an FMU and go through default initialization"""

    mdl_desc = fmpy.read_model_description(path)
    unzip_dir = fmpy.extract(path)

    fmu = FMU2Slave(instanceName=instance_name,
                    guid=mdl_desc.guid,
                    modelIdentifier=mdl_desc.coSimulation.modelIdentifier,
                    unzipDirectory=unzip_dir)
    return Slave(mdl_desc, fmu)
コード例 #8
0
 def __init__(self, file: str):
     self.file = file
     logger.info('Opening twin %s in %s', self.file, os.getcwd())
     self.model_description = read_model_description(file)
     self.variables = ModelVariables(self.model_description)
     self.unzipped_directory = extract(file)
     self.fmu = FMU2Slave(guid=self.model_description.guid,
                          unzipDirectory=self.unzipped_directory,
                          modelIdentifier=self.model_description.
                          coSimulation.modelIdentifier,
                          instanceName='instance')
     self.running = False
     self.time = 0
コード例 #9
0
    def spawn(self):
        guid = self.model_description.guid
        unzipdir = self.unzipdir
        model_id = self.model_description.coSimulation.modelIdentifier
        inst_name = model_id[:8] + str(uuid1())[:8]  # Unique 16-char FMU ID

        self._fmu = FMU2Slave(guid=guid, unzipDirectory=unzipdir,
                              modelIdentifier=model_id, instanceName=inst_name)
        self._fmu.instantiate()
        self._fmu.setupExperiment(startTime=self.start_time,
                                  stopTime=self.stop_time)
        self._fmu.enterInitializationMode()
        self._fmu.exitInitializationMode()
        self.status = ModelStatus.READY
コード例 #10
0
async def initialize(request):
    global FACTORY
    global FMU
    global TIME
    global RESULTS

    if request.body_exists:

        data = await request.read()
        data = json.loads(data.decode("utf-8"))
        # ???
        FACTORY["pathToFMU"] = data["target"]
        FACTORY["modelDescription"] = fm.read_model_description(
            FACTORY["pathToFMU"])
        FACTORY["unzipdir"] = fm.extract(FACTORY["pathToFMU"])

        # Get variable references and input variables
        FACTORY["vrs"] = {}
        for variable in FACTORY["modelDescription"].modelVariables:
            FACTORY["vrs"][variable.name] = variable.valueReference
            if variable.causality == "input":
                FACTORY["inputVars"][variable.name] = None

        FMU = FMU2Slave(guid=FACTORY["modelDescription"].guid,
                        unzipDirectory=FACTORY["unzipdir"],
                        modelIdentifier=FACTORY["modelDescription"].
                        coSimulation.modelIdentifier,
                        instanceName="instance1")

        ###   ###   ###   ###   ###   ###
        # Init FMU
        FACTORY["startTime"] = data["startTime"]
        FACTORY["endTime"] = data["endTime"]
        FACTORY["stepSize"] = data["stepSize"]
        TIME = FACTORY["startTime"]
        RESULTS = []  # list to record the results

        FMU.instantiate()
        FMU.setupExperiment(startTime=FACTORY["startTime"])
        FMU.enterInitializationMode()
        FMU.exitInitializationMode()

        return web.json_response({"description": "Service initialized."},
                                 status=200)

    return web.json_response({"description": "Wrong init information"},
                             status=500)
コード例 #11
0
    def test_serialize_fmu_state(self):

        fmu_filename = 'Rectifier.fmu'

        # download the FMU
        download_test_file('2.0', 'cs', 'MapleSim', '2016.2', 'Rectifier',
                           fmu_filename)

        # read the model description
        model_description = read_model_description(fmu_filename)

        # extract the FMU
        unzipdir = extract(fmu_filename)

        # instantiate the FMU
        fmu = FMU2Slave(
            guid=model_description.guid,
            unzipDirectory=unzipdir,
            modelIdentifier=model_description.coSimulation.modelIdentifier)

        # initialize
        fmu.instantiate()
        fmu.setupExperiment()
        fmu.enterInitializationMode()
        fmu.exitInitializationMode()

        # get the FMU state
        state = fmu.getFMUstate()

        # serialize the FMU state
        serialized_state = fmu.serializeFMUstate(state)

        # de-serialize the FMU state
        fmu.deSerializeFMUstate(serialized_state, state)

        # set the FMU state
        fmu.setFMUstate(state)

        # free the FMU state
        fmu.freeFMUstate(state)

        fmu.terminate()
        fmu.freeInstance()

        # clean up
        shutil.rmtree(unzipdir)
コード例 #12
0
def instantiate_fmu(component,
                    ssp_unzipdir,
                    start_time,
                    stop_time=None,
                    parameter_set=None):
    """ Instantiate an FMU """

    fmu_filename = os.path.join(ssp_unzipdir, component.source)

    component.unzipdir = extract(fmu_filename)

    # read the model description
    model_description = read_model_description(fmu_filename, validate=False)

    if model_description.coSimulation is None:
        raise Exception("%s does not support co-simulation." %
                        component.source)

    # collect the value references
    component.variables = {}
    for variable in model_description.modelVariables:
        # component.vrs[variable.name] = variable.valueReference
        component.variables[variable.name] = variable

    fmu_kwargs = {
        'guid': model_description.guid,
        'unzipDirectory': component.unzipdir,
        'modelIdentifier': model_description.coSimulation.modelIdentifier,
        'instanceName': component.name
    }

    if model_description.fmiVersion == '1.0':
        component.fmu = FMU1Slave(**fmu_kwargs)
        component.fmu.instantiate()
        if parameter_set is not None:
            set_parameters(component, parameter_set)
        component.fmu.initialize(stopTime=stop_time)
    else:
        component.fmu = FMU2Slave(**fmu_kwargs)
        component.fmu.instantiate()
        component.fmu.setupExperiment(startTime=start_time)
        if parameter_set is not None:
            set_parameters(component, parameter_set)
        component.fmu.enterInitializationMode()
        component.fmu.exitInitializationMode()
コード例 #13
0
    def load(fmu_path, instance_name, logger):

        fmu_path = Path(fmu_path)

        is_compressed = fmu_path.is_file() and fmu_path.name.endswith('.fmu')

        if(is_compressed):
            unzipdir = extract(fmu_path)
        else:
            unzipdir = str(fmu_path)

        desc = read_model_description(unzipdir)
        vars = FMULoader.get_vars(desc)
        fmu = FMU2Slave(guid=desc.guid,
                        unzipDirectory=unzipdir,
                        modelIdentifier=desc.coSimulation.modelIdentifier,
                        instanceName=instance_name,
                        fmiCallLogger=logger)
        return LoadedFMU(fmu=fmu, dir=unzipdir, vars=vars,cleanup = is_compressed)
コード例 #14
0
def prepare_slave(
        instance_name: InstanceName, path: str
) -> Slave:
    """A function to read an FMU and go through default initialization"""
    if path in used_slaves:
        mdl_desc, unzip_dir = used_slaves[path]
    else:
        mdl_desc = fmpy.read_model_description(path)
        unzip_dir = fmpy.extract(path)
        used_slaves[path] = mdl_desc, unzip_dir
    fmu = FMU2Slave(
        instanceName=instance_name,
        guid=mdl_desc.guid,
        modelIdentifier=mdl_desc.coSimulation.modelIdentifier,
        unzipDirectory=unzip_dir
    )
    fmu.instantiate()
    fmu.setupExperiment(startTime=0.)
    fmu.enterInitializationMode()
    fmu.exitInitializationMode()
    return Slave(mdl_desc, fmu)
    def __init__(self, filename, instance_name, input_connectors,
                 output_connectors, start_time):
        self.filename = filename
        self.instance_name = instance_name

        self.unzipdir = extract(filename)
        self.model_description = read_model_description(filename,
                                                        validate=False)

        self.variables = {}
        for variable in self.model_description.modelVariables:
            self.variables[variable.name] = variable

        # create connector dicts
        self.in_connectors = {
            connector_name: {
                "value": self.variables[connector_name].start
            }
            for connector_name in input_connectors
        }
        self.out_connectors = {
            connector_name: {
                "value": 0.0
            }
            for connector_name in output_connectors
        }

        fmu_kwargs = {
            'guid': self.model_description.guid,
            'unzipDirectory': self.unzipdir,
            'modelIdentifier':
            self.model_description.coSimulation.modelIdentifier,
            'instanceName': instance_name
        }

        self.fmu = FMU2Slave(**fmu_kwargs)
        self.fmu.instantiate()
        self.fmu.setupExperiment(startTime=start_time)
        self.fmu.enterInitializationMode()
        self.fmu.exitInitializationMode()
コード例 #16
0
def startFmu(
    filename,
    startTime=0.0,
    threshold=2.0,
    stopTime=30.0,
    stepSize=None,
):

    if stepSize == None:
        stepSize = (stopTime - startTime) / 500

    modelDescription = read_model_description(filename)

    vrs = {}
    for variable in modelDescription.modelVariables:
        vrs[variable.name] = variable.valueReference

    # get the value references for the variables we want to get/set
    vrInputs = vrs[
        'u']  # These need to be changed per model, or use standardised naming conventions
    vrOutputs = vrs['y']

    unzipdir = extract(filename)

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

    # initalize
    fmu.instantiate()
    fmu.setupExperiment(startTime=startTime)
    fmu.enterInitializationMode()
    fmu.exitInitializationMode()

    return fmu, vrInputs, vrOutputs, startTime, stepSize, stopTime
コード例 #17
0
def simulateCustomInput(filename, showPlot=True):

    # define the model name and simulation parameters
    startTime = 0.0
    threshold = 2.0
    stopTime = 30.0
    stepSize = (stopTime - startTime) / 500

    # read the model description
    modelDescription = read_model_description(filename)

    # collect the value references
    vrs = {}
    for variable in modelDescription.modelVariables:
        vrs[variable.name] = variable.valueReference

    # get the value references for the variables we want to get/set
    vrInputs = vrs[
        'u']  # These need to be changed per model, or use standardised naming conventions
    vrOutputs = vrs['y']

    unzipdir = extract(filename)

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

    # initalize
    fmu.instantiate()
    fmu.setupExperiment(startTime=startTime)
    fmu.enterInitializationMode()
    fmu.exitInitializationMode()

    time = startTime

    rows = []

    # Sim loop
    while time < stopTime:

        # NOTE: the FMU.get*() and FMU.set*() functions take lists of
        # value references as arguments and return lists of values

        # set the input
        fmu.setReal([vrInputs], [0.0 if time < 1.0 else 1.0])

        # perform 1 step
        fmu.doStep(currentCommunicationPoint=time,
                   communicationStepSize=stepSize)

        # get the values for 'inputs' and 'outputs'
        inputs, outputs = fmu.getReal([vrInputs, vrOutputs])

        # Use threshold to terminate sim
        if outputs > threshold:
            print("Threshold reached at t = {:.3f} s".format(time))
            break

        # append the results
        rows.append((time, inputs, outputs))

        # advance the time
        time += stepSize

    fmu.terminate()
    fmu.freeInstance()

    result = np.array(rows,
                      dtype=np.dtype([('time', np.float64),
                                      ('inputs', np.float64),
                                      ('outputs', np.float64)]))

    if showPlot:
        plot_result(result)

    return time
コード例 #18
0
def simulate_fmu(*args):
    """ Worker function that simulates the FMU
    Parameters:
        args = [indices, fmu_args, start_vrs, result_vrs]
        indices     a list of indices into the parameter arrays
        fmu_args    FMU constructor arguments
    Returns:
        a list of tuples (i, [u_dc, losses]) that contain the index 'i' and the averaged results of the
        'uDC' and 'Losses' variables
    """

    indices, fmu_args, start_vrs, result_vrs = args

    zipped = []

    # global fmu_args, start_vrs, result_vrs, dll_handle

    fmu = FMU2Slave(**fmu_args)

    fmu.instantiate()

    # iterate over the all indices in this batch
    for i in indices:

        # get the start values for the current index
        start_values = [INITIAL_INPUTS_GRID[i], INITIAL_INTEGRATORS_GRID[i]]

        fmu.reset()

        fmu.setupExperiment()

        # set the start values
        fmu.setReal(vr=start_vrs, value=start_values)

        fmu.enterInitializationMode()
        fmu.exitInitializationMode()

        time = 0.0
        step_size = 0.02

        results = []

        # simulation loop
        while time < STOP_TIME:
            fmu.doStep(currentCommunicationPoint=time,
                       communicationStepSize=step_size)
            time += step_size

            if time > 0.02:
                result = fmu.getReal(result_vrs)
                results.append(result)

        u_dc, losses = zip(*results)

        # store the index and the averaged signals
        zipped.append((i, [np.average(u_dc), np.average(losses)]))

    fmu.terminate()

    # call the FMI API directly to avoid unloading the share library
    fmu.fmi2FreeInstance(fmu.component)

    if SYNC:
        # remember the shared library handle so we can unload it later
        global DLL_HANDLE
        DLL_HANDLE = fmu.dll._handle
    else:
        # unload the shared library directly
        fmpy.freeLibrary(fmu.dll._handle)

    return zipped
コード例 #19
0
ファイル: custom_input.py プロジェクト: wushuaibuaa/FMPy
def simulate_custom_input(show_plot=True):

    # define the model name and simulation parameters
    fmu_filename = 'CoupledClutches.fmu'
    start_time = 0.0
    threshold = 2.0
    stop_time = 2.0
    step_size = 1e-3

    # download the FMU
    download_test_file('2.0', 'CoSimulation', 'MapleSim', '2016.2', 'CoupledClutches', fmu_filename)

    # read the model description
    model_description = read_model_description(fmu_filename)

    # collect the value references
    vrs = {}
    for variable in model_description.modelVariables:
        vrs[variable.name] = variable.valueReference

    # get the value references for the variables we want to get/set
    vr_inputs   = vrs['inputs']      # normalized force on the 3rd clutch
    vr_outputs4 = vrs['outputs[4]']  # angular velocity of the 4th inertia

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

    time = start_time

    rows = []  # list to record the results

    # simulation loop
    while time < stop_time:

        # NOTE: the FMU.get*() and FMU.set*() functions take lists of
        # value references as arguments and return lists of values

        # set the input
        fmu.setReal([vr_inputs], [0.0 if time < 0.9 else 1.0])

        # perform one step
        fmu.doStep(currentCommunicationPoint=time, communicationStepSize=step_size)

        # get the values for 'inputs' and 'outputs[4]'
        inputs, outputs4 = fmu.getReal([vr_inputs, vr_outputs4])

        # use the threshold to terminate the simulation
        if outputs4 > threshold:
            print("Threshold reached at t = %g s" % time)
            break

        # append the results
        rows.append((time, inputs, outputs4))

        # advance the time
        time += step_size

    fmu.terminate()
    fmu.freeInstance()

    # clean up
    shutil.rmtree(unzipdir)

    # convert the results to a structured NumPy array
    result = np.array(rows, dtype=np.dtype([('time', np.float64), ('inputs', np.float64), ('outputs[4]', np.float64)]))

    # plot the results
    if show_plot:
        plot_result(result)

    return time
コード例 #20
0
def simulate_custom_input(show_plot=True):
    # define the model name and simulation parameters
    start_time = 0.0
    step_size = 0.001
    stop_time = 20

    # read the model description
    model_description = read_model_description(fmu_filename)

    # collect the value references
    vrs = {}
    for variable in model_description.modelVariables:
        vrs[variable.name] = variable.valueReference

    # get the value references for the variables we want to get/set
    accel = vrs['accelCMD']  # Steering and Acceleration Commands
    steer = vrs['steerCMD']

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

    time = start_time

    rows = []  # list to record the results

    # simulation loop
    while time < stop_time:

        # NOTE: the FMU.get*() and FMU.set*() functions take lists of
        # value references as arguments and return lists of values

        # set the inputs
        if keyboard.is_pressed('5'):
            fmu.setReal([accel], [1.0])
        elif keyboard.is_pressed('2'):
            fmu.setReal([accel], [-1.0])
        else:
            fmu.setReal([accel], [0.0])

        #fmu.setReal([steer], [0.0])
        if keyboard.is_pressed('1'):
            fmu.setReal([steer], [1.0])
        elif keyboard.is_pressed('3'):
            fmu.setReal([steer], [-1.0])
        else:
            fmu.setReal([steer], [0.0])

        # Aborting with Escape
        if keyboard.is_pressed('Escape'):
            break

        # Timing the step
        start = TIME.time()
        # perform one step
        fmu.doStep(currentCommunicationPoint=time,
                   communicationStepSize=step_size)

        end = TIME.time()

        # get the values for 'inputs' and 'outputs[4]'
        #inputs, outputs = fmu.getReal([vr_inputs, vr_outputs])

        # append the results
        #rows.append((time, inputs, outputs))

        # advance the time and sync
        time += step_size
        if end - start < step_size:
            TIME.sleep(step_size - (end - start))

    fmu.terminate()
    fmu.freeInstance()

    # clean up
    shutil.rmtree(unzipdir, ignore_errors=True)

    # convert the results to a structured NumPy array
    #result = np.array(rows, dtype=np.dtype([('time', np.float64), ('inputs', np.float64), ('outputs', np.float64)]))

    # plot the results
    #if show_plot:
    #   plot_result(result)

    return time
コード例 #21
0
    def test_common_functions(self):

        if platform.startswith('win'):
            fmi_versions = ['1.0', '2.0']
        else:
            return

        for fmi_version in fmi_versions:

            model_name = 'BooleanNetwork1'
            filename = model_name + '.fmu'

            download_test_file(fmi_version, 'CoSimulation', 'Dymola', '2017', model_name, filename)

            model_description = read_model_description(filename)
            unzipdir = extract(filename)

            guid = model_description.guid

            variables = {}

            for v in model_description.modelVariables:
                variables[v.name] = v

            args = {
                'guid': guid,
                'modelIdentifier': model_description.coSimulation.modelIdentifier,
                'unzipDirectory': unzipdir,
                'instanceName': None
            }

            if fmi_version == '1.0':
                fmu = FMU1Slave(**args)
                fmu.instantiate("instance1")
                fmu.initialize()
            else:
                fmu = FMU2Slave(**args)
                fmu.instantiate(loggingOn=False)
                fmu.setupExperiment(tolerance=None)
                fmu.enterInitializationMode()
                fmu.exitInitializationMode()

            # get types platform
            types_platform = fmu.getTypesPlatform()

            if fmi_version == '1.0':
                self.assertEqual('standard32', types_platform)
            else:
                self.assertEqual('default', types_platform)

            # get FMI version
            version = fmu.getVersion()
            self.assertEqual(fmi_version, version)

            # set debug logging
            if fmi_version == '1.0':
                fmu.setDebugLogging(True)
            else:
                fmu.setDebugLogging(True, ['logAll'])

            # set and get Real
            vr = [variables['booleanPulse1.width'].valueReference]
            value = [30.0]
            fmu.setReal(vr, value)
            result = fmu.getReal(vr)
            self.assertTrue(result[0] == value[0])

            # set and get Integer
            vr = [variables['integerConstant.k'].valueReference]
            value = [-4]
            fmu.setInteger(vr, value)
            result = fmu.getInteger(vr)
            self.assertTrue(result[0] == value[0])

            # set and get Boolean
            vr = [variables['rSFlipFlop.Qini'].valueReference]
            value = [True]
            fmu.setBoolean(vr, value)
            result = fmu.getBoolean(vr)
            self.assertTrue(result[0] == value[0])

            # TODO: set and get String

            # clean up
            fmu.terminate()
            fmu.freeInstance()
            shutil.rmtree(unzipdir)
コード例 #22
0
dump(pathToFmu)

model_description = read_model_description(pathToFmu)
unzipdir = extract(pathToFmu)

# get value references

vrs = {}

for variable in model_description.modelVariables:
    vrs[variable.name] = variable.valueReference
    print("Variable name \t", variable.name, "Variable reference \t",
          variable.valueReference)

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

###   ###   ###   ###   ###   ###
# Init FMU
start_time = 0.0
stop_time = 30.0
step_size = 1.0
time = start_time
results = []  # list to record the results

fmu.instantiate()
fmu.setupExperiment(startTime=start_time)
fmu.enterInitializationMode()
fmu.exitInitializationMode()