Repository navigation
Expand file tree
/
Copy pathanalysis.py
More file actions
156 lines (130 loc) · 6.51 KB
/
Copy pathanalysis.py
File metadata and controls
156 lines (130 loc) · 6.51 KB
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
# SPDX-FileCopyrightText: 2026 canoP authors
#
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Analysis of a convergence campaign: L1 error of the density versus amr.max_refine.
The runs advect the sine wave of physics/onephase/initial_conditions/sine.py in a periodic domain,
on a uniform mesh. analyse() reads the last output of each run, compares its density with the exact
solution (the initial wave moved by (vx, vy) t) and gives the L1 error and the observed order between
successive levels; panel() shows them, with the error versus the number of cells. The graph of the
tab shows the metric chosen in it versus the chosen parameter (e.g. the time of each run).
"""
import base64
import configparser
import glob
import io
import math
import os
import re
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
_errors = {} # (output, modification time) -> (error, cells per direction)
def _ini(run_dir):
"""Input file of a run, as a ConfigParser."""
ini = configparser.ConfigParser(comment_prefixes=("#", ";"), inline_comment_prefixes=(";",), strict=False)
for path in sorted(glob.glob(os.path.join(run_dir, "*.ini"))):
ini.read(path, encoding="utf-8")
return ini
def _last_output(run_dir):
"""Last output (XDMF file) of a run, or None."""
steps = sorted(glob.glob(os.path.join(run_dir, "*_iter*.xmf")))
return steps[-1] if steps else None
def _cells(path):
"""Density, cell centres, cell areas and time of an output."""
# pylint: disable=import-outside-toplevel (VTK is only needed here)
from vtkmodules.util.numpy_support import vtk_to_numpy
from vtkmodules.vtkFiltersParallel import vtkMergeBlocks
from vtkmodules.vtkIOXdmf2 import vtkXdmfReader
reader = vtkXdmfReader()
reader.SetFileName(path)
reader.Update()
grid = reader.GetOutputDataObject(0)
if grid.IsA("vtkCompositeDataSet"):
merge = vtkMergeBlocks()
merge.SetInputData(grid)
merge.Update()
grid = merge.GetOutput()
points = vtk_to_numpy(grid.GetPoints().GetData()).astype(float)
corners = points[vtk_to_numpy(grid.GetCells().GetConnectivityArray()).reshape(-1, 4)] # quads, 2D
centres = corners.mean(axis=1)
sizes = corners.max(axis=1) - corners.min(axis=1)
density = vtk_to_numpy(grid.GetCellData().GetArray("m"))
with open(path, encoding="utf-8") as fd:
time = float(re.search(r'<Time[^>]*Value="([^"]+)"', fd.read()).group(1))
return density, centres, sizes[:, 0] * sizes[:, 1], time, points
def l1_error(run_dir):
"""L1 error of the density of the last output of a run, and its number of cells per direction."""
path = _last_output(run_dir)
if path is None:
return None
key = (path, os.path.getmtime(path))
if key not in _errors:
ini = _ini(run_dir)
sine = ini["sine"] if ini.has_section("sine") else {}
def value(name, default):
return float(sine.get(name, default))
density, centres, areas, time, points = _cells(path)
lower, length = points.min(axis=0), points.max(axis=0) - points.min(axis=0)
x = (centres[:, 0] - lower[0] - value("vx", 1.0) * time) / length[0]
y = (centres[:, 1] - lower[1] - value("vy", 1.0) * time) / length[1]
exact = value("m0", 1.0) + value("amplitude", 0.2) * np.sin(2 * math.pi * x) * np.sin(2 * math.pi * y)
error = float(np.sum(np.abs(density - exact) * areas) / np.sum(areas))
_errors[key] = (error, round(length[0] / math.sqrt(areas.mean())))
return _errors[key]
def _run_dir(run):
"""Directory of a run, from the start of its id (the studio gives its first 8 characters)."""
found = glob.glob(os.path.join(HERE, "workspace", glob.escape(run) + "*"))
return found[0] if len(found) == 1 else None
def analyse(points, x, y):
"""L1 error of each run, sorted by number of cells, with the observed order between neighbours."""
rows = []
for _, _, run in points:
run_dir = _run_dir(run)
found = l1_error(run_dir) if run_dir else None
if found:
rows.append({"run": run[:8], "cells": found[1], "error": found[0]})
rows.sort(key=lambda r: r["cells"])
for coarse, fine in zip(rows, rows[1:]):
fine["order"] = math.log(coarse["error"] / fine["error"]) / math.log(fine["cells"] / coarse["cells"])
return {"rows": rows, "plot": _plot(rows) if len(rows) > 1 else None}
def _plot(rows):
"""Log-log plot of the error versus the number of cells per direction, as a PNG data URL."""
import matplotlib # pylint: disable=import-outside-toplevel
matplotlib.use("Agg")
import matplotlib.pyplot as plt # pylint: disable=import-outside-toplevel
from matplotlib.ticker import NullLocator # pylint: disable=import-outside-toplevel
n = np.array([r["cells"] for r in rows], dtype=float)
e = np.array([r["error"] for r in rows])
fig, ax = plt.subplots(figsize=(4.6, 3.4), dpi=100)
ax.loglog(n, e, "o-", label="L1 error of the density")
ax.loglog(n, e[0] * (n[0] / n) ** 2, "--", color="grey", label="order 2")
ax.set_xticks(n, labels=["%d" % v for v in n]) # the meshes of the runs, not the powers of 10
ax.xaxis.set_minor_locator(NullLocator())
ax.set_xlabel("cells per direction")
ax.set_ylabel("L1 error")
ax.grid(True, which="both", alpha=0.3)
ax.legend(fontsize=8)
fig.tight_layout()
buf = io.BytesIO()
fig.savefig(buf, format="png")
plt.close(fig)
return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
def draw(ax, points, result, x, y):
"""Nothing to add to the graph of the tab."""
def panel(app):
"""The convergence plot and the table of the errors and orders."""
v3, html = app.v3, app.html
html.Div("No finished run yet.", v_if="!an_result || !an_result.rows.length",
classes="text-caption text-medium-emphasis pa-2")
with html.Div(v_if="an_result && an_result.rows.length"):
html.Img(src=("an_result.plot",), v_if="an_result.plot", style="width: 100%")
with v3.VTable(density="compact"):
with html.Thead():
with html.Tr():
for title in ("run", "cells", "L1 error", "order"):
html.Th(title)
with html.Tbody():
with html.Tr(v_for="r in an_result.rows", key="r.run"):
html.Td("{{ r.run }}", classes="mono")
html.Td("{{ r.cells }}²")
html.Td("{{ r.error.toExponential(3) }}")
html.Td("{{ r.order === undefined ? '' : r.order.toFixed(2) }}")