Skip to content

Commit 4847c90

Browse files
authored
Merge pull request #258 from lisawim/SE_new
Inheritance for Battery, hardcoded references and more
2 parents ecbccf9 + 9b02518 commit 4847c90

14 files changed

+1532
-1252
lines changed

pySDC/implementations/problem_classes/Battery.py

Lines changed: 202 additions & 107 deletions
Large diffs are not rendered by default.

pySDC/implementations/problem_classes/Battery_2Condensators.py

Lines changed: 0 additions & 168 deletions
This file was deleted.
Lines changed: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
1+
import numpy as np
2+
import dill
3+
from pathlib import Path
4+
5+
from pySDC.helpers.stats_helper import get_sorted
6+
from pySDC.core.Collocation import CollBase as Collocation
7+
from pySDC.implementations.problem_classes.Battery import battery_n_capacitors
8+
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
9+
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
10+
from pySDC.projects.PinTSimE.battery_model import (
11+
controller_run,
12+
generate_description,
13+
get_recomputed,
14+
log_data,
15+
proof_assertions_description,
16+
)
17+
from pySDC.projects.PinTSimE.piline_model import setup_mpl
18+
import pySDC.helpers.plot_helper as plt_helper
19+
from pySDC.core.Hooks import hooks
20+
21+
from pySDC.projects.PinTSimE.switch_estimator import SwitchEstimator
22+
23+
24+
def run():
25+
"""
26+
Executes the simulation for the battery model using the IMEX sweeper and plot the results
27+
as <problem_class>_model_solution_<sweeper_class>.png
28+
"""
29+
30+
dt = 1e-2
31+
t0 = 0.0
32+
Tend = 3.5
33+
34+
problem_classes = [battery_n_capacitors]
35+
sweeper_classes = [imex_1st_order]
36+
37+
ncapacitors = 2
38+
alpha = 5.0
39+
V_ref = np.array([1.0, 1.0])
40+
C = np.array([1.0, 1.0])
41+
42+
recomputed = False
43+
use_switch_estimator = [True]
44+
45+
for problem, sweeper in zip(problem_classes, sweeper_classes):
46+
for use_SE in use_switch_estimator:
47+
description, controller_params = generate_description(
48+
dt, problem, sweeper, log_data, False, use_SE, ncapacitors, alpha, V_ref, C
49+
)
50+
51+
# Assertions
52+
proof_assertions_description(description, False, use_SE)
53+
54+
proof_assertions_time(dt, Tend, V_ref, alpha)
55+
56+
stats = controller_run(description, controller_params, False, use_SE, t0, Tend)
57+
58+
check_solution(stats, dt, use_SE)
59+
60+
plot_voltages(description, problem.__name__, sweeper.__name__, recomputed, use_SE, False)
61+
62+
63+
def plot_voltages(description, problem, sweeper, recomputed, use_switch_estimator, use_adaptivity, cwd='./'):
64+
"""
65+
Routine to plot the numerical solution of the model
66+
67+
Args:
68+
description(dict): contains all information for a controller run
69+
problem (pySDC.core.Problem.ptype): problem class that wants to be simulated
70+
sweeper (pySDC.core.Sweeper.sweeper): sweeper class for solving the problem class numerically
71+
recomputed (bool): flag if the values after a restart are used or before
72+
use_switch_estimator (bool): flag if the switch estimator wants to be used or not
73+
use_adaptivity (bool): flag if adaptivity wants to be used or not
74+
cwd (str): current working directory
75+
"""
76+
77+
f = open(cwd + 'data/{}_{}_USE{}_USA{}.dat'.format(problem, sweeper, use_switch_estimator, use_adaptivity), 'rb')
78+
stats = dill.load(f)
79+
f.close()
80+
81+
# convert filtered statistics to list of iterations count, sorted by process
82+
cL = np.array([me[1][0] for me in get_sorted(stats, type='u', recomputed=recomputed)])
83+
vC1 = np.array([me[1][1] for me in get_sorted(stats, type='u', recomputed=recomputed)])
84+
vC2 = np.array([me[1][2] for me in get_sorted(stats, type='u', recomputed=recomputed)])
85+
86+
t = np.array([me[0] for me in get_sorted(stats, type='u', recomputed=recomputed)])
87+
88+
setup_mpl()
89+
fig, ax = plt_helper.plt.subplots(1, 1, figsize=(4.5, 3))
90+
ax.plot(t, cL, label='$i_L$')
91+
ax.plot(t, vC1, label='$v_{C_1}$')
92+
ax.plot(t, vC2, label='$v_{C_2}$')
93+
94+
if use_switch_estimator:
95+
switches = get_recomputed(stats, type='switch', sortby='time')
96+
if recomputed is not None:
97+
assert len(switches) >= 2, f"Expected at least 2 switches, got {len(switches)}!"
98+
t_switches = [v[1] for v in switches]
99+
100+
for i in range(len(t_switches)):
101+
ax.axvline(x=t_switches[i], linestyle='--', color='k', label='Switch {}'.format(i + 1))
102+
103+
ax.legend(frameon=False, fontsize=12, loc='upper right')
104+
105+
ax.set_xlabel('Time')
106+
ax.set_ylabel('Energy')
107+
108+
fig.savefig('data/battery_2capacitors_model_solution.png', dpi=300, bbox_inches='tight')
109+
plt_helper.plt.close(fig)
110+
111+
112+
def check_solution(stats, dt, use_switch_estimator):
113+
"""
114+
Function that checks the solution based on a hardcoded reference solution. Based on check_solution function from @brownbaerchen.
115+
116+
Args:
117+
stats (dict): Raw statistics from a controller run
118+
dt (float): initial time step
119+
use_switch_estimator (bool): flag if the switch estimator wants to be used or not
120+
"""
121+
122+
data = get_data_dict(stats, use_switch_estimator)
123+
124+
if use_switch_estimator:
125+
msg = f'Error when using the switch estimator for battery_2condensators for dt={dt:.1e}:'
126+
if dt == 1e-2:
127+
expected = {
128+
'cL': 1.2065280755094876,
129+
'vC1': 1.0094825899806945,
130+
'vC2': 1.0050052828742688,
131+
'switch1': 1.6094379124373626,
132+
'switch2': 3.209437912457051,
133+
'restarts': 2.0,
134+
'sum_niters': 1568,
135+
}
136+
elif dt == 4e-1:
137+
expected = {
138+
'cL': 1.1842780233981391,
139+
'vC1': 1.0094891393319418,
140+
'vC2': 1.00103823232433,
141+
'switch1': 1.6075867934844466,
142+
'switch2': 3.209437912436633,
143+
'restarts': 2.0,
144+
'sum_niters': 2000,
145+
}
146+
elif dt == 4e-2:
147+
expected = {
148+
'cL': 1.180493652021971,
149+
'vC1': 1.0094825917376264,
150+
'vC2': 1.0007713468084405,
151+
'switch1': 1.6094074085553605,
152+
'switch2': 3.209437912440314,
153+
'restarts': 2.0,
154+
'sum_niters': 2364,
155+
}
156+
elif dt == 4e-3:
157+
expected = {
158+
'cL': 1.1537529501025199,
159+
'vC1': 1.001438946726028,
160+
'vC2': 1.0004331625246141,
161+
'switch1': 1.6093728710270467,
162+
'switch2': 3.217437912434171,
163+
'restarts': 2.0,
164+
'sum_niters': 8920,
165+
}
166+
167+
got = {
168+
'cL': data['cL'][-1],
169+
'vC1': data['vC1'][-1],
170+
'vC2': data['vC2'][-1],
171+
'switch1': data['switch1'],
172+
'switch2': data['switch2'],
173+
'restarts': data['restarts'],
174+
'sum_niters': data['sum_niters'],
175+
}
176+
177+
for key in expected.keys():
178+
assert np.isclose(
179+
expected[key], got[key], rtol=1e-4
180+
), f'{msg} Expected {key}={expected[key]:.4e}, got {key}={got[key]:.4e}'
181+
182+
183+
def get_data_dict(stats, use_switch_estimator, recomputed=False):
184+
"""
185+
Converts the statistics in a useful data dictionary so that it can be easily checked in the check_solution function.
186+
Based on @brownbaerchen's get_data function.
187+
188+
Args:
189+
stats (dict): Raw statistics from a controller run
190+
use_switch_estimator (bool): flag if the switch estimator wants to be used or not
191+
recomputed (bool): flag if the values after a restart are used or before
192+
193+
Return:
194+
data (dict): contains all information as the statistics dict
195+
"""
196+
197+
data = dict()
198+
data['cL'] = np.array([me[1][0] for me in get_sorted(stats, type='u', recomputed=False, sortby='time')])
199+
data['vC1'] = np.array([me[1][1] for me in get_sorted(stats, type='u', recomputed=False, sortby='time')])
200+
data['vC2'] = np.array([me[1][2] for me in get_sorted(stats, type='u', recomputed=False, sortby='time')])
201+
data['switch1'] = np.array(get_recomputed(stats, type='switch', sortby='time'))[0, 1]
202+
data['switch2'] = np.array(get_recomputed(stats, type='switch', sortby='time'))[-1, 1]
203+
data['restarts'] = np.sum(np.array(get_sorted(stats, type='restart', recomputed=None, sortby='time'))[:, 1])
204+
data['sum_niters'] = np.sum(np.array(get_sorted(stats, type='niter', recomputed=None, sortby='time'))[:, 1])
205+
206+
return data
207+
208+
209+
def proof_assertions_time(dt, Tend, V_ref, alpha):
210+
"""
211+
Function to proof the assertions regarding the time domain (in combination with the specific problem):
212+
213+
Args:
214+
dt (float): time step for computation
215+
Tend (float): end time
216+
V_ref (np.ndarray): Reference values (problem parameter)
217+
alpha (np.float): Multiple used for initial conditions (problem_parameter)
218+
"""
219+
220+
assert (
221+
Tend == 3.5 and V_ref[0] == 1.0 and V_ref[1] == 1.0 and alpha == 5.0
222+
), "Error! Do not use other parameters for V_ref[:] != 1.0, alpha != 1.2, Tend != 0.3 due to hardcoded reference!"
223+
224+
assert (
225+
dt == 1e-2 or dt == 4e-1 or dt == 4e-2 or dt == 4e-3
226+
), "Error! Do not use other time steps dt != 4e-1 or dt != 4e-2 or dt != 4e-3 due to hardcoded references!"
227+
228+
229+
if __name__ == "__main__":
230+
run()

0 commit comments

Comments
 (0)