def instantiate_highlevel(n_cpus=2): """Instantiate an FMUFunction and set number of cores to use. Parameters ---------- n_cpus : Integer, number of cores to use for multiprocessing. """ try: directory_platform = dict_platform[key_platform] path_fmu = os.path.join(path_here, "file", "fmu", directory_platform, "deviation.fmu") return otfmi.FMUFunction(path_fmu, inputs_fmu=["E", "F", "L", "I"], outputs_fmu="y", n_cpus=n_cpus) except KeyError: raise RuntimeError("Examples are not available on your platform" " (%s)." % "-".join(key_platform)) sys.exit() except FMUException: raise FMUException("The example FMU 'deviation.fmu' is not" " available on your platform (%s)." % "-".join(key_platform)) sys.exit()
def variable_tcase(varType, fmuType): temp_path = tempfile.mkdtemp() path_mo = os.path.join(temp_path, 'ParamInput.mo') path_fmu = os.path.join(temp_path, 'ParamInput.fmu') with open(path_mo, "w") as mo: mo.write('model ParamInput\n') mo.write(' ' + varType + ' Real p1;\n') mo.write(' parameter Real p2 = 80;\n') mo.write(' Real a;\n') mo.write(' output Real out1;\n') mo.write(' Real d;\n') mo.write('equation\n') mo.write(' a = p1 + 10 + p2;\n') mo.write(' out1 = a * 2;\n') mo.write(' der(d) = d + 2;\n') mo.write('end ParamInput;\n') otfmi.mo2fmu(path_mo, path_fmu, fmuType=fmuType, verbose=True) # reimport fmu model_fmu = otfmi.FMUFunction(path_fmu, inputs_fmu=["p1", "p2"], outputs_fmu=["out1"]) print(model_fmu) # call x = [2.0, 0] y = model_fmu(x) print(y) assert abs(y[0] - 24.0) < 1e-4, "wrong value" shutil.rmtree(temp_path)
def test_export_fmu(self): # export fmu f = ot.SymbolicFunction(['E', 'F', 'L', 'I'], ['(F*L^3)/(3.0*E*I)']) start = [3e7, 3e4, 250.0, 400.0] if sys.platform.startswith('win'): return temp_path = tempfile.mkdtemp() path_fmu = os.path.join(temp_path, 'Deviation.fmu') fe = otfmi.FunctionExporter(f, start) fe.export_fmu(path_fmu, fmuType='cs', verbose=False) assert os.path.isfile(path_fmu), "fmu not created" # reimport fmu model_fmu = otfmi.FMUFunction(path_fmu, inputs_fmu=["E", "F", "L", "I"], outputs_fmu=["y0"]) print(model_fmu) # call x = [3.1e7, 3.1e4, 255.0, 420.0] y = model_fmu(x) print(y) assert abs(y[0] - 13.1598) < 1e-4, "wrong value" if 0: # field function mesh = ot.RegularGrid(0, 1, 100) #g = ot.SymbolicFunction(['t', 'a', 'b'], ['a*sin(t)+b']) #f = ot.VertexValuePointToFieldFunction(g, mesh) def g(X): a, b = X Y = [[a*m.sin(t)+b] for t in range(100)] return Y f = ot.PythonPointToFieldFunction(2, mesh, 1, g) start = [4.0, 5.0] # export fe = otfmi.FunctionExporter(f, start) fe.export_fmu(path_fmu, fmuType='cs', verbose=True) assert os.path.isfile(path_fmu), "fmu not created" # import import pyfmi model = pyfmi.load_fmu(path_fmu) model.initialize() res = model.simulate(options={'silent_mode': True}) print(model.get_model_variables().keys()) print(res['y0']) shutil.rmtree(temp_path)
def test_final_time(self): """Check that specified final time is taken into account. """ final_time = 2. model_fmu_1 = otfmi.FMUFunction( self.path_fmu, inputs_fmu=["infection_rate", "healing_rate"], outputs_fmu=["infected"], final_time=final_time) list_last_infected_value = simulate_with_pyfmi(self.path_fmu, final_time=final_time) y = model_fmu_1(input_value) assert y[0] < max(list_last_infected_value) assert y[0] > min(list_last_infected_value)
def test_sobol(self): temp_path = tempfile.mkdtemp() path_mo = os.path.join(temp_path, 'IshigamiFunction.mo') path_fmu = os.path.join(temp_path, 'IshigamiFunction.fmu') with open(path_mo, "w") as mo: mo.write('model IshigamiFunction\n') mo.write(' final parameter Real a = 7;\n') mo.write(' final parameter Real b = 0.05;\n') mo.write(' input Real x1 = 1;\n') mo.write(' input Real x2 = 1;\n') mo.write(' input Real x3 = 1;\n') mo.write(' output Real f;\n') mo.write(' Real d;\n') mo.write('equation\n') mo.write(' f = sin(x1) + a * sin(x2)^2 + b * x3^4 * sin(x1);\n') mo.write(' der(d) = d + 2;\n') mo.write('end IshigamiFunction;\n') otfmi.mo2fmu(path_mo, path_fmu, fmuType="cs", verbose=True) # reimport fmu model_fmu = otfmi.FMUFunction(path_fmu) print(model_fmu, model_fmu.getInputDescription(), model_fmu.getOutputDescription()) model_symbolic = ot.SymbolicFunction( ['x1', 'x2', 'x3'], ['sin(x1) + 7 * sin(x2)^2 + 0.05 * x3^4 * sin(x1)']) # Sobol' DOE X = ot.ComposedDistribution([ot.Uniform(-m.pi, m.pi)] * 3) N = 20 x = ot.SobolIndicesExperiment(X, N).generate() size = len(x) # evaluate DOE t0 = time() process = psutil.Process(os.getpid()) mem0 = process.memory_info().rss / 1000000 for i in range(size): xi = x[i] yi = model_fmu(xi) yi_ref = model_symbolic(xi) assert m.fabs(yi[0] - yi_ref[0]) < 1e-8, "wrong value" print(i, xi, yi, process.memory_info().rss / 1000000, flush=True) t1 = time() mem1 = process.memory_info().rss / 1000000 print("Speed=", size / (t1 - t0), "evals/s") print("Memory=", mem1 - mem0) shutil.rmtree(temp_path)
def setUp(self): """Load FMU and setup pure python reference.""" fmu_name = "epid.fmu" path_example = os.path.dirname(os.path.abspath(otfmi.example.__file__)) try: directory_platform = dict_platform[key_platform] self.path_fmu = os.path.join(path_example, "file", "fmu", directory_platform, fmu_name) self.model_fmu = otfmi.FMUFunction( self.path_fmu, inputs_fmu=["infection_rate", "healing_rate"], outputs_fmu=["infected"]) except KeyError: raise RuntimeError( "Tests are not available on your platform (%s)." % key_platform) except FMUException: raise FMUException( "The test FMU is not available on your platform (%s)." % key_platform)
def instantiate_model(inputs_fmu, outputs_fmu, with_initialization_script=False): """Instantiate an FMUFunction and set number of cores to use. Parameters ---------- inputs_fmu : Sequence of strings, FMU input variable names. outpus_fmu : Sequence of strings, FMU output variable names. with_initialization_script : Boolean, whether or not to use an initialization script. If not (default), appropriate start values are hard-coded in the FMU. """ if with_initialization_script: initialization_script = os.path.join( path_here, "file", "initialization_script", "bil100.mos") filename_fmu = "bil100_initialization_script.fmu" else: initialization_script = None filename_fmu = "bil100.fmu" try: path_fmu = os.path.join(path_here, "file", "fmu", utility.get_directory_platform(), filename_fmu) model = otfmi.FMUFunction(path_fmu, inputs_fmu=inputs_fmu, outputs_fmu=outputs_fmu, initialization_script=initialization_script) except KeyError: raise RuntimeError("Examples are not available on your platform" " (%s)." % "-".join(key_platform)) sys.exit() except FMUException: raise FMUException("The example FMU '%s' is not" " available on your platform (%s)." % (filename_fmu, "-".join(key_platform))) sys.exit() return model
def setUp(self): """Load FMU and setup pure python reference.""" self.model_py = ot.PythonFunction( 4, 1, otfmi.example.deviation.deviationFunction) #§ FMU model path_example = os.path.dirname(os.path.abspath(otfmi.example.__file__)) try: directory_platform = dict_platform[key_platform] path_fmu = os.path.join(path_example, "file", "fmu", directory_platform, "deviation.fmu") self.model_fmu = otfmi.FMUFunction(path_fmu, inputs_fmu=["E", "F", "L", "I"], outputs_fmu="y") except KeyError: raise RuntimeError("Tests are not available on your platform" " (%s)." % key_platform) except FMUException: raise FMUException("The test FMU 'deviation.fmu' is not" " available on your platform (%s)." % key_platform)
# -------- # # # **What is the probability that the deviation exceeds the # threshold ?** # # # We load the FMU as a FMUFunction (see the # :doc:`tutorial<../_generated/otfmi.FMUFunction>`): import otfmi import otfmi.example.utility path_fmu = otfmi.example.utility.get_path_fmu("deviation") model_fmu = otfmi.FMUFunction(path_fmu, inputs_fmu=["E", "F", "L", "I"], outputs_fmu="y") # %% # We test the function wrapping the deviation model on a point: import openturns as ot point = ot.Point([3e7, 2e4, 255, 350]) model_evaluation = model_fmu(point) print("Running the FMU: deviation = {}".format(model_evaluation)) # %% # We define probability laws on the 4 uncertain inputs: E = ot.Beta(0.93, 3.2, 2.8e7, 4.8e7) F = ot.LogNormal() F.setParameter(ot.LogNormalMuSigma()([30.e3, 9e3, 15.e3]))
# %% # If no initial value is provided for an input / parameter, it is set to its # default initial value (as set in the FMU). # %% # We can now build the `FMUFunction`. In the example below, we use the # initialization script to fix the values of ``L`` and ``F`` in the FMU whereas # ``E`` and `Ì` are the function variables. import openturns as ot from os.path import abspath function = otfmi.FMUFunction( path_fmu, inputs_fmu=["E", "I"], outputs_fmu=["y"], initialization_script=abspath("initialization.mos")) inputPoint = ot.Point([2e9, 7e7]) outputPoint = function(inputPoint) print(outputPoint) # %% # .. note:: # It is possible to set the value of a model input in the # initialization script *and* use it as a function input variable. In this # case, the initial value from the initialization script is overriden. # %% # For instance, we consider the 4 model parameters as variables. Note the
import otfmi otfmi.FMUFunction("path/to/fmu", inputs_fmu=["x_1", "x_2", "x_3"], outputs_fmu=["y"])
L_d = ot.Uniform(250.0, 260.0) I_d = ot.Beta(2.5, 4.0-2.5, 310.0, 450.0) distribution = ot.ComposedDistribution([E_d, F_d, I_d, L_d]) x = distribution.getMean() f = model.getFunction() y = f(x) ott.assert_almost_equal(y, [12.3369]) # script script = myStudy.getPythonScript() print('script=', script) exec(script) # compare with pyfmi directly if 0: import pyfmi import otfmi # print(path_fmu) model_fmu = model_fmu = otfmi.FMUFunction( path_fmu, inputs_fmu=['E', 'F', 'I', 'L'], outputs_fmu='y') ml = pyfmi.load_fmu(path_fmu) vars = ml.get_model_variables() for var in vars.values(): print(var.name, var.value_reference) # print(ml.get_real(var.value_reference))