Beispiel #1
0
def runSimulation():
    # extract the FMU to a temporary directory
    unzipdir = fmpy.extract(fmu)
    # read the model description
    model_description = fmpy.read_model_description(unzipdir)
    # instantiate the FMU
    fmu_instance = fmpy.instantiate_fmu(unzipdir, model_description, 'CoSimulation')

    cf = fun_lib.importCostFunction(dir = 'Combined\\')

    params = readInitParams()
    cost = 1e300
    # shuffledParams = copy.

    for iter in range(niter):
    # todo paralelize this

        
        cur_params = shuffleParams(params)

        # reset the FMU instance instead of creating a new one
        fmu_instance.reset()
        
        result = fmpy.simulate_fmu(unzipdir,
                                    stop_time=1,
                                    start_values=cur_params,
                                    model_description=model_description,
                                    fmu_instance=fmu_instance,
                                    fmi_call_logger=lambda s: print('[FMI] ' + s) )

        var_set = {}
        for name in result.dtype.names:
            var_set[name] = result[name]
            
        if DRAW_PLOTS:
            var_set['__draw_plots'] = True
            var_set['__plot_title'] = "Run %i" % (fun_lib.getRunNumber())
            var_set['__saveFig_path'] = "%sFitFig_%03d.png" % (fun_lib.getSafeLogDir('Schedules'), fun_lib.getRunNumber())

        objectives = cf.getObjectives(var_set, targetsFolder = r"../data/Valsalva/")
        cur_cost = fun_lib.countTotalSumCost(objectives)

        if cur_cost < cost:
            # woohoo, better costs!
            cost = cur_cost
            params = cur_params
            writeSchedule(params, cost, iter)

        print(result)
    

    # free the FMU instance and unload the shared library
    fmu_instance.freeInstance()

    # delete the temporary directory
    shutil.rmtree(unzipdir, ignore_errors=True)

    print('that is all, folks')
    pass
Beispiel #2
0
    def __init__(self,
                 fmupath,
                 outputs=None,
                 states=None,
                 parameters=None,
                 verbose=False):
        """
        :param fmupath: str, path to FMU
        :param outputs: list(str), monitored outputs names
        :param states: list(str), monitored states names
        :param parameters: dict, parameters names and values
        :param verbose: bool, whether to suppress pyfmi prints
        """
        if parameters is None:
            parameters = {}
        if states is None:
            states = []
        if outputs is None:
            outputs = []

        self.logger = logging.getLogger(type(self).__name__)
        print(fmupath)
        self.logger.debug("Loading FMU")
        # Load FMU
        model_description = read_model_description(fmupath)
        self.model_description = model_description
        self.unzipdir = extract(fmupath)
        self.fmupath = fmupath
        self.fmu = instantiate_fmu(self.unzipdir, model_description)

        self.outputs = outputs
        self.states = states
        self.parameters = parameters
        self.verbose = verbose

        # Get initial state
        # Comment:
        #   The model has to be initialized to read the state variables.
        #dummy_result = self.fmu.initialize(tStart=0, stopTime=None)
        self.fmu.setupExperiment(startTime=0)
        self.fmu.enterInitializationMode()
        self.fmu.exitInitializationMode()
        self.x0 = self._get_state()

        # Reset the FMU
        self.fmu.reset()
Beispiel #3
0
def initFmus() -> list:
    fmu_init = []
    for model_info in model_infos:
        (prefix, cf_folder, fmu) = model_info
        # extract the FMU to a temporary directory
        unzipdir = fmpy.extract(fmu)
        # read the model description
        model_description = fmpy.read_model_description(unzipdir)
        # instantiate the FMU
        fmu_instance = fmpy.instantiate_fmu(unzipdir, model_description,
                                            'CoSimulation')
        # fmu_instance = fmpy.instantiate_fmu(unzipdir, model_description, 'CoSimulation', debug_logging=True, fmi_call_logger=logger, visible=True)

        # TODO this might be obsolete atm
        cf = fun_lib.importCostFunction(dir='..\\' + cf_folder + '\\')
        fmu_init.append((fmu_instance, model_description, cf, prefix))

    return fmu_init
