forked from CATIA-Systems/FMPy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom_input.py
97 lines (68 loc) · 2.87 KB
/
custom_input.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
""" This example demonstrates how to use the FMU.get*() and FMU.set*() functions
to set custom input and control the simulation """
from fmpy import read_model_description, extract
from fmpy.fmi2 import FMU2Slave
from fmpy.util import plot_result, download_test_file
import numpy as np
import shutil
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
if __name__ == '__main__':
simulate_custom_input()