Plot examples¶
Run the cells in order after installation. Code comes from the original notebook. Saved outputs are previews. Output paths are relative to the working directory.
The examples cover lines, prediction errors, scalar fields, surfaces and panel grids. Draw with Matplotlib, then finish and export with Hedgehogs.
Preamble¶
# Import plotting tools
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import hedgehogs as hdg
Figure configuration¶
# Set the figure size, palette and output directory
FIG_X, FIG_Y = hdg.figsize(name="science", column="single")
PALETTE = hdg.get_palette(palette="okabe-ito")
hdg.set_style(figsize=(FIG_X, FIG_Y), palette="okabe-ito")
FIGURE_DIR = Path.cwd() / "output" / "figures"
FIGURE_DIR.mkdir(parents=True, exist_ok=True)
Line plot¶
# Sample sine and cosine at the same phases
x = np.linspace(0, 2*np.pi, 200)
response = np.sin(x)
reference = np.cos(x)
# Compare the phase response
fig, ax = plt.subplots(figsize=(FIG_X, FIG_Y))
ax.plot(x, response, color=PALETTE["blue"], label="Sine")
ax.plot(x, reference, color=PALETTE["red"], label="Cosine")
ax.set(xlabel="Phase (rad)", ylabel="Response")
hdg.plots.grid(ax=ax, axis="y")
ax.legend(loc="best")
hdg.plots.save(FIGURE_DIR / "line_plot.pdf", fig=fig, dpi=300, transparent=True)
hdg.plots.show(fig=fig)

Prediction comparison¶
Data¶
# Generate paired sound-pressure measurements and predictions
# These synthetic data require no model training.
rng = np.random.default_rng(seed=42)
measured_spl = rng.uniform(105, 140, size=200)
linear_spl = measured_spl + rng.normal(0, 3.5, size=200)
dnn_spl = measured_spl + rng.normal(0, 1.6, size=200)
# Compare predictions with the ideal line
fig, ax = plt.subplots(figsize=(FIG_X * 2, FIG_Y * 2))
ax.scatter(measured_spl, linear_spl, s=14, alpha=0.6,
color=PALETTE["red"], label="Linear Regression")
ax.scatter(measured_spl, dnn_spl, s=14, alpha=0.6,
color=PALETTE["blue"], label="DNN")
limits = [
min(measured_spl.min(), linear_spl.min(), dnn_spl.min()),
max(measured_spl.max(), linear_spl.max(), dnn_spl.max()),
]
ax.plot(limits, limits, "--", color=PALETTE["black"], label="Ideal")
ax.set_title("Airfoil Self-Noise Prediction")
ax.set_xlabel("Measured Sound Pressure Level (dB)")
ax.set_ylabel("Predicted Sound Pressure Level (dB)")
ax.set_xlim(limits)
ax.set_ylim(limits)
hdg.plots.square()
hdg.plots.legend(placement="outside", loc="upper center", ncols=3, ax=ax)
hdg.plots.save(FIGURE_DIR / "prediction_comparison.png", fig=fig, dpi=300, transparent=True)
hdg.plots.show(fig=fig)

Prediction error¶
# Compare mean absolute prediction errors
mae = [
np.mean(np.abs(linear_spl - measured_spl)),
np.mean(np.abs(dnn_spl - measured_spl)),
]
fig, ax = plt.subplots(figsize=(FIG_X, FIG_Y))
bars = ax.bar(["Linear", "DNN"], mae, color=[PALETTE["red"], PALETTE["blue"]])
ax.bar_label(bars, fmt="%.2f")
ax.set_ylabel("MAE (dB)")
hdg.plots.save(FIGURE_DIR / "prediction_error.png", fig=fig, dpi=300, transparent=True)
hdg.plots.show(fig=fig)

Loss landscape¶
# Evaluate a synthetic loss field on a common grid
coordinates = np.linspace(0, 1, 150)
W1, W2 = np.meshgrid(coordinates, coordinates)
loss = (
2.8 * np.exp(-((W1 - 0.25)**2 / 0.04 + (W2 - 0.75)**2 / 0.05))
+ 3.2 * np.exp(-((W1 - 0.80)**2 / 0.06 + (W2 - 0.70)**2 / 0.04))
- 3.5 * np.exp(-((W1 - 0.40)**2 / 0.025 + (W2 - 0.25)**2 / 0.05))
- 1.5 * np.exp(-((W1 - 0.85)**2 / 0.04 + (W2 - 0.20)**2 / 0.06))
+ 0.4 * np.sin(2*np.pi*W1) * np.cos(2*np.pi*W2)
)
2D field¶
# Plot the loss field with a colour scale
fig, ax = plt.subplots(figsize=(FIG_X * 1.5, FIG_Y * 1.5))
image = ax.pcolormesh(W1, W2, loss, cmap="viridis", shading="auto",
vmin=-4, vmax=4, rasterized=True)
ax.set(xlabel=r"$w_1$", ylabel=r"$w_2$", xlim=(0, 1), ylim=(0, 1))
fig.colorbar(image, ax=ax, label=r"$J(\mathbf{w})$")
hdg.plots.square()
hdg.plots.save(FIGURE_DIR / "loss_landscape_2d.pdf", fig=fig, dpi=300, transparent=True)
hdg.plots.show(fig=fig)

