Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
RWTH-EBC
GitHub Repository: RWTH-EBC/ebcpy
Path: blob/master/examples/e2_fmu_example.py
505 views
1
"""
2
Goals of this part of the examples:
3
4
1. Learn how to use the `FMU_API`
5
2. Understand model variables
6
3. Learn how to change variables to store (`result_names`)
7
4. Learn how to change parameters of a simulation
8
5. Learn how to change inputs of a simulation
9
6. Learn how to run simulations in parallel
10
"""
11
# Start by importing all relevant packages
12
import pathlib
13
import numpy as np
14
import matplotlib.pyplot as plt
15
import pandas as pd
16
17
# Imports from ebcpy
18
from ebcpy import FMU_API
19
20
21
def main(
22
working_directory=None,
23
n_cpu=1,
24
log_fmu=True,
25
n_sim=5,
26
output_interval=100,
27
with_plot=True
28
):
29
"""
30
Arguments of this example:
31
:param str working_directory:
32
Path in which to store the output.
33
Default is the examples\results folder
34
:param int n_cpu:
35
Number of processes to use
36
:param bool log_fmu:
37
Whether to get the FMU log output
38
:param int n_sim:
39
Number of simulations to run
40
:param int output_interval:
41
Output interval / step size of the simulation
42
:param bool with_plot:
43
Show the plot at the end of the script. Default is True.
44
"""
45
46
# General settings
47
if working_directory is None:
48
working_directory = pathlib.Path(__file__).parent.joinpath("results")
49
50
# ######################### Simulation API Instantiation ##########################
51
# %% Setup the FMU-API:
52
model_name = pathlib.Path(__file__).parent.joinpath("data", "HeatPumpSystemWithInput.fmu")
53
fmu_api = FMU_API(model_name=model_name,
54
working_directory=working_directory,
55
n_cpu=n_cpu,
56
log_fmu=log_fmu)
57
print("Number of variables:", len(fmu_api.variables))
58
print("Number of outputs:", len(fmu_api.outputs))
59
print("Number of inputs:", len(fmu_api.inputs))
60
print("Number of parameters:", len(fmu_api.parameters))
61
print("Number of states:", len(fmu_api.states))
62
print("Variables to store when simulating:", fmu_api.result_names)
63
print("Outputs of the fmu", fmu_api.outputs)
64
65
# ######################### Simulation Setup Part ##########################
66
# Change the simulation settings:
67
# Which settings can I change?
68
print("Supported setup options:", fmu_api.get_simulation_setup_fields())
69
fmu_api.sim_setup.start_time = 0
70
fmu_api.sim_setup.stop_time = 3600
71
fmu_api.sim_setup.output_interval = output_interval
72
# Or pass a dictionary. This makes using configs (toml, json) much easier
73
simulation_setup = {"start_time": 0,
74
"stop_time": 3600,
75
"output_interval": output_interval}
76
fmu_api.set_sim_setup(sim_setup=simulation_setup)
77
78
# ######################### Parameters ##########################
79
# Let's get some parameter to change, e.g. the capacity of the thermal mass:
80
print(fmu_api.parameters['heaCap.C'])
81
hea_cap_c = fmu_api.parameters['heaCap.C'].value
82
# Let's alter it from 10% to 1000 % in n_sim simulations:
83
sizings = np.linspace(0.1, 10, n_sim)
84
parameters = []
85
for sizing in sizings:
86
parameters.append({"heaCap.C": hea_cap_c * sizing})
87
88
# Additional information: Dynamic exchange of parameter values has the same syntax when using DymolaAPI,
89
# instead of FMU_API.
90
91
# ######################### Inputs ##########################
92
# Let's also change the input of the simulation:
93
print("Inputs names are:", fmu_api.inputs)
94
# We only have TDryBul (outdoor air temperature) as an input.
95
# Start with the setup of a time-index that matches our simulation setup
96
# Feel free to play around with the settings to see what happens if your time_index is malformed.
97
time_index = np.arange(
98
fmu_api.sim_setup.start_time,
99
fmu_api.sim_setup.stop_time,
100
fmu_api.sim_setup.output_interval
101
)
102
# Apply some sinus function for the outdoor air temperature
103
t_dry_bulb = np.sin(time_index/3600*np.pi) * 10 + 263.15
104
df_inputs = pd.DataFrame({"TDryBul": t_dry_bulb}, index=time_index)
105
# Warning: If you enable the following line you will trigger an error.
106
# It only goes to show that inputs to the simulation must contain clear
107
# tags.
108
# df_inputs[('TDryBul', 'constant_0_degC')] = 275.15
109
110
# ######################### Results to store ##########################
111
# As we vary the heating capacity,
112
# let's plot the influence on the temperature of said capacity:
113
# Per default, all outputs will be stored:
114
print("Results that will be stored", fmu_api.result_names)
115
# In our case, we are not interested in Pel but in other states:
116
# First, the temperature
117
# Second, the input outdoor air temperature to see if our input is correctly used.
118
fmu_api.result_names = ["heatCap.T", "TDryBul"]
119
# Oops, `heatCap.T` is not part of the model. We warn you about such typos.
120
# This way, you can easier debug your simulations if something goes wrong.
121
# Set the correct names:
122
fmu_api.result_names = ["heaCap.T", "TDryBul"]
123
print("Results that will be stored", fmu_api.result_names)
124
125
# ######################### Execute simulation ##########################
126
# Pass the created list to the simulate function
127
results = fmu_api.simulate(parameters=parameters,
128
inputs=df_inputs)
129
130
# ######################### Closing ##########################
131
# Close the fmu. If you forget to do so,
132
# we call this function at the exit of your script.
133
# It deleted all extracted FMU files.
134
fmu_api.close()
135
136
# ######################### Visualization ##########################
137
# Plot the result
138
fig, ax = plt.subplots(2, sharex=True)
139
ax[0].set_ylabel("TDryBul in K")
140
ax[1].set_ylabel("T_Cap in K")
141
ax[1].set_xlabel("Time in s")
142
ax[0].plot(df_inputs, label="Inputs", linestyle="--")
143
for res, sizing in zip(results, sizings):
144
ax[0].plot(res['TDryBul'])
145
ax[1].plot(res['heaCap.T'], label=sizing)
146
for _ax in ax:
147
_ax.legend(bbox_to_anchor=(1, 1.05), loc="upper left")
148
149
if with_plot:
150
plt.show()
151
# Save the data for later reproduction
152
file = fmu_api.save_for_reproduction(
153
title="FMUTest",
154
log_message="This is just an example.")
155
print("ZIP-File to reproduce all this:", file)
156
157
158
if __name__ == '__main__':
159
main(
160
n_cpu=5,
161
log_fmu=False,
162
n_sim=5,
163
output_interval=100
164
)
165
166