Skip to content

Commit

Permalink
Implemented a solution for automatic reporting of initial values for …
Browse files Browse the repository at this point in the history
…all cases
  • Loading branch information
eisDNV committed Nov 1, 2024
1 parent 0764816 commit 15bee56
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 33 deletions.
53 changes: 36 additions & 17 deletions case_study/case.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,7 @@ def do_actions(_t: float, _a, _iter, time: int, record: bool = True):
_t, _a = 10 * tstop, []
return (_t, _a)

# Note: final actions are included as _get at end time
# Note: final actions are included as _get at stopTime
tstart: int = int(self.special["startTime"] * self.cases.timefac)
time = tstart
tstop: int = int(self.special["stopTime"] * self.cases.timefac)
Expand All @@ -442,12 +442,15 @@ def do_actions(_t: float, _a, _iter, time: int, record: bool = True):
t_get, a_get = next(get_iter)
except StopIteration:
t_get, a_get = (tstop + 1, [])
if t_get < 0:
if t_get < 0: # negative time indicates 'always'
act_step = a_get
else:
break

while True:

for a in a_set: # since there is no hook to get initial values we report it this way
self.res.add( tstart, *a.args)

while True: # main simulation loop
t_set, a_set = do_actions(t_set, a_set, set_iter, time, record=False)

time += tstep
Expand Down Expand Up @@ -1006,6 +1009,33 @@ def inspect(self, component: str | None = None, variable: str | None = None):
)
return cont

def time_series(self, variable: str):
"""Extract the provided alias variables and make them available as two lists 'times' and 'values'
of equal length.
Args:
variable (str): variable identificator as str.
A variable identificator is the jspath expression after the time, i.e. <component>.<variable>[<element>]
For example 'bb.v[2]' identifies the z-velocity of the component 'bb'
Returns:
tuple of two lists (times, values)
"""
if not len(self.res.js_py) or self.case is None:
return
times: list = []
values: list = []
for key in self.res.js_py:
found = self.res.jspath("$['" + str(key) + "']." + variable)
if found is not None:
if isinstance(found, list):
raise NotImplementedError("So far not implemented for multi-dimensional plots") from None
else:
times.append(key)
values.append(found)
return (times, values)


def plot_time_series(self, variables: list[str], title: str = ""):
"""Extract the provided alias variables and plot the data found in the same plot.
Expand All @@ -1015,20 +1045,8 @@ def plot_time_series(self, variables: list[str], title: str = ""):
For example 'bb.v[2]' identifies the z-velocity of the component 'bb'
title (str): optional title of the plot
"""
if not len(self.res.js_py) or self.case is None:
return
#timefac = self.case.cases.timefac
for var in variables:
times: list = []
values: list = []
for key in self.res.js_py:
found = self.res.jspath("$['" + str(key) + "']." + var)
if found is not None:
if isinstance(found, list):
raise NotImplementedError("So far not implemented for multi-dimensional plots") from None
else:
times.append(key)
values.append(found)
times, values = self.time_series( var)

plt.plot(times, values, label=var, linewidth=3)

Expand All @@ -1038,3 +1056,4 @@ def plot_time_series(self, variables: list[str], title: str = ""):
# plt.ylabel('Values')
plt.legend()
plt.show()

6 changes: 3 additions & 3 deletions tests/data/BouncingBall3D/BouncingBall3D.cases
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ base : {
g : 9.81,
e : 1.0,
x[2] : 39.37007874015748, # this is in inch => 1m!
# }
# assert: {
# 1 : 'abs(g-9.81)<1e-9'
}},
restitution : {
description : "Smaller coefficient of restitution e",
Expand All @@ -36,9 +39,6 @@ gravity : {
}},
results : {
spec : [
e@0.0,
g@0.0,
x@0.0,
x@step,
v@step,
'x_b[0]@step',
Expand Down
Binary file modified tests/data/BouncingBall3D/BouncingBall3D.fmu
Binary file not shown.
18 changes: 9 additions & 9 deletions tests/test_bouncing_ball_3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,9 @@ def check_case(
v_bounce = g * t_bounce # speed in z-direction
x_bounce = v[0] * t_bounce # x-position where it bounces
# check outputs after first step:
assert results.res.jspath("$['0.01'].bb.e") == e, "Not possible to check at time 0!"
assert results.res.jspath("$['0.01'].bb.g") == g, "Not possible to check at time 0!"
assert results.res.jspath("$['0'].bb.e") == e, "??Initial value of e"
assert results.res.jspath("$['0'].bb.g") == g, "??Initial value of g"
assert results.res.jspath("$['0'].bb.['x[2]']") == x[2], "??Initial value of x[2]"
arrays_equal(results.res.jspath("$['0.01'].bb.x"), [dt, 0, x[2] - 0.5 * g * dt**2 / hf])
arrays_equal(results.res.jspath("$['0.01'].bb.v"), [v[0], 0, -g * dt])
x_b = results.res.jspath("$.['0.01'].bb.['x_b[0]']")
Expand Down Expand Up @@ -171,12 +172,11 @@ def test_run_cases():


if __name__ == "__main__":
# retcode = pytest.main(["-rA", "-v", __file__, "--show", "True"])
# assert retcode == 0, f"Non-zero return code {retcode}"
import os

os.chdir(Path(__file__).parent.absolute() / "test_working_directory")
fmu = _ensure_fmu()
retcode = pytest.main(["-rA", "-v", __file__, "--show", "True"])
assert retcode == 0, f"Non-zero return code {retcode}"
# import os
# os.chdir(Path(__file__).parent.absolute() / "test_working_directory")
# fmu = _ensure_fmu()
# test_make_fmu()
# test_run_fmpy( show=True)
test_run_cases()
# test_run_cases()
10 changes: 6 additions & 4 deletions tests/test_results.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from datetime import datetime
from pathlib import Path
import pytest

from case_study.case import Cases, Results

Expand Down Expand Up @@ -33,7 +34,8 @@ def test_add():


def test_plot_time_series():
file = Path.cwd().parent / "data" / "BouncingBall3D" / "test_results.js5"
file = Path(__file__).parent / "data" / "BouncingBall3D" / "test_results.js5"
assert file.exists(), f"File {file} not found"
res = Results(file=file)
res.plot_time_series(("bb.x[2]", "bb.v[2]"), "Test plot")

Expand All @@ -53,11 +55,11 @@ def test_inspect():


if __name__ == "__main__":
# retcode = pytest.main(["-rA", "-v", __file__])
# assert retcode == 0, f"Non-zero return code {retcode}"
retcode = pytest.main(["-rA", "-v", __file__])
assert retcode == 0, f"Non-zero return code {retcode}"
# import os
# os.chdir(Path(__file__).parent.absolute() / "test_working_directory")
# test_init()
# test_add()
test_plot_time_series(show=True)
# test_plot_time_series()
# test_inspect()

0 comments on commit 15bee56

Please sign in to comment.