3D surface¶
# View the loss surface in three dimensions
fig = plt.figure(figsize=(FIG_X * 2, FIG_Y * 2))
ax = fig.add_subplot(111, projection="3d")
ax.plot_surface(W1, W2, loss, cmap="viridis", vmin=-4, vmax=4,
rstride=2, cstride=2, linewidth=0.3, edgecolor=(0, 0, 0, 0.15))
ax.set_xlabel(r"$w_1$")
ax.set_ylabel(r"$w_2$")
ax.set_zlabel(r"$J(\mathbf{w})$")
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_zlim(-4, 4)
ax.view_init(elev=25, azim=-60)
ax.set_box_aspect((1, 1, 0.6))
hdg.plots.save(FIGURE_DIR / "loss_landscape_3d.png", fig=fig, dpi=300, transparent=True)
hdg.plots.show(fig=fig)

Shared legends and panel labels¶
# Generate binary outputs from linear decision boundaries
rng = np.random.default_rng(seed=42)
X1 = rng.uniform(0, 1, size=100)
X2 = rng.uniform(0, 1, size=100)
sum_X = X1 + X2
gates_data = {"AND": sum_X > 1.5, "OR": sum_X > 0.5, "NAND": sum_X < 1.5}
# Share the output legend across the logic gate panels
fig, axes = plt.subplots(
2, 2, figsize=(FIG_X * 2, FIG_Y * 2),
sharex=True, sharey=True,
)
axes[0, 0].scatter(X1, X2, color=PALETTE["black"], alpha=0.5)
for ax, y_pred in zip(axes.ravel()[1:], gates_data.values(), strict=True):
ax.scatter(X1[y_pred == 1], X2[y_pred == 1], color=PALETTE["blue"], label="1")
ax.scatter(X1[y_pred == 0], X2[y_pred == 0], color=PALETTE["red"], label="0")
axes[0, 0].set_ylabel(r"$x_2$")
axes[1, 0].set_xlabel(r"$x_1$")
axes[1, 0].set_ylabel(r"$x_2$")
axes[1, 1].set_xlabel(r"$x_1$")
hdg.plots.legend(title="Output", shared=True, loc="upper center", placement="outside", ncols=2, fig=fig)
hdg.plots.label(["Data", *gates_data], ax=axes, loc="lower left", halo=False, box=True)
hdg.plots.square()
hdg.plots.save(FIGURE_DIR / "logic_gates.png", fig=fig, dpi=300, bbox_inches="tight", transparent=True)
hdg.plots.show(fig=fig)

Fixed-aspect field comparison¶
# Build synthetic reaction fronts on a shared physical grid
x_mm = np.linspace(0, 22, 90)
z_mm = np.linspace(0, 3.4, 35)
x_grid_mm, z_grid_mm = np.meshgrid(x_mm, z_mm)
front_width_mm = 1.0
front_center_mm = 12 + 0.4 * np.cos(2.5 * z_grid_mm)
front_coordinates = [
(x_grid_mm - (front_center_mm + offset_mm)) / front_width_mm
for offset_mm in (0, 1, 2)
]
progress_fields = [1 / (1 + np.exp(-coordinate)) for coordinate in front_coordinates]
temperature_K = [300 + 1400 * progress for progress in progress_fields]
reaction_rate_per_s = [18000 * np.exp(-coordinate**2) for coordinate in front_coordinates]
# Compare the fronts at equal physical aspect on one color scale per row
# Focus on the reaction-front window and calculate color limits over the full fields.
fig, axes = plt.subplots(
2, 3, figsize=(FIG_X * 4.5, FIG_Y * 2.4),
sharex=True, sharey=True, layout="constrained",
)
cases = ("Reference", "Model A", "Model B")
fields = (
(temperature_K, "inferno", r"$T$ [K]"),
(reaction_rate_per_s, "magma", r"$\omega$ [s$^{-1}$]"),
)
for row_index, (sections, cmap, label) in enumerate(fields):
row = axes[row_index]
vmin = min(section.min() for section in sections)
vmax = max(section.max() for section in sections)
for ax, name, section, progress in zip(row, cases, sections, progress_fields, strict=True):
image = ax.pcolormesh(x_mm, z_mm, section, cmap=cmap, vmin=vmin, vmax=vmax)
ax.contour(x_mm, z_mm, progress, levels=[0.5], colors="cyan", linewidths=0.8)
ax.set_aspect("equal")
if row_index == 0:
ax.set_title(name)
else:
ax.set_xlabel(r"$x$ [mm]")
row[0].set_ylabel(r"$z$ [mm]")
fig.colorbar(image, ax=row, label=label)
axes[0, 0].set(xlim=(9, 17), ylim=(0, 3.4), xticks=(9, 11, 13, 15, 17))
fig.suptitle(r"Reaction-front window ($c=0.5$ in cyan)")
hdg.plots.save(FIGURE_DIR / "field_comparison.png", fig=fig)
hdg.plots.show(fig=fig)