Beispiel #4
0
    def __init__(self, fmu_path, opts=None):
        self.logger = logging.getLogger(type(self).__name__)

        try:
            self.logger.debug("Loading FMU")
            # Load FMU
            model_desc = read_model_description(fmu_path)
            self.unzipdir = extract(fmu_path)
            self.model = instantiate_fmu(self.unzipdir, model_desc)

        except Exception as e:
            self.logger.error(type(e).__name__)
            self.logger.error(str(e))
            raise e

        self.start = None
        self.end = None
        self.timeline = None
        self.opts = opts  # TODO: Not used at the moment

        self.input_arr = None
        self.output_names = list()
        self.parameters = dict()
Beispiel #5
0
fmuClocks['Task2_10MS']['start'] = 'startTask2'
fmuClocks['Task2_10MS']['end'] = 'endTask2'
fmuClocks['Task3_20MS']['start'] = 'startTask3'
fmuClocks['Task3_20MS']['end'] = 'endTask3'
fmuClocks['Task4_10MS']['start'] = 'startTask4'
fmuClocks['Task4_10MS']['end'] = 'endTask4'
fmuClocks['Task5_20MS']['start'] = 'startTask5'
fmuClocks['Task5_20MS']['end'] = 'endTask5'
fmuOutputs = ['output1', 'output2']

# initialize simulation
unzipdir = fmpy.extract(fmuFilename)
modelDescription = fmpy.read_model_description(unzipdir)
vr = dict((v.name, v.valueReference) for v in modelDescription.modelVariables)

fmu = fmpy.instantiate_fmu(unzipdir, modelDescription)
fmu.enterInitializationMode()
fmu.exitInitializationMode()

results = list()
t = 0

# run simulation
for (commPointTime, commPointTarget, commPointEvent) in commPoints:

    dt = commPointTime / (10**9) - t
    if dt > 0:
        fmu.doStep(t, dt, fmpy.fmi3.fmi3False)  # advance time, empty impl...
        t = t + dt

    fmu.enterEventMode()
    return df


# Paths
fmu_path = f"examples/simple/resources/Simple2R1C_ic_{get_sys_arch()}.fmu"
input_path = "examples/simple/resources/inputs.csv"
known_path = "examples/simple/resources/known.json"
est_path = "examples/simple/resources/est.json"

# Print some info about the FMU
dump(fmu_path)

# Instantiate FMU
model_desc = read_model_description(fmu_path)
unzipdir = extract(fmu_path)
fmu = instantiate_fmu(unzipdir, model_desc)

# Input
inp_df = pd.read_csv(input_path)
inp_struct = df_to_struct_arr(inp_df)

# Parameters
with open(known_path, "r") as f:
    start_values = json.load(f)

# Declare output names
# output = []

# Start and stop time
start_time = 360  # THIS TRIGGERS THE WARNINGS
stop_time = inp_df["time"].iloc[-1]
Beispiel #7
0
# test FMPy optim
import fmpy

fmu = 'ADAN_0main_SystemicTree_Tilt_OlufsenTriSeg_0tiltable.fmu'

unzipdir = fmpy.extract(fmu)
# read the model description
model_description = fmpy.read_model_description(unzipdir)
# instantiate the FMU
fmu_instance = fmpy.instantiate_fmu(unzipdir,
                                    model_description,
                                    'CoSimulation',
                                    fmi_call_logger=lambda s: print(s),
                                    debug_logging=True)

# the python breaks at fmu.terminate()
result = fmpy.simulate_fmu(unzipdir,
                           fmu_instance=fmu_instance,
                           stop_time=1,
                           relative_tolerance=1e-6,
                           output_interval=0.02)

# it wont come to this point without any trace
print(result)
fmpy.write_csv('test', result)
pass