"""Matplotlib plots of solver results, in the units people read.
import matplotlib.pyplot as plt
from openairbearing import core, plots
film = core.circular_pad(18.5e-3, porous=core.Porous(), ps=0.5e6)
state = core.solve_static(film, [5e-6, 1e-4, 0.0])
plots.plot_field(state, gauge=True) # map of the pressure
plots.plot_profile(state, gauge=True) # the same along a line
plt.show()
Every function draws into the axes it is given (a new figure otherwise) and
returns them, so the figure stays ordinary matplotlib: lay it out, add
curves and annotate as usual. Keywords that a function does not name go to
the matplotlib call that draws the data.
plot_field and plot_profile take a solved state (``core.solve_static``) or
a field document (``study.field``); plot_geometry takes a film;
plot_output takes a study result (``study.run``), fresh or loaded from JSON,
and draws it in display units or, with ``normalise``, in a named
dimensionless scheme of ``openairbearing.normalise``.
Inputs are in SI units. What is drawn is in the display units of
``openairbearing.display``, which also converts curves drawn by hand:
pressure in MPa, film thickness in µm, the film coordinates in mm and
degrees, stiffness in N/µm and flow in L/min of free gas.
"""
from __future__ import annotations
import numpy as np
from . import display
from .core.meshes import element_edges, reference_corners, triangles
__all__ = [
"COLOURS",
"plot_field",
"plot_geometry",
"plot_output",
"plot_profile",
]
_FIELDS = {"p": ("Pressure", "Pa"), "h": ("Film thickness", "m")}
# colours of the prescribed edges in plot_geometry, strong against the grey mesh
_EDGES = ("blue", "red", "green", "darkviolet", "darkorange", "black")
# the colours of the series of a plot, in this order
COLOURS = ("blue", "red", "black", "grey")
def _new_axes():
"""The axes of a new figure, its series in ``COLOURS``."""
import matplotlib.pyplot as plt
ax = plt.subplots()[1]
ax.set_prop_cycle(color=COLOURS)
return ax
def _field(source, what: str, gauge: bool):
"""A field as drawing data, in display units.
Returns (grid, values, coords, label): a matplotlib Triangulation, the
values at its points, the (name, SI unit) of the two coordinates and the
label of the values.
"""
from matplotlib.tri import Triangulation
if what not in _FIELDS:
raise ValueError('what must be "p" or "h"')
if isinstance(source, dict): # field document
coords = [(source[key]["name"], source[key]["unit"]) for key in ("x", "y")]
x = np.array([source["x"]["values"], source["y"]["values"]], dtype=float)
t = np.column_stack([source["i"], source["j"], source["k"]])
values = np.array(source[what]["values"], dtype=float)
pa = source["pa"]
else: # solved state
film = source.film
coords = list(film.coords)
x, t, p = triangles(film.basis, source.p)
t = t.T
values = p if what == "p" else film.gap(x, source.q) * np.ones(x.shape[1])
pa = film.pa
name, unit = _FIELDS[what]
if what == "p" and gauge:
name, values = "Gauge pressure", values - pa
grid = Triangulation(
*(
display.shown(v, u, coordinate=True)
for v, (_, u) in zip(x, coords, strict=True)
),
t,
)
return grid, display.shown(values, unit), coords, display.label(name, unit)
[docs]
def plot_field(
source,
what: str = "p",
ax=None,
*,
gauge: bool = False,
colorbar: bool = True,
**mesh,
):
"""Map of the pressure or the film thickness over the film.
source is a solved state or a field document. what is "p" (absolute
pressure, in MPa) or "h" (film thickness, in µm); gauge subtracts the
ambient pressure. The film is drawn in its own coordinates (mm,
degrees), seen from above, in the jet colour scale. colorbar=False
leaves the colour bar out, for one bar shared by several maps (the image
is ax.collections[-1]). Other keywords go to tripcolor. Returns the
axes. Raises ValueError for another what.
"""
grid, values, coords, label = _field(source, what, gauge)
if ax is None:
ax = _new_axes()
image = ax.tripcolor(grid, values, **{"cmap": "jet", "shading": "gouraud", **mesh})
if colorbar:
ax.figure.colorbar(image, ax=ax, label=label)
(x_name, x_unit), (y_name, y_unit) = coords
ax.set_xlabel(display.label(x_name, x_unit, coordinate=True))
ax.set_ylabel(display.label(y_name, y_unit, coordinate=True))
if x_unit == y_unit:
ax.set_aspect("equal")
return ax
[docs]
def plot_profile(
source,
what: str = "p",
ax=None,
*,
along: str | None = None,
at: float | None = None,
gauge: bool = False,
n: int = 201,
**line,
):
"""Pressure or film thickness along a straight line in the film coordinates.
source and what are as in plot_field. along names the film coordinate
that runs along the line (the first one by default: x of a pad, the
axial coordinate of a journal); at is the value of the other
coordinate, in SI units (m or rad), by default the middle of its range,
which is a diameter of a round pad. The line is drawn through n equally
spaced points over the range of the film and is interrupted where it
leaves the film. Other keywords go to matplotlib's plot. Returns the
axes. Raises ValueError if along is not a film coordinate.
"""
grid, values, coords, label = _field(source, what, gauge)
names = [name for name, _ in coords]
along = names[0] if along is None else along
if along not in names:
raise ValueError(f"along must be one of the film coordinates {names}")
k = names.index(along)
points = (grid.x, grid.y)
across_scale = display.unit(coords[1 - k][1], coordinate=True)["scale"]
if at is None:
across = 0.5 * (points[1 - k].min() + points[1 - k].max())
else:
across = at * across_scale
s = np.linspace(points[k].min(), points[k].max(), n)
profile = _along_line(points[k], points[1 - k], grid.triangles, values, s, across)
if ax is None:
ax = _new_axes()
ax.plot(s, profile, **line)
ax.set_xlabel(display.label(along, coords[k][1], coordinate=True))
ax.set_ylabel(label)
return ax
def _over(value, x) -> np.ndarray:
"""A number or a function of the film coordinates, at the points x."""
return np.broadcast_to(value(x) if callable(value) else value, x.shape[1:])
# the colours of plot_geometry: porous, and porous with gas supply
_POROUS, _SUPPLIED = "0.78", (0.55, 0.74, 0.9)
[docs]
def plot_geometry(film, ax=None, *, mesh: bool = True, legend: bool = True):
"""The film as the solver sees it, from above: mesh, feed and edges.
Shows what a result rests on before looking at the result:
- the elements of the mesh (mesh=False leaves their edges out);
- what is behind each element, in one of three colours: blue where the
restrictor is porous and the supply acts on its back, grey where it is
porous without supply behind it (the rest of the back of a restrictor
fed over a part of it, ``Porous.feed_area``), white where nothing
passes into the film (zero permeability, or a sealed face). An element
that the edge of such an area passes through takes the colour of most
of it. A film on a porous body is porous and grey: the body takes its
supply on faces of its own;
- the edges where the pressure is prescribed, each in its own colour,
with its name and absolute pressure (MPa) in the legend. An edge
without a colour is a symmetry line, with no flow across it.
film is a ``core.Film``, from any geometry builder. It is drawn in its own
coordinates (mm, degrees), so a journal is unrolled; a face meshed in
radius and angle (coordinates r and theta) is drawn as the disc it is.
legend=False leaves the legend below the axes out. Returns the axes.
"""
from matplotlib.collections import PolyCollection
from matplotlib.colors import ListedColormap
from matplotlib.patches import Patch
if ax is None:
ax = _new_axes()
# Points of the reference element, mapped to the film: its outline, with
# points along each edge so that a curved edge is drawn curved, and a few
# inside it at which the feed is sampled.
ref = reference_corners(film.basis)
polar = [name for name, _ in film.coords] == ["r", "theta"]
centre = ref.mean(axis=1, keepdims=True)
inside = np.concatenate([ref, centre, 0.5 * (ref + centre)], axis=1)
mapping = film.basis.mapping
# every edge without its last point, which is the first of the next edge
edges = element_edges(film.basis, 24 if polar else 6)[..., :-1]
outline = edges.reshape(2, edges.shape[1], -1).transpose(0, 2, 1)
points = mapping.F(inside).transpose(0, 2, 1)
units = [u for _, u in film.coords]
def shown(x):
"""Film coordinates as drawn: display units, a disc if polar."""
if polar:
r = display.shown(x[0], "m", coordinate=True)
return [r * np.cos(x[1]), r * np.sin(x[1])]
return [display.shown(v, u, coordinate=True) for v, u in zip(x, units)] # noqa: B905
# What is behind an element, sampled at its corners, its centre and the
# points half way between: porous where anything passes into the film,
# supplied where the supply also acts on the back there.
porous = film.porous
passes = _over(porous.kappa, points) / _over(porous.hp, points) > 0.0
if porous.face_seal is not None:
passes &= ~np.asarray(_over(porous.face_seal, points), dtype=bool)
supplied = passes
if getattr(film, "body", None) is not None:
# a porous body (porous_body.on_body) takes its supply on faces of its
# own, not on the back of the film face
supplied = np.zeros_like(passes)
elif porous.feed_area is not None:
supplied = passes & np.asarray(_over(porous.feed_area, points), dtype=bool)
# 0 nonporous, 1 porous, 2 porous with gas supply: most of the element
kind = np.where(
supplied.mean(axis=0) >= 0.5, 2, np.where(passes.mean(axis=0) >= 0.5, 1, 0)
)
polygons = np.stack(shown(outline), axis=-1).transpose(1, 0, 2)
ax.add_collection(
PolyCollection(
polygons,
array=kind,
cmap=ListedColormap(["white", _POROUS, _SUPPLIED]),
clim=(-0.5, 2.5),
edgecolors="0.45" if mesh else "face",
linewidths=0.2 if mesh else 0.0,
)
)
handles = [
Patch(facecolor=colour, edgecolor="0.45", label=label)
for value, colour, label in (
(2, _SUPPLIED, "porous, gas supply"),
(1, _POROUS, "porous"),
(0, "white", "nonporous"),
)
if np.any(kind == value)
]
for k, (name, (dofs, pressure)) in enumerate(film.boundaries.items()):
ex, ey = shown(film.basis.doflocs[:, np.asarray(dofs, dtype=int)])
shown_p = display.shown(pressure, "Pa")
label = f"{name}: {shown_p:.4g} {display.unit('Pa')['display']}"
(line,) = ax.plot(ex, ey, ".", ms=3, color=_EDGES[k % len(_EDGES)], label=label)
handles.append(line)
if polar:
ax.set_xlabel(display.label("x", "m", coordinate=True))
ax.set_ylabel(display.label("y", "m", coordinate=True))
else:
(x_name, x_unit), (y_name, y_unit) = film.coords
ax.set_xlabel(display.label(x_name, x_unit, coordinate=True))
ax.set_ylabel(display.label(y_name, y_unit, coordinate=True))
ax.autoscale_view()
if polar or units[0] == units[1]:
ax.set_aspect("equal")
if legend: # below the axes, so that it never covers the film
ax.legend(
handles=handles,
fontsize=7,
loc="upper center",
bbox_to_anchor=(0.5, 0.0),
borderaxespad=5.5, # in font sizes: clear of the axis label
ncols=min(3, len(handles)),
frameon=False,
)
return ax
def _along_line(u, v, t, values, s, v0: float) -> np.ndarray:
"""Values of a triangulated field at the points (s, v0); NaN outside it.
u and v are the coordinates of the points along and across the line and
t the triangles, shape (m, 3). The field is linear on each triangle.
"""
vt = v[t]
t = t[(vt.min(axis=1) <= v0) & (vt.max(axis=1) >= v0)] # the ones the line meets
out = np.full(len(s), np.nan)
if not len(t):
return out
(u0, u1, u2), (c0, c1, c2) = u[t].T, v[t].T
det = (c1 - c2) * (u0 - u2) + (u2 - u1) * (c0 - c2)
t, u0, u1, u2, c0, c1, c2, det = (
a[det != 0.0] for a in (t, u0, u1, u2, c0, c1, c2, det)
)
ds, dv = s[:, None] - u2, v0 - c2
w0 = ((c1 - c2) * ds + (u2 - u1) * dv) / det
w1 = ((c2 - c0) * ds + (u0 - u2) * dv) / det
weights = np.stack([w0, w1, 1.0 - w0 - w1], axis=-1) # (n, m, 3)
inside = weights.min(axis=-1) >= -1e-9
hit = inside.any(axis=1)
first = inside.argmax(axis=1)[hit]
out[hit] = np.sum(weights[hit, first] * values[t[first]], axis=1)
return out
[docs]
def plot_output(
result: dict,
output: str,
ax=None,
*,
x_axis: int = 0,
sign: float = 1.0,
label: str | None = None,
cases: list | None = None,
normalise=None,
x_normalise=None,
**line,
):
"""Plot one output of a study against a swept quantity, one line per case.
With two swept quantities, x_axis picks the one on the horizontal axis
and every value of the other one gets its own line. Values are shown in
display units, taken from the result. sign = -1 flips the output (a
restoring force plotted as positive), label replaces the axis label,
cases restricts the plot to the named cases, and any other keyword goes
to matplotlib's plot (color, linestyle, marker, ...). Returns the axes.
Raises ValueError for a result without a swept quantity, and if a case
lacks the output or none of the named cases is in the result.
normalise draws the output in a scheme of ``openairbearing.normalise``
instead of display units, and x_normalise the swept quantity on the
horizontal axis. Each is a function f(values, at) called once for every
drawn line, which returns a ``normalise.Normalised`` whose label becomes
the axis label with the unit [-]. values are the SI values of that line
(the output after sign, or the swept quantity), one per point along the
horizontal axis; at maps the path of every swept quantity ("position.h",
"ps", ...) to its SI value at each of those points, so a reference that
is itself swept is taken point by point. A scheme takes its reference
quantities explicitly, so bind the rest, for example:
plot_output(result, "stiffness.h.h", sign=-1.0,
normalise=lambda k, at: normalise.stiffness_over_gauge_supply(
k, gap=at["position.h"], ps=at.get("ps", ps), pa=pa,
area=area),
x_normalise=lambda h, at: normalise.feeding_parameter(
h, kappa=kappa, hp=hp, radius=radius))
Either may also be a dict from case name to such a function, for cases
whose reference quantities differ (another size); a plotted case missing
from it raises ValueError, and so do lines whose schemes give different
labels for the same axis. Left out, nothing changes: display units and
the labels of the result.
"""
axes = result["axes"]
if not axes:
raise ValueError("This result has no swept quantity to plot against.")
if ax is None:
ax = _new_axes()
x_info = axes[x_axis]
x_si = np.array(x_info["values"], dtype=float)
other = axes[1 - x_axis] if len(axes) == 2 else None
info = None
x_labels, y_labels = set(), set()
for case in result["cases"]:
if cases is not None and case["name"] not in cases:
continue
if output not in case["outputs"]:
raise ValueError(f"Case {case['name']!r} has no output {output!r}.")
info = case["outputs"][output]
y_si = sign * np.array(info["values"], dtype=float)
if other is None:
lines = [(case["name"], y_si, {x_info["path"]: x_si})]
else:
if x_axis == 1:
y_si = y_si.T # rows follow the horizontal axis
lines = []
for k, value in enumerate(other["values"]):
shown = value * other["scale"]
name = f"{case['name']}, {other['label']} {shown:g} {other['display']}"
at = {x_info["path"]: x_si,
other["path"]: np.full(x_si.shape, float(value))} # fmt: skip
lines.append((name, y_si[:, k], at))
for name, y_line, at in lines:
if normalise is None:
y = y_line * info["scale"]
y_labels.add(f"{info['label']} [{info['display']}]")
else:
y, y_label = _normalised(normalise, case["name"], y_line, at)
y_labels.add(y_label)
if x_normalise is None:
x = x_si * x_info["scale"]
x_labels.add(f"{x_info['label']} [{x_info['display']}]")
else:
x, x_label = _normalised(x_normalise, case["name"], x_si, at)
x_labels.add(x_label)
ax.plot(x, y, **{"label": name, **line})
if info is None:
raise ValueError("None of the named cases is in this result.")
for which, labels in (("horizontal", x_labels), ("vertical", y_labels)):
if len(labels) > 1:
raise ValueError(
f"The lines give different labels for the {which} axis, "
f"{sorted(labels)}: draw them on separate axes."
)
ax.set_xlabel(x_labels.pop())
ax.set_ylabel(label or y_labels.pop())
ax.legend()
return ax
def _normalised(scheme, case: str, values, at: dict):
"""Values and axis label of one line in a scheme (see plot_output)."""
result = _scheme(scheme, case)(values, at)
return np.asarray(result.values, dtype=float), f"{result.label} [-]"
def _scheme(scheme, case: str):
"""The normalisation of one case: scheme itself, or its entry for case."""
if not isinstance(scheme, dict):
return scheme
if case not in scheme:
raise ValueError(f"No normalisation is given for case {case!r}.")
return scheme[case]