/
run_dg_utils.py
176 lines (143 loc) · 6.08 KB
/
run_dg_utils.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
"""
Script with utility functions for running DG examples and convergence studies
"""
from glob import glob
import os
from matplotlib import pyplot as plt
import numpy as nm
from sfepy.discrete import Integral, Material, Integrals
from sfepy.discrete.common.mappings import get_jacobian
from sfepy.base.base import output, configure_output
from example_dg_common import diffusion_schemes_explicit, clear_folder
outputs_folder = "outputs"
# configure_output({'output_screen': True,
# 'output_log_name': pjoin(outputs_folder, "last_run.txt")})
param_names = ["adflux", "limit", "cw", "diffcoef", "diffscheme", "cfl", "dt"]
def add_dg_arguments(parser):
"""
Adds arguments for parametrizing DG example:
advelo, adflux, limit, cw, diffcoef, diffscheme,
cfl, dt
"""
parser.add_argument('--advelo', metavar='float', type=float,
action='store', dest='advelo',
default=None, help="Advection velocity")
parser.add_argument('--adflux', metavar='float', type=float,
action='store', dest='adflux',
default=None, help="Advection flux parameter, " +
"\n0.0 - upwind, " +
"\n1.0 - central")
parser.add_argument("--limit", help="Use 1D or 2D moment limiter",
default=None, action='store_true', dest='limit', )
parser.add_argument('--cw', metavar='float', type=float,
action='store', dest='cw',
default=None, help="Diffusion penalty coefficient")
parser.add_argument('--diffcoef', metavar='float', type=float,
action='store', dest='diffcoef',
default=None, help="Diffusion coeffcient")
parser.add_argument('--diffscheme', type=str,
choices=diffusion_schemes_explicit.keys(),
action='store', dest='diffscheme',
default=None, help="Scheme to use for diffusion")
parser.add_argument('--cfl', metavar='float', type=float,
action='store', dest='cfl',
default=None, help="CFL coefficient")
parser.add_argument('--dt', metavar='float', type=float,
action='store', dest='dt',
default=None,
help="Time step size, overrides CFL coefficient")
def plot_conv_results(base_output_folder, conf, err_df,
plot_title_attrs=None, save=False):
"""
Plots errors along with convergence rate estimates.
:param base_output_folder:
:param conf: conf structure defined in declarative mode, or object
containing: dt, CFL or diffusion_coef attributese, example_name
:plot_title_attrs: attributes to list in the figure sup title
:param err_df: pandas dataframe containing at least:
"order", "num_order", "n_cells", "diff_l2" columns
:return:
"""
if plot_title_attrs is None:
plot_title_attrs = ["Cw", "diffusion_coef", "dt", "CFL"]
fig_sup_title = "Convergence by order"
fig_sup_title += build_attrs_string(conf, plot_title_attrs, sep=", ",
remove_dots=False)
conv_fig, ax = plt.subplots(1, 1)
conv_fig.suptitle(fig_sup_title)
orders = sorted(err_df["order"].unique())
for o in orders:
ax.set_xscale('log', basex=2)
ax.set_yscale('log', basey=10)
curr_df = err_df[err_df["order"] == o]
co = ax.plot(curr_df["n_cells"], curr_df["diff_l2"], 'o',
label=str(int(o)))[0].get_color()
ax.plot(curr_df["n_cells"], curr_df["diff_l2"], color=co, label="")
for i, r in curr_df.iloc[1:, :].iterrows():
ax.text(r["n_cells"], r["diff_l2"], "{:.2}".format(r["num_order"]))
ax.grid(True)
ax.set_xlabel("cells")
ax.set_ylabel("L^2 error")
ax.legend(title="Order")
return conv_fig
def compute_erros(analytic_fun, pb):
"""
Compute errors from analytical solution in conf.sol_fun and numerical
solution saved in pb
:param analytic_fun: analytic solution
:param pb: problem with numerical solution
:return: analytic_fun L2 norm,
vaules of analytic_fun in qps
L2 norm of difference between analytic and numerical solution
relative difference
values of numerical solution in qps
"""
idiff = Integral('idiff', 20)
num_qp = pb.evaluate(
'ev_volume_integrate.idiff.Omega(p)',
integrals=Integrals([idiff]), mode='qp',
copy_materials=False, verbose=False
)
aux = Material('aux', function=analytic_fun)
ana_qp = pb.evaluate(
'ev_volume_integrate_mat.idiff.Omega(aux.p, p)',
aux=aux, integrals=Integrals([idiff]), mode='qp',
copy_materials=False, verbose=False
)
field = pb.fields['f']
det = get_jacobian(field, idiff)
diff_l2 = nm.sqrt((((num_qp - ana_qp) ** 2) * det).sum())
ana_l2 = nm.sqrt(((ana_qp ** 2) * det).sum())
rel_l2 = diff_l2 / ana_l2
diff_loo = nm.max(num_qp - ana_qp)
ana_loo = nm.max(ana_qp)
rel_loo = diff_loo / ana_loo
diff_l1 = nm.sqrt((nm.abs(num_qp - ana_qp) * det).sum())
ana_l1 = nm.sqrt((nm.abs(ana_qp) * det).sum())
rel_l1 = diff_l2 / ana_l2
return ana_l2, ana_qp, diff_l2, rel_l2, num_qp
def build_attrs_string(conf, attrs=("Cw", "diffusion_coef", "dt", "CFL"),
sep="_", ret_form=False, remove_dots=True):
"""
Builds string from intersection of attributes
list attrs and conf attributes, removes "." !
:param conf:
:param attrs:
:param sep:
:return:
"""
form = ""
attr_vals = []
for attr in attrs:
attr_val = getattr(conf, attr, None)
if attr_val is not None:
form += sep + attr + "{}"
attr_vals += [attr_val]
if not remove_dots:
res = form.format(*attr_vals)
else:
res = form.format(*attr_vals).replace(".", "")
if ret_form:
return res, form, attr_vals
else:
return res